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

前端 未结 2 1774
渐次进展
渐次进展 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)
    

    0 讨论(0)
  • 2021-01-14 11:37
    library(plotly)
    library(shiny)
    library(htmlwidgets)
    
    js <- c(
      "function(el, x){",
      "  el.on('plotly_legendclick', function(evtData) {",
      "    Shiny.setInputValue('trace', evtData.data[evtData.curveNumber].name);",
      "  });",
      "}")
    
    
    ui <- fluidPage(
      plotlyOutput("plot"),
      verbatimTextOutput("legendItem")
    )
    
    server <- function(input, output, session) {
    
      output$plot <- renderPlotly({
        p <- plot_ly()
        for(name in c("drat", "wt", "qsec"))
        {
          p = add_markers(p, x = as.numeric(mtcars$cyl), y = as.numeric(mtcars[[name]]), name = name)
        }
        p %>% onRender(js)
      })
    
      output$legendItem <- renderPrint({
        d <- input$trace
        if (is.null(d)) "Clicked item appear here" else d
      })
    }
    
    shinyApp(ui, server)
    

    0 讨论(0)
提交回复
热议问题