我遇到了一个令人烦恼的问题,但一直没有找到具体的解决方案。我正在尝试创建水平分组的条形图;我想要的只是获取标准的垂直条形图并将其向右旋转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解决方案是否可行。
任何帮助将不胜感激!
答案 0 :(得分:5)
如果您熟悉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)