2

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)
ismirsehregal
  • 30,045
  • 5
  • 31
  • 78
Sada93
  • 2,785
  • 1
  • 10
  • 21

2 Answers2

3

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; })}")
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
0

htmlwidgets::onRender isn't needed. We can simply use layout():

library(plotly)

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) %>% layout(legend = list(
  itemclick = FALSE,
  itemdoubleclick = FALSE,
  groupclick = FALSE
))

Run schema()and navigate:

object ► layout ► layoutAttributes ► legend ► itemclick

for more information on these parameters.

ismirsehregal
  • 30,045
  • 5
  • 31
  • 78