我想使用ggplot2创建一个条形图,其中x轴的离散值将被分组为子组(请参见附加的图片 - 图片来自网络,我还没有绘制该图的代码)。
谢谢您的帮助!
两种方法:
示例数据:
dat <- data.frame(value=runif(26)*10,
grouping=c(rep("Group 1",10),
rep("Group 2",10),
rep("Group 3",6)),
letters=LETTERS[1:26])
head(dat)
value grouping letters
1 8.316451 Group 1 A
2 9.768578 Group 1 B
3 4.896294 Group 1 C
4 2.004545 Group 1 D
5 4.905058 Group 1 E
6 8.997713 Group 1 F
不使用分面:
ggplot(dat, aes(grouping, value, fill=letters, label = letters)) +
geom_bar(position="dodge", stat="identity") +
geom_text(position = position_dodge(width = 1), aes(x=grouping, y=0))
使用分面:
ggplot(dat, aes(letters,value, label = letters)) +
geom_bar(stat="identity") +
facet_wrap(~grouping, scales="free")
分面具有明显的优势,不必纠结于标签的位置。
facet_grid
函数,并加上参数 'space="free_x"'! - lqdo2000除此之外,还有ggh4x::guide_axis_nested()
这个替代方案,它解决了类似的问题。免责声明:我是ggh4x的作者。
library(ggplot2)
df <- data.frame(
x = LETTERS[1:16],
group = rep(c("Group 1", "Group 2", "Group 3"), c(5, 3, 8)),
value = rpois(16, 10)
)
ggplot(df, aes(paste0(x, "&", group), value)) +
geom_col() +
guides(x = ggh4x::guide_axis_nested(delim = "&"))
由 reprex package (v2.0.0) 创建于2023年2月24日
factor(paste(...), levels = ...)
来设置你想要的顺序的水平。 - teunbrand
facet_wrap
吗? - Gary Weissmanfacet_grid
来控制分面布局。 - Gary Weissmanfacet_grid
! - lqdo2000