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

如何使用ggplot绘制含NA值的混合频率时间序列?

混合频率时间序列多序列ggplot绘制方案

无需依赖dualplot等专用混合频率绘图工具,使用ggplot原生功能即可实现3个混合频率序列的同步绘制,核心是处理好季度序列的NA值展示逻辑即可,以下是两种常用场景的实现代码:

单Y轴方案(三个序列量级相近时使用)

先将宽表数据转为ggplot适配的长表格式,分别处理月度、季度序列的绘图逻辑:

# 加载依赖包
library(tidyverse)

# 转为长表格式
x_long <- x %>% 
  pivot_longer(cols = starts_with("TS"),
               names_to = "series",
               values_to = "value")

# 绘图
ggplot() +
  # 绘制两个月度序列折线
  geom_line(data = filter(x_long, series %in% c("TS1", "TS2")),
            aes(x = Date, y = value, color = series)) +
  # 绘制季度序列连续折线(自动过滤NA实现连续展示)
  geom_line(data = filter(x_long, series == "TS3" & !is.na(value)),
            aes(x = Date, y = value, color = series), linewidth = 1) +
  # 为季度序列添加观测点标记,区分月度序列
  geom_point(data = filter(x_long, series == "TS3" & !is.na(value)),
            aes(x = Date, y = value, color = series), size = 2) +
  labs(x = "日期", y = "数值", color = "序列类型") +
  theme_minimal()

如果希望季度序列仅在季度节点展示、非季度节点断开折线,去掉filter中的!is.na(value)过滤条件即可,ggplot默认会在NA值处自动断开折线。

双Y轴方案(季度序列与月度序列量级差异大时使用)

将季度序列映射到右侧次Y轴,通过缩放系数适配两个Y轴的取值范围:

# 缩放系数需根据实际数据取值范围调整,保证展示效果合理
y_scaling_factor <- 2 

ggplot(x, aes(x = Date)) +
  # 左侧主Y轴对应两个月度序列
  geom_line(aes(y = TS1, color = "TS1")) +
  geom_line(aes(y = TS2, color = "TS2")) +
  # 右侧次Y轴对应季度序列,添加na.rm=T跳过NA值警告
  geom_line(aes(y = TS3 * y_scaling_factor, color = "TS3"), linewidth = 1, na.rm = T) +
  geom_point(aes(y = TS3 * y_scaling_factor, color = "TS3"), size = 2, na.rm = T) +
  # 配置双Y轴映射
  scale_y_continuous(
    name = "月度序列数值",
    sec.axis = sec_axis(~./y_scaling_factor, name = "季度序列TS3数值")
  ) +
  # 自定义序列配色
  scale_color_manual(values = c("TS1" = "#1f77b4", "TS2" = "#ff7f0e", "TS3" = "#2ca02c"),
                     name = "序列类型") +
  labs(x = "日期") +
  theme_minimal()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 03:45:02