Search code examples
rggplotly

In ggplotly, how can deselect legend entries with code?


I am making a ggplotly plot that defines groups with different fill colors (group A or Group B).

library(ggplot2)
library(plotly)

data <- data.frame(x = c(1,2,3, 10, 11, 12),
                   y = c(1,2,3, 10, 11, 12), 
                   group = c(rep("A",3), rep("B",3)))
p <- ggplot(data, aes(x = x, y = y, fill = group))+
  geom_point()

ggplotly(p)

I want one of the levels to not show by default, as if I clicked the legend to hide the level.

How can I programmatically set the legend so the B group is deselected by default.


Solution

  • Inspired by this this question, you can modify each trace with the property visible = 'legendonly. As r2evans noted, it's not always simple to translate between plot_ly and ggplotly. This post shows how you might go about fixing a ggplotly object if that's what you already have, and it worked for me.

    gg <- ggplotly(p)
    gg <- plotly_build(gg) 
    gg$x$data[[2]]$visible <- 'legendonly'  
    
    gg