2

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.

itsMeInMiami
  • 2,324
  • 1
  • 13
  • 34
  • I googled `plotly hide legend entry` and found https://plot.ly/r/legend/#hiding-legend-entries. The fact that this is starting with `plot_ly` and not `ggplotly` should not make a difference. I find I don't like the approach, as it requires "wide" data (vice my preference for "long" data that makes most of these plots much simpler). Are you able to widen your data and exploit that technique? – r2evans Jul 29 '19 at 17:12
  • .. but it *does* make a difference, you're right. – r2evans Jul 29 '19 at 17:16
  • ... and I realize now that I was trying to remove just the legend, not hide the whole thing by-default. I'm out, I think DavidKlotz's answer is right. (Though now I know the ability to control line/legend presence with `...$showlegend` and `...$visible`.) – r2evans Jul 29 '19 at 17:34
  • It was news to me, too. We all learned something today! – David Klotz Jul 29 '19 at 17:39

1 Answers1

8

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
David Klotz
  • 2,401
  • 1
  • 7
  • 16