gpt4 book ai didi

r - 在 coord_flip 之后翻转分组条形图中数据的顺序

转载 作者:行者123 更新时间:2023-12-04 12:21:51 25 4
gpt4 key购买 nike

我一直有一个烦人的问题,我无法找到具体的解决方案。我正在尝试创建一个水平分组条形图;我想要的只是采用标准的垂直条形图并将其向右旋转 90 度。当我使用 coord_flip 时,它会将绘图向右旋转,但会翻转(反转)每组中数据的顺序。下面是一个例子:

library("ggplot2")

df <- data.frame(Group = c("A","A","A","B","B","B","C","C","C"),
Sub = c("1","2","3","1","2","3","1","2","3"),
Score = c(1,2,3,1,2,3,1,2,3))

df$Group <- factor(df$Group,
levels = c("A","B","C"),
labels = c("A","B","C"),
ordered = TRUE)

df$Sub <- factor(df$Sub,
levels = c("1","2","3"),
labels = c("1","2","3"),
ordered = TRUE)

ggplot(data = df, aes(x = Group, y = Score, fill = Sub)) +
geom_bar(stat="identity", position=position_dodge()) +
coord_flip() +
scale_x_discrete(limits = rev(levels(df$Group)))

我可以使用以下方法按正确的顺序获取组:
scale_x_discrete(limits = rev(levels(df$Group)))

但是,我无法使每个组中的顺序正确。图例和数据彼此相反,在这种情况下,我想更改绘制数据的顺序,而不是图例的顺序。

我已经看到您可以通过将条形图的位置闪避设置为 -.9 来解决该问题,如下所示:
geom_bar(stat="identity", position=position_dodge(-.9))

鉴于我的分组变量是字符串,我不确定提出的解决方案 here会工作。

任何帮助将不胜感激!

最佳答案

如果您熟悉 forcats包裹,fct_rev()在绘图时反转因子水平非常方便,并且在翻转坐标之前可以轻松反转图例顺序/颜色映射以匹配原始版本:

library(forcats)
library(ggplot2)

# unflipped version
p1 <- ggplot(data = df,
aes(x = Group, y = Score, fill = Sub)) +
geom_col(position="dodge") #geom_col is equivalent to geom_bar(stat = "identity")

# flipped version
p2 <- ggplot(data = df,
aes(x = fct_rev(Group), y = Score, fill = fct_rev(Sub))) +
geom_col(position="dodge") +
coord_flip() +
scale_fill_viridis_d(breaks = rev, direction = -1)

gridExtra::grid.arrange(p1, p2, nrow = 1)

plot comparison

关于r - 在 coord_flip 之后翻转分组条形图中数据的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52509050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com