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

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

提交回复
热议问题