如何在R Shiny中从plotly_click中显示多个点?

时间:2016-07-27 15:05:05

标签: r shiny plotly

我在R Shiny中有一个情节剧情。我希望能够点击许多点并将它们显示在表格中。情节很好,我可以得到1个plotly_click(通过event_data())来显示在表格中。如何生成许多event_data点的向量。这是一些示例代码。我试图在d_save中保存事件。谢谢。

library(shiny)
library(plotly)

data1 <- data.frame(cbind(seq(1,1000,1),seq(1,1000,1)*5))
colnames(data1) <- c('index','data')
data_points <- data.frame(cbind(seq(1,1000,5),seq(1,1000,5)*5))
colnames(data_points) <- c('index','data')


ui <- fluidPage(
  plotlyOutput("plot1"),
  tableOutput("dataTable")
)

d_save <- vector()

server <- function(input, output, session) {

  # make plotly plot
  output$plot1 <- renderPlotly({
    p <- plot_ly(data1, x = data1$index, y = data1$data,mode = "lines")
    add_trace(p, x = data_points$index, y = data_points$data, mode = "markers")
  })

    # show table of stances 
    output$dataTable <- renderTable({
      d <- event_data("plotly_click")
      d_save <- c(d_save,d$pointNumber[2]+1)
      data.frame(d_save)
    })
}

shinyApp(ui, server)

1 个答案:

答案 0 :(得分:3)

这没有什么严重的错误,它从来没有得到回答,这很奇怪。这不是纯粹的情节(不使用ggplot)的坏例子。

我修理了:

  • d_save <- c(...)作业更改为d_save <<- c(...)(在此使用reactiveValues会更清晰。)
  • 将剧情调用更改为管道,这似乎允许某些设置继续进行(如type=scatter默认值) - 消除警告:
  

未指定任何跟踪类型:根据提供的信息,&#39;分散&#39;跟踪   似乎合适。

  • 修了一个&#34; off-by-one&#34; d_save任务中的索引错误。
  • 添加了一个layout(...)给它一个标题(这对很多东西很有用)。

结果代码:

library(shiny)
library(plotly)

data1 <- data.frame(cbind(seq(1,1000,1),seq(1,1000,1)*5))
colnames(data1) <- c('index','data')
data_points <- data.frame(cbind(seq(1,1000,5),seq(1,1000,5)*5))
colnames(data_points) <- c('index','data')

ui <- fluidPage(
  plotlyOutput("plot1"),
  tableOutput("dataTable")
)

d_save <- vector()

server <- function(input, output, session) {

  # make plotly plot
  output$plot1 <- renderPlotly({
    plot_ly(data1, x=data1$index, y=data1$data,mode = "lines") %>%
         add_trace(x = data_points$index, y=data_points$data, mode = "markers") %>%
         layout(title="Plotly_click Test")
  })

  # show table of point markers clicked on by number
  output$dataTable <- renderTable({
    d <- event_data("plotly_click")
    d_save <<- c(d_save,d$pointNumber[1]+1)
    data.frame(d_save)
  })
}
shinyApp(ui, server)

图片:

enter image description here