如何在分解的时间序列图中自定义标题,轴标签等

Pet*_*son 4 plot r time-series timeserieschart

我非常熟悉通过编写自己的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
Run Code Online (Sandbox Code Playgroud)

为您提供观察时间序列,趋势等的基本情况.根据我自己的数据(水面下方的深度变化),我希望能够切换y轴的方向(例如'观察'的ylim = c(40,0),'趋势'的ylim = c(18,12),将'季节'改为'潮汐',包括x轴的单位('时间(天)) '),并为该图提供更具描述性的标题.

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

有没有办法做到这一点?

谢谢!皮特

eip*_*i10 6

您可以修改plot.decomposed.ts函数(这是在plot运行plot类对象decomposed.ts(它的类td)时调度的"方法" .

getAnywhere(plot.decomposed.ts)
Run Code Online (Sandbox Code Playgroud)
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"), ...)
}
Run Code Online (Sandbox Code Playgroud)

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

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")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这是情节的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))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述