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

ggplot分面绘图:如何使各子图仅显示对应模型的均值水平线?

分面绘图时仅显示对应子图的均值水平线

问题场景

现有两组模型准确率数据,需要绘制每个模型的准确率曲线,并在对应分面子图中仅显示该模型的均值水平线。当前代码运行后,两个子图都会同时显示两条均值线,不符合需求。

原始数据定义:

x1 <- c(0.6800000, 0.6634863, 0.6534353, 0.6596089, 0.6636000)
x2 <- c(0.6866667, 0.6973262, 0.6894212, 0.6892579, 0.6829512)
x1_mean <- mean(x1)
x2_mean <- mean(x2)

构建的数据集:

test01 <- data.frame('count' = 1:5, 'model' = c(rep('x1',5), rep('x2', 5)), 'accuracy' = c(x1, x2), 'mean' = c(x1_mean, x2_mean))

当前绘图代码:

ggplot(test01, aes(x = count, y = accuracy, color = model)) +
  geom_line(mapping = aes(x = count, y = accuracy)) +
  geom_point(mapping = aes(x = count, y = accuracy)) +
  geom_hline(aes(yintercept = mean)) +
  facet_grid(~model)

当前绘图效果:
绘图效果展示

问题原因

test01数据集中,每个模型的5行数据里,mean列同时包含了x1和x2的均值,geom_hline会遍历所有行的均值并绘制,导致每个分面都出现两条线。

解决方法

方法1:单独构建均值数据集

创建只包含每个模型对应均值的小数据集,传给geom_hline,让分面只匹配对应模型的均值:

# 构建仅含模型与对应均值的数据集
mean_df <- data.frame(
  model = c("x1", "x2"),
  mean_val = c(x1_mean, x2_mean)
)

# 重新绘图
ggplot(test01, aes(x = count, y = accuracy, color = model)) +
  geom_line() +  # 可省略重复的mapping,继承全局aes
  geom_point() +
  geom_hline(data = mean_df, aes(yintercept = mean_val)) +
  facet_grid(~model)

方法2:通过group绑定均值与模型

在geom_hline的aes中添加group = model,让均值线与模型分组绑定,分面时只显示对应组的线:

ggplot(test01, aes(x = count, y = accuracy, color = model)) +
  geom_line() +
  geom_point() +
  geom_hline(aes(yintercept = mean, group = model)) +
  facet_grid(~model)

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

无需提前计算均值,直接用stat_summary在绘图时计算并绘制对应分面的均值线,更简洁:

ggplot(test01, aes(x = count, y = accuracy, color = model)) +
  geom_line() +
  geom_point() +
  stat_summary(fun = mean, geom = "hline", aes(yintercept = after_stat(y))) +
  facet_grid(~model)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 04:32:41