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

如何缩放时间序列乘法分解autoplot的数据与趋势组件单位?

仅缩放时间序列乘法分解中数据与趋势组件的单位

要实现仅缩放乘法分解中的数据和趋势组件单位,同时保留季节性、残差组件的原始刻度,可通过以下两种可靠方法实现:

方法1:手动构建数据框 + 精准控制面板刻度(推荐)

这种方法灵活性最高,能完全自定义每个面板的轴刻度,依赖ggh4x包实现面板级刻度配置:

  1. 执行乘法分解并整理数据为长格式:
library(tidyverse)
library(forecast)
library(scales)
library(ggh4x)

# 对co2数据放大1000倍后执行乘法分解
decomp_result <- decompose(co2 * 1000, type = "multiplicative")

# 将分解结果转换为适合ggplot的长格式数据框
decomp_df <- tibble(
  date = time(decomp_result$x),  # 提取时间轴
  Data = decomp_result$x,        # 原始数据
  Trend = decomp_result$trend,   # 趋势组件
  Seasonal = decomp_result$seasonal,  # 季节性因子
  Residuals = decomp_result$random    # 残差因子
) %>%
  pivot_longer(cols = -date, names_to = "Component", values_to = "Value")
  1. 为指定面板设置专属刻度:
ggplot(decomp_df, aes(x = date, y = Value)) +
  geom_line(color = "#2c3e50") +
  # 按组件分面板,开启y轴独立缩放
  facet_wrap(~Component, scales = "free_y", ncol = 1) +
  # 为不同面板单独配置y轴刻度
  facetted_pos_scales(
    y = list(
      Component == "Data" ~ scale_y_continuous(labels = unit_format(unit = "K", scale = 1e-3)),
      Component == "Trend" ~ scale_y_continuous(labels = unit_format(unit = "K", scale = 1e-3)),
      # 季节性和残差保留原始刻度
      Component == "Seasonal" ~ scale_y_continuous(),
      Component == "Residuals" ~ scale_y_continuous()
    )
  ) +
  labs(x = "日期", y = "") +
  theme_minimal()

方法2:修改分解结果后使用forecast::autoplot

如果偏好使用forecast包自带的绘图函数,可先修改分解结果中的数据和趋势组件,再结合自由y轴实现需求:

library(forecast)
library(scales)

# 执行乘法分解
decomp_result <- decompose(co2 * 1000, type = "multiplicative")

# 仅缩放数据和趋势组件(转换为千单位)
decomp_result$x <- decomp_result$x / 1000
decomp_result$trend <- decomp_result$trend / 1000

# 绘图时为指定面板添加单位标签
autoplot(decomp_result) +
  scale_y_continuous(labels = function(y) {
    # 识别当前面板,仅对数据/趋势应用K单位
    panel <- as.character(current.panel()$row)
    if (panel %in% c("Data", "Trend")) {
      paste0(y, " K")
    } else {
      y
    }
  }) +
  facet_wrap(~Series, scales = "free_y", ncol = 1)

关键说明

乘法分解的季节性和残差是乘法因子(通常在1附近波动),修改其刻度会破坏因子的实际意义,因此必须保留原始数值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 17:07:07