【问题标题】:How to customize title, axis labels, etc. in a plot of a decomposed time series如何在分解的时间序列图中自定义标题、轴标签等
【发布时间】:2025-12-05 10:25:01
【问题描述】:

我相当熟悉通过编写自己的 x 轴标签或主标题来修改绘图的常用方法,但是在绘制时间序列分解的结果时,我无法自定义输出。

例如,

library(TTR)
t <- ts(co2, frequency=12, start=1, deltat=1/12)
td <- decompose(t)
plot(td)
plot(td, main="Title Doesn't Work") # gets you an error message

为您提供观察到的时间序列、趋势等的漂亮基本图。但是,使用我自己的数据(水面以下的深度变化),我希望能够切换 y 的方向轴(例如 ylim=c(40,0) 表示 'observed',或 ylim=c(18,12) 表示 'trend'),将 'seasonal' 更改为 'tidal',包括 x 轴的单位('Time (days)'),并为该图提供更具描述性的标题。

我的印象是我正在做的那种时间序列分析是非常基本的,最终,我可能最好使用另一个包,也许有更好的图形控制,但我想使用 ts() 和decompose() 如果我现在可以的话(是的,蛋糕和消费)。假设这不会变得太可怕。

有没有办法做到这一点?

谢谢!皮特

【问题讨论】:

    标签: r plot time-series timeserieschart


    【解决方案1】:

    您可以修改plot.decomposed.ts 函数(即在decomposed.ts 类(td 的类)的对象上运行plot 时调度的plot“方法”。

    getAnywhere(plot.decomposed.ts)
    
    function (x, ...) 
    {
        xx <- x$x
        if (is.null(xx)) 
            xx <- with(x, if (type == "additive") 
                random + trend + seasonal
            else random * trend * seasonal)
        plot(cbind(observed = xx, trend = x$trend, seasonal = x$seasonal, random = x$random), 
             main = paste("Decomposition of", x$type, "time series"), ...)
    }
    

    请注意,在上面的代码中,该函数对标题进行了硬编码。所以让我们修改它,以便我们可以选择我们自己的标题:

    my_plot.decomposed.ts = function(x, title="", ...) {
      xx <- x$x
      if (is.null(xx)) 
        xx <- with(x, if (type == "additive") 
          random + trend + seasonal
          else random * trend * seasonal)
      plot(cbind(observed = xx, trend = x$trend, seasonal = x$seasonal, random = x$random), 
           main=title, ...)
    }
    
    my_plot.decomposed.ts(td, "My Title")
    

    这是情节的 ggplot 版本。 ggplot需要数据框,所以第一步是将分解后的时间序列变成数据框形式,然后绘制出来。

    library(tidyverse) # Includes the packages ggplot2 and tidyr, which we use below
    
    # Get the time values for the time series
    Time = attributes(co2)[[1]]
    Time = seq(Time[1],Time[2], length.out=(Time[2]-Time[1])*Time[3])
    
    # Convert td to data frame
    dat = cbind(Time, with(td, data.frame(Observed=x, Trend=trend, Seasonal=seasonal, Random=random)))
    
    ggplot(gather(dat, component, value, -Time), aes(Time, value)) +
      facet_grid(component ~ ., scales="free_y") +
      geom_line() +
      theme_bw() +
      labs(y=expression(CO[2]~(ppm)), x="Year") +
      ggtitle(expression(Decomposed~CO[2]~Time~Series)) +
      theme(plot.title=element_text(hjust=0.5))
    

    【讨论】: