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

如何使用ggplot2包绘制指定参考样式的统计图表

ggplot2 分组带误差棒显著性柱状图实现方案

参考素材

  • 目标效果图:目标绘制效果
  • 参考数据结构:参考数据集样例

实现思路

  • 数据预处理:将宽格式的原始数据转换为ggplot2适配的长格式,按「分组+指标」维度聚合计算均值、标准误,用于绘制柱高和误差棒
  • 图层顺序:先绘制分组柱状图主体,再叠加误差棒图层,最后添加组间显著性标记
  • 细节适配:调整柱形间距、误差棒宽度、配色方案,搭配简洁主题匹配目标图样式

可运行R代码示例

# 加载依赖包
library(ggplot2)
library(ggsignif)
library(tidyr)
library(dplyr)

# ---------------
# 以下为模拟测试数据,实际使用时替换为你自己的数据集即可,数据结构和参考截图一致
set.seed(123)
raw_df <- data.frame(
  group = rep(c("对照组", "处理组1", "处理组2"), each = 20),
  指标A = c(rnorm(20, 10, 2), rnorm(20, 15, 2.5), rnorm(20, 12, 1.8)),
  指标B = c(rnorm(20, 8, 1.5), rnorm(20, 13, 2), rnorm(20, 18, 2.2))
)
# ---------------

# 数据格式转换与统计量计算
plot_df <- raw_df %>%
  pivot_longer(cols = -group, names_to = "indicator", values_to = "value") %>%
  group_by(group, indicator) %>%
  summarise(
    mean_val = mean(value),
    se_val = sd(value)/sqrt(n()), # 计算标准误做误差棒,也可根据需求替换为标准差、置信区间
    .groups = "drop"
  )

# 核心绘图代码
ggplot(plot_df, aes(x = group, y = mean_val, fill = indicator)) +
  # 分组柱状图主体
  geom_col(position = position_dodge(width = 0.8), width = 0.7, color = "black") +
  # 误差棒
  geom_errorbar(
    aes(ymin = mean_val - se_val, ymax = mean_val + se_val),
    position = position_dodge(width = 0.8), width = 0.2, linewidth = 0.6
  ) +
  # 显著性标记,y_position、标注内容根据你实际的统计检验结果调整即可
  geom_signif(
    y_position = c(17, 20, 22),
    xmin = c(0.8, 1.8, 2.8),
    xmax = c(1.2, 2.2, 3.2),
    annotation = c("p<0.01", "p>0.05", "p<0.001"),
    tip_length = 0.01,
    textsize = 3.5,
    position = position_dodge(width = 0.8)
  ) +
  # 配色调整
  scale_fill_brewer(palette = "Set1") +
  # 标签设置
  labs(x = "实验分组", y = "指标检测值", fill = "检测指标") +
  # 主题调整
  theme_classic() +
  theme(
    legend.position = "top",
    axis.text = element_text(color = "black", size = 11),
    axis.title = element_text(size = 12)
  )

代码说明:运行前请先通过install.packages(c("ggplot2","ggsignif","tidyr","dplyr"))安装缺失的依赖包;显著性标记的位置、标注内容请根据你实际做的统计检验结果修改对应参数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.31 20:48:46