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

如何使用R ggplot绘制对照组与处理组并列的分组柱状图

修改方案

你当前代码输出分面图的原因是调用了facet_wrap(~treatment)语句,要实现同分类下对照组/处理组柱子并列,只需做两处调整:

  • 删除facet_wrap分面代码
  • 在aes()映射中添加fill = treatment,将处理分组映射为柱子填充色,让position = "dodge"参数识别需要并列的分组

完整可运行代码

library(ggplot2)
library(tibble)

# 示例数据
example <- tribble(
  ~treatment, ~categorical_var, ~n,
  "control",            "1",    10,
  "control",            "2",    12,
  "control",            "3",     7,
  "treatment",          "1",     14,
  "treatment",          "2",     5,
  "treatment",          "3",     11,
)

# 绘图代码
ggplot(example, aes(x = categorical_var, y = n, fill = treatment)) + 
  geom_col(position = "dodge")

注:geom_col()等价于geom_bar(stat = "identity"),是汇总值柱状图的更简洁写法。如果要保留原写法也可以替换为:

ggplot(example, aes(categorical_var, n, fill = treatment)) + 
  geom_bar(position="dodge",stat="identity")

可选美化

可以添加标签层自定义轴标题和图例名称:

ggplot(example, aes(x = categorical_var, y = n, fill = treatment)) + 
  geom_col(position = "dodge") +
  labs(x = "分类变量", y = "计数", fill = "实验分组")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:45:04