首页 > 解决方案 > Plotly and Shiny:是否可以将事件数据作为列表对象获取?

问题描述

问题:使用 plotly 和 shiny,是否可以一次提取一个 curveNumber、pointNumber、x 和 y 的列表?

示例(参见代码):通过单击每个条,p返回下方。是否可以在不首先单击绘图的情况下获取 x 值、pointNumbers 等列表?即c(4, 6, 8)的x-object,pointNumber对象c(0, 1, 2)

  curveNumber pointNumber x    y
1           0           2 8 15.1
  curveNumber pointNumber x        y
1           0           1 6 19.74286

示例代码

ui <- fluidPage(
    plotlyOutput("plot")
)

server <- function(input, output) {

    output$plot <- renderPlotly({
      mtcars %>%
            group_by(cyl) %>%
            summarise(m = mean(mpg)) %>%
            plot_ly(., x = ~cyl,
              y = ~m, source = "test_plot") %>%
            add_bars()
    })

    observe({
        p <- event_data("plotly_click", source = "test_plot")
        print(p)
    })

}

# Run the application
shinyApp(ui = ui, server = server)

标签: rshinyplotlydata-visualizationshiny-reactivity

解决方案


不确定你想要什么。你可以得到xand ywith plotly_build,见下文。而且pointNumber只是0,...,length(x)-1

p <- mtcars %>%
  group_by(cyl) %>%
  summarise(m = mean(mpg)) %>%
  plot_ly(., x = ~cyl,
          y = ~m, source = "test_plot") %>%
  add_bars() 

pp <- plotly_build(p)
curves <- pp$x$data
curveNumber <- 0
dat <- curves[[curveNumber+1]]
as.vector(dat$x)
# [1] 4 6 8
as.vector(dat$y)
# [1] 26.66364 19.74286 15.10000

推荐阅读