繁体   English   中英

使用 ggplotly() 时反转图例顺序

[英]Reverse the legend order when using ggplotly()

我想颠倒水平条形图的图例顺序。 当添加guides(fill = guide_legend(reverse = TRUE))ggplot正常工作(见第二个图)。 但是,在应用ggplotly() ,图例再次处于默认顺序。

如何在改变条形顺序的情况下反转plotly图例的顺序?

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)

在此处输入图片说明

当您调用 ggplotly 时,它实际上只是在该列表上创建一个列表和一个函数调用。

因此,如果您保存该中间步骤,则可以直接修改列表。 因此,修改绘图输出。

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

html_plot <- ggplotly(p1)

replace_1 <- html_plot[["x"]][["data"]][[2]]
replace_2 <- html_plot[["x"]][["data"]][[1]]
html_plot[["x"]][["data"]][[1]] <- replace_1
html_plot[["x"]][["data"]][[2]] <- replace_2

html_plot

绘图输出

除了@Zac Garland 的精彩答案之外,还有一个适用于任意长度图例的解决方案:

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

在此处输入图片说明

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

在此处输入图片说明

一个简单的解决方案是定义因子变量am的级别顺序:

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


df <-  mtcars %>%
  count(cyl, am) %>%
  mutate(cyl = factor(cyl), am = factor(as.character(am), levels = c("1", "0"))) 

head(df)


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

在此处输入图片说明

plotly::ggplotly(p1)

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM