ggplot2:将x轴离散值分组到子组中

lqd*_*000 6 grouping r ggplot2

我想创建一个带有ggplot2的条形图,其中x轴的离散值将被分组为子组(参见附图 - 图片来自网络我还没有绘图的代码).

在此输入图像描述

谢谢你的帮助 !

Bra*_*sen 9

两种方法:

示例数据:

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
Run Code Online (Sandbox Code Playgroud)

没有分面:

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))
Run Code Online (Sandbox Code Playgroud)

用facetting:

ggplot(dat, aes(letters,value, label = letters)) + 
     geom_bar(stat="identity") + 
     facet_wrap(~grouping, scales="free")
Run Code Online (Sandbox Code Playgroud)

刻面具有明显的优点,即不必对标签的定位进行捣乱.

  • 如何在 y 轴上使用离散的非数字值执行此操作? (3认同)
  • 找到了。我将`facet_grid`与参数'space =“ free_x”`一起使用! (2认同)

teu*_*and 8

为了提供替代方案,还有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 = "&"))
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v2.0.0)于 2023-02-24 创建