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

如何在R语言ggplot折线图中添加自定义模型标签?

解决ggplot折线图添加标签的问题

你的代码报错是因为geom_text默认会使用主数据集Auto,但你传入的label只有3个元素,和Auto的行数不匹配,导致长度冲突。下面提供两种可行的解决方案:

方法一:用annotate手动指定标签位置

适合快速给单条折线加标签,需要先确定每条折线的标注位置(比如选择horsepower最大的点):

# 获取horsepower最大值对应的位置
max_hp <- max(Auto$horsepower)
max_hp_idx <- which(Auto$horsepower == max_hp)

# 提取各模型在该位置的拟合值
model1_y <- fitted(lm_mpg_1)[max_hp_idx]
model2_y <- fitted(lm_mpg_2)[max_hp_idx]
model3_y <- fitted(lm_mpg_3)[max_hp_idx]

# 添加标签到原图表
p1 +
  annotate("text", x = max_hp, y = model1_y, label = "model_1", color = "blue", hjust = -0.1) +
  annotate("text", x = max_hp, y = model2_y, label = "model_2", color = "red", hjust = -0.1) +
  annotate("text", x = max_hp, y = model3_y, label = "model_3", color = "darkgreen", hjust = -0.1)

hjust = -0.1是让标签在折线点的右侧,避免和线条重叠,可根据需要调整。

方法二:整理数据为tidy格式(推荐)

这种方式更符合ggplot的设计逻辑,后续修改或添加模型更方便:

# 加载tidyr包用于数据整理(如果没安装先运行install.packages("tidyr"))
library(tidyr)

# 把三个模型的拟合结果整理成 tidy 格式
fit_data <- data.frame(
  horsepower = Auto$horsepower,
  model_1 = fitted(lm_mpg_1),
  model_2 = fitted(lm_mpg_2),
  model_3 = fitted(lm_mpg_3)
) %>%
  pivot_longer(cols = -horsepower, names_to = "model", values_to = "mpg_fit")

# 重新绘制图表并添加标签
ggplot(data = Auto, aes(x = horsepower, y = mpg)) +
  geom_point() +
  # 用分组映射绘制折线
  geom_line(data = fit_data, aes(y = mpg_fit, color = model), size = 1) +
  # 指定各模型的颜色
  scale_color_manual(values = c("model_1" = "blue", "model_2" = "red", "model_3" = "darkgreen")) +
  # 在每条折线的最后一个点添加标签
  geom_text(data = fit_data %>% 
              group_by(model) %>% 
              filter(horsepower == max(horsepower)),
            aes(y = mpg_fit, label = model, color = model), 
            hjust = -0.1, size = 4)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:35:22