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
opened 04:15PM - 22 Jul 16 UTC
closed 09:49PM - 02 Aug 16 UTC
type: feature
type: community
Was pointed out in #766 that scrolling not intended for `layout.legend.orientati… on = 'h'`. Example workaround is to use [legend groups](https://github.com/plotly/plotly.js/blob/master/test/image/mocks/legend_horizontal_groups.json).
This is not a great solution, however, as it means clicking the legend group hides/shows ALL traces in the group (see [jsfiddle](https://jsfiddle.net/psalmody/c9x3xzg9/)).
Proposing that plotly.js implement something similar to ggplot2 which automatically wraps additional legend items on horizontal legend orientation. Especially on mobile portrait orientation, this allows the graph data to take up the entire width of the screen and push the legend below the graph which is much preferable in my view.

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