I would like to revert the order of the legend in a plotly graph.
This is an example of what I made :
df <- data.frame(trt = c("a", "b", "c"), outcome = c(2.3, 1.9, 3.2))
correct_order <- ggplot(df, aes(trt, outcome,fill = trt)) +
scale_fill_manual(guide = guide_legend(reverse = TRUE),
values = c("red","blue","green")) +
geom_col()
but the ggplotly output ton use the guide_legend(reverse = TRUE) see :
ggplotly(correct_order )
How can I revert the ordre in a ggplotly output ?
>Solution :
You can use this code:
library(ggplot2)
library(dplyr)
library(plotly)
df <- data.frame(trt = c("a", "b", "c"), outcome = c(2.3, 1.9, 3.2))
# reverse function
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
}
# Reversed order ggplotly
correct_order %>%
plotly::ggplotly() %>%
reverse_legend_labels()
Reversed legend output ggplotly:


