event when clicking a name in the legend of a plotly's graph in R Shiny

前端 未结 2 1775
渐次进展
渐次进展 2021-01-14 11:15

I want to display some information when the user click on the legend of a plotly graph. For example in the code below, if the user clicks on the \"drat\" name in the legend

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-14 11:23

    Just for the sake of completeness: The same can be done without additional JS using plotlyProxy:

    library(shiny)
    library(plotly)
    
    ui <- fluidPage(
      plotlyOutput("plot"),
      verbatimTextOutput("clickedLegendItem"),
      verbatimTextOutput("doubleclickedLegendItem")
    )
    
    server <- function(input, output, session) {
      
      output$plot <- renderPlotly({
        p <- plot_ly(source = "mySource")
        for(name in c("drat", "wt", "qsec"))
        {
          p = add_markers(p, x = as.numeric(mtcars$cyl), y = as.numeric(mtcars[[name]]), name = name)
        }
        p %>% event_register('plotly_legendclick') %>% event_register('plotly_legenddoubleclick')
      })
      
      myPlotlyProxy <- plotlyProxy("plot")
      
      legendClickEvents <- reactive({
        event_data(source = "mySource", "plotly_legendclick")
      })
      
      legendDoubleclickEvents <- reactive({
        event_data(source = "mySource", "plotly_legenddoubleclick")
      })
      
      output$clickedLegendItem <- renderPrint({
        clickedItem <- legendClickEvents()$name
        if (is.null(clickedItem)){"Clicked item appears here"} else {clickedItem}
      })
      
      output$doubleclickedLegendItem <- renderPrint({
        doubleclickedItem <- legendDoubleclickEvents()$name
        if (is.null(doubleclickedItem)){"Doubleclicked item appears here"} else {doubleclickedItem}
      })
    }
    
    shinyApp(ui, server)
    

提交回复
热议问题