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

双站点多年份差异采样数据时间序列图及回归直线绘制咨询

嘿,我来帮你搞定这个需求!针对你两个站点跨年度且采样年份不同的时间序列数据,我们可以用ggplot2一步步实现带折线连接和回归趋势线的可视化,下面是具体的代码和细节说明:

1. 先复现你的数据(确保演示一致)

首先我们先把你提供的示例数据跑起来,顺便加个随机种子让结果可重复:

set.seed(123) # 固定随机数,方便你复现效果
df <- data.frame( 
  year= c(seq(1997,2016,1), seq(2001,2017,1)), 
  site= c(rep("cr", 20),rep("ec", 17)), 
  mean= sample(1:50,37)
)

2. 绘制基础类时间序列折线图

用ggplot2的geom_line()和geom_point()组合,就能实现同站点数据点的折线连接——因为两个站点的年份范围不重叠,ggplot会自动只连接同站点内的年份点,不会出现跨站点的错误连线:

library(ggplot2)

# 初始化基础绘图对象
base_plot <- ggplot(df, aes(x = year, y = mean, color = site)) +
  geom_point(size = 2) + # 突出显示每个采样数据点
  geom_line(linewidth = 1) + # 用折线连接同站点的时间序列点
  labs(x = "年份", y = "Mean值", color = "站点") +
  theme_minimal() # 用简洁的主题风格

print(base_plot)

3. 叠加回归趋势线

接下来给每个站点添加专属的线性回归趋势线,用geom_smooth()指定method = "lm"就能实现,还可以通过样式区分原始折线和趋势线:

# 在基础图上叠加回归趋势线
trend_plot <- base_plot +
  geom_smooth(
    method = "lm", # 指定用线性回归拟合趋势
    se = FALSE, # 关闭置信区间(需要的话改成TRUE即可)
    linetype = "dashed", # 用虚线表示趋势线,和实线原始折线区分
    linewidth = 1
  )

print(trend_plot)

如果想要让趋势线覆盖整个时间跨度(比如从1997到2017),可以加上xlim()扩展坐标轴范围,不过回归计算还是基于各自站点的采样数据:

trend_plot + xlim(1997, 2017)

4. 可选的图表优化

如果想让图表更美观清晰,可以做这些调整:

  • 自定义站点颜色,让区分度更高
  • 调整年份刻度的显示间隔
  • 添加居中的标题和副标题

完整优化后的代码:

ggplot(df, aes(x = year, y = mean, color = site)) +
  geom_point(size = 2) +
  geom_line(linewidth = 1) +
  geom_smooth(method = "lm", se = FALSE, linetype = "dashed", linewidth = 1) +
  # 自定义站点颜色
  scale_color_manual(values = c("cr" = "#2E8B57", "ec" = "#FF6347")) +
  # 每2年显示一个年份刻度,避免拥挤
  scale_x_continuous(breaks = seq(1997,2017,2)) +
  # 设置标签和标题
  labs(
    x = "年份", 
    y = "Mean值", 
    color = "站点",
    title = "不同站点Mean值的时间序列趋势",
    subtitle = "1997-2017年"
  ) +
  theme_minimal() +
  # 让标题和副标题居中
  theme(
    plot.title = element_text(hjust = 0.5),
    plot.subtitle = element_text(hjust = 0.5)
  )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:00:45