I would like to disable the plotly legend selection from the server side using the R Plotly. We see here that it is possible to achieve this on plotly javascript using the following,
gd.on('plotly_legendclick',function() { return false; })
Is there any way we can achieve this in R using event_register()
or event_data()
?
I found a hacky solution using CSS to disable the legend. However, if you have multiple different plots for the same output$gg
, the CSS code disables the legend for all plots.
Reprex:
The final goal, clicking on the legend below must not hide any of the points.
library(shiny)
library(plotly)
library(tidyverse)
ui <- fluidPage(
plotlyOutput("gg"),
verbatimTextOutput("click"),
verbatimTextOutput("doubleclick")
)
server <- function(input, output, session) {
output$gg <- renderPlotly({
p <- ggplot(mtcars, aes(wt, mpg, color = factor(cyl))) +
geom_point() +
facet_wrap(~vs)
ggplotly(p) %>%
event_register("plotly_legendclick") %>%
event_register("plotly_legenddoubleclick")
})
output$click <- renderPrint({
event_data("plotly_legendclick")
})
output$doubleclick <- renderPrint({
event_data("plotly_legenddoubleclick")
})
}
shinyApp(ui,server)
This is a job for htmlwidgets::onRender
:
library(plotly)
library(htmlwidgets)
x <- c(1:15)
y <- c(1:15)
w <- gl(3,5)
dat <- data.frame(x = x, y = y, w = w)
example <- ggplot(dat, aes(x = x, y = y, color = w)) + geom_line()
ggplotly(example) %>%
onRender("function(el,x){el.on('plotly_legendclick', function(){ return false; })}")