如何在分解时间序列的图表中定制标题、轴标签等。

7

我比较熟悉通过编写自己的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),或对于“趋势”使用ylim=c(18,12)),将“季节性”更改为“潮汐性”,包括x轴单位(“时间(天)”),并为图形提供更详细描述的标题。

我的印象是,我正在进行的时间序列分析相当基础,最终可能会更好地使用另一个包,也许具有更好的图形控制,但我现在想尽量使用ts()和decompose()(是的,就像蛋糕和消耗)。假设这不会变得非常可怕。

有方法可以做到这一点吗?

谢谢! Pete

1个回答

12
您可以修改plot.decomposed.ts函数(这是在类为decomposed.ts的对象上运行plot时调度的plot“方法”(即td的类))。请注意,保留HTML标签。
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")

enter image description here

这是一个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))

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接