Plotly horizontal legend wrapping

Hi,

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

I have seen this discussed on plotly.js
https://github.com/plotly/plotly.js/pull/786/commits/919d8c8f81f5511c2ab7f8ee2e284a807c88d142https://github.com/plotly/plotly.js/pull/786/commits/919d8c8f81f5511c2ab7f8ee2e284a807c88d142

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.

Thanks
Dave

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)
2 Likes

Awesome, thanks so much @cpsievert