Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse the legend order when using ggplotly()

I would like to reverse the order of the legend for a horizontal bar chart. When adding guides(fill = guide_legend(reverse = TRUE)) to the ggplot it works fine (see second plot). However, after applying ggplotly() the legend is again in the default order.

How to reverse the order of the plotly legend without changing the order of the bars?

library(ggplot2)
library(dplyr)
data(mtcars)

p1 <- mtcars %>%
  count(cyl, am) %>%
  mutate(cyl = factor(cyl), am = factor(am)) %>%
  ggplot(aes(cyl, n, fill = am)) +
  geom_col(position = "dodge") +
  coord_flip()
p1


p2 <- p1 + guides(fill = guide_legend(reverse = TRUE))
p2

plotly::ggplotly(p2)

enter image description here

like image 339
Thomas Neitmann Avatar asked Feb 23 '26 20:02

Thomas Neitmann


1 Answers

Adding to the great answer of @Zac Garland here is a solution that works with legends of arbitrary length:

library(ggplot2)
library(dplyr)

reverse_legend_labels <- function(plotly_plot) {
  n_labels <- length(plotly_plot$x$data)
  plotly_plot$x$data[1:n_labels] <- plotly_plot$x$data[n_labels:1]
  plotly_plot
}

p1 <- mtcars %>%
  count(cyl, am) %>%
  mutate(cyl = factor(cyl), am = factor(am)) %>%
  ggplot(aes(cyl, n, fill = am)) +
  geom_col(position = "dodge") +
  coord_flip()

p2 <- mtcars %>%
  count(am, cyl) %>%
  mutate(cyl = factor(cyl), am = factor(am)) %>%
  ggplot(aes(am, n, fill = cyl)) +
  geom_col(position = "dodge") +
  coord_flip()
p1 %>%
  plotly::ggplotly() %>%
  reverse_legend_labels()

enter image description here

p2 %>%
  plotly::ggplotly() %>%
  reverse_legend_labels()

enter image description here

like image 162
Thomas Neitmann Avatar answered Feb 26 '26 11:02

Thomas Neitmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!