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

如何用ggplot2绘制含均值标准误及数据点的分组柱状图?

解决方案:带均值、标准误与原始数据点的分组柱状图

步骤1:加载所需工具包

完成需求需要用到ggplot2绘图,dplyr做数据统计汇总:

library(ggplot2)
library(dplyr)

步骤2:计算分组统计量

先算出每个类别的均值和标准误(标准误计算公式:标准差÷样本量的平方根):

summary_df <- df %>%
  group_by(category) %>%
  summarize(
    mean_ratio = mean(ratio),
    se_ratio = sd(ratio)/sqrt(n())
  )

步骤3:绘制完整图表

用汇总数据画柱状图和误差棒,再叠加原始数据点:

ggplot() +
  # 绘制均值柱状图,用汇总后的数据避免原始数据导致的柱子异常
  geom_col(data = summary_df, aes(x = category, y = mean_ratio), fill = "#4287f5", width = 0.6) +
  # 添加标准误误差棒,设置横向宽度让图表更清晰
  geom_errorbar(data = summary_df, 
                aes(x = category, ymin = mean_ratio - se_ratio, ymax = mean_ratio + se_ratio),
                width = 0.2) +
  # 叠加原始数据点,用jitter避免点重叠,红色点更醒目
  geom_jitter(data = df, aes(x = category, y = ratio), 
              color = "#ff5252", size = 2, position = position_jitter(width = 0.15)) +
  # 设置图表标签和标题
  labs(title = "分组Ratio均值柱状图",
       x = "类别",
       y = "Ratio值") +
  # 使用简洁的主题风格
  theme_minimal()

关键提示

  • 不要用geom_bar()默认参数(默认统计计数),改用geom_col()直接绘制计算好的均值,这是解决基础柱状图异常的核心。
  • geom_jitter()的width参数可以调整点的分散程度,避免同组数据点重叠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 01:57:14