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

如何在R的ggplot中拟合多条类别均值水平线并显示均值

在ggplot中为不同产品类别添加对应均值水平线并显示数值

先准备示例数据和初始绘图

假设你的数据集结构如下,我们先模拟一个可复现的例子:

set.seed(123)
df <- data.frame(
  product = rep(c("A", "B", "C"), each = 50),
  value = c(rnorm(50, 10, 2), rnorm(50, 15, 3), rnorm(50, 8, 1.5))
)

# 初始散点绘图
library(ggplot2)
ggplot(df, aes(x = product, y = value)) +
  geom_jitter(width = 0.2, alpha = 0.6)

问题1:确保水平线对应对应类别的均值

有两种直观的实现方式:

方法1:提前计算均值数据集

先单独算出每个product的均值,再基于这个数据集绘制水平线,逻辑最清晰:

# 计算每个产品的均值
mean_df <- aggregate(value ~ product, df, mean)

# 绘制带均值线的图
ggplot(df, aes(x = product, y = value)) +
  geom_jitter(width = 0.2, alpha = 0.6) +
  # 用均值数据集映射截距和颜色,确保每条线匹配对应产品
  geom_hline(data = mean_df, aes(yintercept = value, color = product), 
             linetype = "dashed", linewidth = 1)

方法2:用stat_summary自动计算均值

无需提前生成均值数据集,直接让ggplot按组自动计算均值并绘制水平线:

ggplot(df, aes(x = product, y = value)) +
  geom_jitter(width = 0.2, alpha = 0.6) +
  stat_summary(
    fun = mean, 
    geom = "hline", 
    aes(color = product), 
    yintercept = ..y..,  # 用..y..获取每组的均值作为截距
    linetype = "dashed", 
    linewidth = 1
  )

问题2:显示均值的具体数值

方式1:在水平线上方标注数值

结合提前计算的均值数据集,用geom_text添加文本标注:

ggplot(df, aes(x = product, y = value)) +
  geom_jitter(width = 0.2, alpha = 0.6) +
  geom_hline(data = mean_df, aes(yintercept = value, color = product), 
             linetype = "dashed", linewidth = 1) +
  # 在均值线上方0.5个单位处标注保留两位小数的均值
  geom_text(
    data = mean_df, 
    aes(x = product, y = value + 0.5, label = round(value, 2)),
    color = "black", 
    fontface = "bold"
  )

如果用stat_summary的话,也可以直接添加文本层:

ggplot(df, aes(x = product, y = value)) +
  geom_jitter(width = 0.2, alpha = 0.6) +
  stat_summary(fun = mean, geom = "hline", aes(color = product), 
               yintercept = ..y.., linetype = "dashed", linewidth = 1) +
  stat_summary(
    fun = mean, 
    geom = "text", 
    aes(label = round(..y.., 2)),
    y = ..y.. + 0.5,  # 调整文本位置避免遮挡散点
    fontface = "bold"
  )

方式2:在图例中显示均值数值

修改图例标签,把产品名称和对应均值合并展示:

# 给均值数据集添加带均值的标签列
mean_df$product_with_mean <- paste0(mean_df$product, " (均值: ", round(mean_df$value, 2), ")")

ggplot(df, aes(x = product, y = value)) +
  geom_jitter(width = 0.2, alpha = 0.6) +
  geom_hline(data = mean_df, aes(yintercept = value, color = product_with_mean), 
             linetype = "dashed", linewidth = 1) +
  labs(color = "产品类别及均值")  # 自定义图例标题

内容的提问来源于stack exchange,提问作者Joe the Second

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 00:17:20