绘制时间序列为一年

时间:2017-12-08 09:08:42

标签: r plot time-series

我有10年的月度数据时间序列:

myts <- ts(rnorm(12*10), frequency = 12, start = 2001)

现在,我想绘制数据,但x轴限制在1月到12月(通用年份)的范围/刻度。因此,整个时间序列应该分成10行,其中每行从1月开始到12月结束。因此,多行应该相互叠加,我想用它来直观地比较不同的年份。是否有直接的命令在R中执行此操作?

到目前为止,我使用matplot提出了以下解决方案,这可能不是最复杂的解决方案:

mydf <- as.data.frame(matrix(myts, 12))
matplot(mydf,type="l")

Time series in one generic year

或者甚至更好的方法是计算每个月的平均值和相应的CI /标准偏差,然后绘制1月 - 12月的平均线作为线,相应的CI /标准差作为线周围的波段对于平均值。

1 个答案:

答案 0 :(得分:0)

考虑使用ggplot2

library(ggplot2)
library(ggfortify)
d <- fortify(myts)
d$year <- format(d$Index, "%Y")
d$month <- format(d$Index, "%m")

从将ts对象重新整形为长数据帧开始是有用的。鉴于数据框架,您可以直接创建您想要的图表:

ggplot(d, aes(x = month, y = Data, group = year, colour = year)) +
  geom_line()

ggplot(d, aes(x = month, y = Data, group = month)) +  
  stat_summary(fun.data = mean_se, fun.args = list(mult = 1.96))

结果: enter image description here

您也可以自己汇总数据,然后绘制它:

d_sum <- do.call(rbind, (lapply(split(d$Data, d$month), mean_se, mult = 1.96)))
d_sum$month <- rownames(d_sum)
ggplot(d_sum, aes(x = month, y = y, ymin = ymin, ymax = ymax)) +
  geom_errorbar() +
  geom_point() +
  geom_line(aes(x = as.numeric(month)))

结果: enter image description here

相关问题