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
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)