Plotly horizontal legend wrapping




I am having trouble making making plotly horizontal legends wrap in R.

I have seen this discussed on plotly.js

You will note if you use the below code, the legend does not wrap. You can see this by making your browser window small.

Any help much appreciated.


df <- iris %>% 
  group_by(Species) %>% 
  summarise(Sepal.Length = mean(Sepal.Length)) %>% 
  mutate(Species = paste0(Species, "_blahblahblahblah"))

plot <- ggplot(df) +
  geom_col(aes(x = 1, y = Sepal.Length, fill = Species))

plotly::ggplotly(plot) %>% 
  layout(legend = list(orientation = "h",  xanchor = "center", x = 0.5, y = -0.1))


As this comment indicates, plotly.js does "linebreak" horizontal legend items by default, but for some reason, it doesn't currently work when the legendgroup attribute is used. Currently all ggplotly() graphs with leverage this attribute (you can double-check that via plotly_json()), but I think it's only really needed for faceted charts. Anyway, for this simple example, you could "fix" it this way:

ggplotly(plot) %>%
    layout(legend = list(orientation = "h", xanchor = "center", x = 0.5, y = -0.1)) %>% 
    style(legendgroup = NULL)


Awesome, thanks so much @cpsievert