You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用R的ggplot2绘制带有序因子和单柱标签的分组条形图

方案1:仅用基础ggplot2实现(无需额外安装包)

通过调整柱子间距参数即可满足全部需求:

library(ggplot2)

# 构造数据
pizza = data.frame(
  person = c("john", "jim", "alice", "amy"), 
  pizzas_eaten  = c(2, 3, 4, 5),
  gender = c("male", "male", "female", "female")
)
# 保留指定的人员排序规则
pizza$person = factor(pizza$person, ordered = TRUE, levels = c("john", "jim", "alice", "amy"))

# 绘图代码
ggplot(pizza, aes(x = person, y = pizzas_eaten, fill = person)) +
  geom_col(
    width = 0.9, 
    position = position_dodge2(
      padding = c(0, 1, 0) # 第1、3个间隙为0(同组紧挨),第2个间隙为1(组间留空)
    )
  ) +
  labs(x = "人员", y = "食用披萨数量", fill = "人员") +
  # 可自定义每个柱子的独有配色
  scale_fill_manual(values = c("john" = "#F8766D", "jim" = "#7CAE00", "alice" = "#00BFC4", "amy" = "#C77CFF"))

方案2:使用ggh4x包实现嵌套分组轴(支持显示性别分组标签)

如果需要同时在x轴展示人员标签和性别分组标识,推荐使用该方案:

# 首次使用先安装依赖包
# install.packages("ggh4x")
library(ggplot2)
library(ggh4x)

ggplot(pizza, aes(x = interaction(gender, person, lex.order = TRUE), y = pizzas_eaten, fill = person)) +
  geom_col(width = 0.9) +
  scale_x_discrete(
    # 保留每个柱子的人员标签
    labels = ~ sub(".*\\.", "", .x),
    # 配置嵌套分组轴,自动生成分组间隙和性别标签
    guide = guide_axis_nested(
      delim = "\\.",
      extend = unit(0.5, "cm")
    )
  ) +
  labs(x = "人员", y = "食用披萨数量", fill = "人员") +
  scale_fill_manual(values = c("john" = "#F8766D", "jim" = "#7CAE00", "alice" = "#00BFC4", "amy" = "#C77CFF")) +
  theme(
    axis.ticks.length.x = unit(0.5, "cm"),
    ggh4x.axis.nesttext.x = element_text(hjust = 0.5)
  )

两种方案均满足全部要求:

  • 柱子完全按照指定的人员因子顺序排列
  • 男性组、女性组内部柱子紧挨,两组之间存在明显间隙
  • 每个柱子下方显示对应人员名称,且每个柱子有独立的唯一配色

内容的提问来源于stack exchange,提问作者verybadatthis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 14:36:03