Home > other >  How to make a legend appear on plotly but not plot the associated points
How to make a legend appear on plotly but not plot the associated points

Time:11-20

I have a plot and I would only like to render the legend but none of the plot points. Can anyone tell me how to do this?

library(tidyverse)
library(plotly)

mtcars %>% 
  mutate(cyl = factor(cyl)) %>% 
  plot_ly() %>% 
  add_markers(x = ~mpg,
              y = ~hp,
              color = ~cyl,
              colors = c("4" = "red", "6" = "green", "8" = "blue"))

Currently I have this:

enter image description here

What I want is this:

enter image description here

CodePudding user response:

Not sure what this result should be good for, but you can disable legendclick's like this:

Edit: also possible without onRender

library(plotly)
mtcars %>% 
  mutate(cyl = factor(cyl)) %>% 
  plot_ly() %>% 
  add_markers(x = ~mpg,
              y = ~hp,
              color = ~cyl,
              colors = c("4" = "red", "6" = "green", "8" = "blue"), visible='legendonly') %>%
  layout(legend=list(itemclick = FALSE, itemdoubleclick = FALSE)) 

library(htmlwidgets)
library(plotly)

js <- c(
  "function(el, x){",
  "  el.on('plotly_legendclick', function() {",
  "    return false;",
  "  });",
  "  el.on('plotly_legenddoubleclick', function() {",
  "    return false;",
  "  });",
  "}")

mtcars %>% 
  mutate(cyl = factor(cyl)) %>% 
  plot_ly() %>% 
  add_markers(x = ~mpg,
              y = ~hp,
              color = ~cyl,
              colors = c("4" = "red", "6" = "green", "8" = "blue"), visible='legendonly') %>%
  onRender(js)
  • Related