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

如何用ggplot2添加趋势线并区分时间序列点线图例

实现时间序列点线与趋势线图例分离,并指定趋势线颜色与线型

以下是满足需求的修改后代码,既可以给min/mean/max分别设置蓝、黑、红虚线趋势线,还能将时间序列的点线图例和趋势线图例完全分开:

library(ggplot2)
library(latex2exp)

year <- c(2000, 2001, 2002, 2003, 2004, 2005, 2006,
          2000, 2001, 2002, 2003, 2004, 2005, 2006,
          2000, 2001, 2002, 2003, 2004, 2005, 2006)

temp <- c(5, 8, 7, 5, 10, 13, 8, 
          10, 12, 11, 8, 14, 17, 10, 
          20, 18, 23, 25, 21, 28, 30)

type <- factor(c(rep("min",7), rep("mean",7), rep("max",7)))

series <- data.frame(year = year, temp = temp, type = type)

ggplot(series, aes(x = year, y = temp, group = type)) +
  # 绘制时间序列的线与点
  geom_line(aes(color = type)) +
  geom_point(aes(color = type)) +
  # 绘制趋势线:匹配对应序列颜色,设置为虚线,不加入默认颜色图例
  geom_smooth(aes(color = type), formula = y ~ x, method = lm, se = FALSE, 
              linetype = "dashed", show.legend = FALSE) +
  # 定义时间序列的颜色映射与图例名称
  scale_color_manual(values = c("min" = "blue", "mean" = "black", "max" = "red"),
                     name = "时间序列") +
  # 创建趋势线专属图例,统一设置为虚线
  scale_linetype_manual(values = rep("dashed", 3),
                        name = "趋势线",
                        labels = levels(type)) +
  # 调整趋势线图例的颜色,与对应序列保持一致
  guides(linetype = guide_legend(override.aes = list(color = c("blue", "black", "red")))) +
  xlim(2000, 2006) +
  labs(x = "Year",
       y = TeX("Temperatura"))

关键修改说明

  • 趋势线与时间序列使用相同的color = type映射,确保颜色一一对应;同时给趋势线设置show.legend = FALSE,避免和点线图例合并
  • 通过scale_linetype_manual单独创建趋势线图例,指定所有趋势线为虚线,并设置图例名称
  • 利用guides手动覆盖趋势线图例的颜色属性,让图例中的虚线颜色和对应序列保持一致
  • 两个图例分别命名为“时间序列”和“趋势线”,实现完全分离展示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 00:13:15