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

如何在R的ggplot中为各组添加a1与a3的均值回归线?

解决方案

你可以通过两种方式实现每个组连接a1和a3队列均值的线条:

方法一:直接使用stat_summary添加线条层

在现有代码基础上,新增一个stat_summary层指定geom="line",同时确保group映射正确(让ggplot识别同一组的两个均值点并连线):

ggplot(df_acc_score, aes(x = cohort, y = score, color = group, group = group))+
  geom_hline(yintercept = 5, color = "grey")+
  stat_summary(fun = "mean", geom = "point", size = 2)+  # 调大尺寸让均值点更明显
  stat_summary(fun = "mean", geom = "line")+
  theme_bw()+
  theme(strip.background = element_blank())+
  ylab("Mean accuracy score")+
  xlab("Cohort")

方法二:先计算均值再绘图(更直观可控)

先通过分组计算每个group和cohort的均值,再用geom_point和geom_line绘图:

# 计算均值数据框
library(dplyr)
df_mean <- df_acc_score %>%
  group_by(group, cohort) %>%
  summarise(mean_score = mean(score), .groups = "drop")

# 绘图
ggplot(df_mean, aes(x = cohort, y = mean_score, color = group))+
  geom_hline(yintercept = 5, color = "grey")+
  geom_point(size = 2)+
  geom_line()+
  theme_bw()+
  theme(strip.background = element_blank())+
  ylab("Mean accuracy score")+
  xlab("Cohort")

两种方法都能实现需求:方法一无需提前处理数据,直接用ggplot的统计函数完成;方法二先明确计算均值,后续对数据调整更灵活。另外建议把均值点的size调大(比如2),原代码的size=0.1会导致点几乎不可见。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 08:06:03