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

如何使用ggplot绘制两个变量的时间序列折线图

实现方案

你已经完成了数据整理,只需要按照ggplot的语法调整即可,以下是两种常用实现方式:

方案1:转换为长格式绘图(更推荐,自动生成图例、维护更方便)

先加载所需包,完成数据格式转换后绘图:

# 加载依赖包
library(ggplot2)
library(tidyr)

# 宽表转长表
Ydet.obs_long <- pivot_longer(Ydet.obs, 
                              cols = c(Ydet, Yobs),
                              names_to = "指标",
                              values_to = "数值")

# 绘制折线图
ggplot(Ydet.obs_long, aes(x = Date, y = 数值, color = 指标, group = 指标)) +
  geom_line(linewidth = 1) +
  labs(x = "日期", y = "数值") +
  theme_bw()

方案2:宽表直接绘图(无需格式转换)

如果不想额外做数据转换,可以分别指定两个折线的映射规则:

library(ggplot2)

ggplot(Ydet.obs, aes(x = Date)) +
  geom_line(aes(y = Ydet, color = "Ydet"), linewidth = 1) +
  geom_line(aes(y = Yobs, color = "Yobs"), linewidth = 1) +
  labs(x = "日期", y = "数值", color = "指标") +
  theme_bw()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 13:27:03