Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

change guide_legend order in ggplotly

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()

This is the ggplot2 output
This is the ggplot2 output

but the ggplotly output ton use the guide_legend(reverse = TRUE) see :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ggplotly(correct_order )

enter image description here

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:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading