在geom_bar中显示排序值

esbemjvw  于 2023-06-03  发布在  其他
关注(0)|答案(1)|浏览(185)

我尝试使用geom_bar以排序的方式绘制值,但当我添加更多条件时,事情变得混乱。我是这样开始的:

library(ggplot2)

ggplot(dummy, aes(y = Value, x = reorder(Index, Value))) + 
geom_bar(stat = "identity") +
coord_flip() +
theme(axis.title.y = element_blank(), axis.ticks.y = element_blank(), axis.text.y = element_blank()) +
ylim(c(-1,1))

它很好地生成了这个:

然后,我想用不同的颜色为不同的组着色,所以我在aes中添加了fill = Group:

ggplot(dummy, aes(y = Value, x = reorder(Index, Value), fill = Group)) +
geom_bar(stat = "identity") +
coord_flip() +
theme(axis.title.y = element_blank(), axis.ticks.y = element_blank(), axis.text.y = element_blank()) +
ylim(c(-1,1))

它起作用了:

但后来...我想使用facet_wrap(~Condition)在两个单独的面板中显示它。代码如下:

ggplot(dummy, aes(y = Value, x = reorder(Index, Value), fill = Group)) +
geom_bar(stat = "identity") +
coord_flip() +
theme(axis.title.y = element_blank(), axis.ticks.y = element_blank(), axis.text.y = element_blank()) +
ylim(c(-1,1)) + 
facet_wrap(~Condition)

结果就是这样:

如何解决此问题?我要它们一个一个叠起来,没有空格...
下面是生成我的 Dataframe 的代码:

structure(list(Index = structure(1:30, .Label = c("1", "2", "3", 
"4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", 
"16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", 
"27", "28", "29", "30"), class = "factor"), Group = c("A", "A", 
"A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", 
"B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", 
"B", "B"), Condition = c("Easy", "Hard", "Easy", "Hard", "Easy", 
"Hard", "Easy", "Hard", "Easy", "Hard", "Easy", "Hard", "Easy", 
"Hard", "Easy", "Hard", "Easy", "Hard", "Easy", "Hard", "Easy", 
"Hard", "Easy", "Hard", "Easy", "Hard", "Easy", "Hard", "Easy", 
"Hard"), Value = c(-0.75, -0.44, -0.27, 0.49, 0.04, 0.74, -0.95, 
-0.59, 0.73, 0.93, -0.29, -0.47, -0.01, -0.65, -0.02, 0.32, -0.56, 
-0.66, 0.95, -0.13, -0.42, -0.25, -0.07, 0.06, 0.46, -0.74, -0.25, 
-0.37, -0.82, 0.86)), row.names = c(NA, 30L), class = "data.frame")

谢谢!

u3r8eeie

u3r8eeie1#

facet_wrap中有一个scale参数,将其设置为free_y,以在不同的小平面部分中具有独立的缩放。

library(ggplot2)

ggplot(dummy, aes(y = Value, x = reorder(Index, Value), fill = Group)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  theme(axis.title.y = element_blank(), axis.ticks.y = element_blank(), axis.text.y = element_blank()) +
  ylim(c(-1,1)) + 
  facet_wrap(~Condition, scale = "free_y")

相关问题