0

我想在一张图上组合三个图形。来自 R 内部的数据,即“nottem”。有人可以帮助我编写代码以使用不同的颜色将季节性均值和谐波(余弦模型)及其时间序列图放在一起吗?我已经编写了模型代码,只是不知道如何将它们组合在一起进行比较。

Code :library(TSA)
  nottem
  month.=season(nottem)
  model=lm(nottem~month.-1)
  summary(nottem)
  har.=harmonic(nottem,1)
  model1=lm(nottem~har.)
  summary(model1)
plot(nottem,type="l",ylab="Average monthly temperature at Nottingham castle") 
points(y=nottem,x=time(nottem), pch=as.vector(season(nottem)))
4

2 回答 2

1

该图很难阅读,因为您的三组值非常相似。尽管如此,如果您只想在样本图上绘制所有这些图形,您可以使用模型生成的系数轻松完成。

第 1 步:绘制原始数据。这来自您的原始代码。

plot(nottem,type="l",ylab="Average monthly temperature at Nottingham castle") 

第 2 步:为均值图和余弦图设置 x 值。

x <- seq(1920, (1940 - 1/12), by=1/12)

第 3 步:通过重复第一个模型的系数来绘制季节性均值。

lines(x=x, y=rep(model$coefficients, 20), col="blue")

第 4 步:使用来自第二个模型的系数计算余弦函数的 y 值,然后绘图。

y <- model1$coefficients[2] * cos(2 * pi * x) + model1$coefficients[1]
lines(x=x, y=y, col="red")

ggplot 变体:如果您决定为您的绘图切换到流行的“ggplot2”包,您可以这样做:

x <- seq(1920, (1940 - 1/12), by=1/12)
y.seas.mean <- rep(model$coefficients, 20)
y.har.cos <- model1$coefficients[2] * cos(2 * pi * x) + model1$coefficients[1]

plot_Data <- melt(data.frame(x=x, temp=nottem, seas.mean=y.seas.mean, har.cos=y.har.cos), id="x")
ggplot(plot_Data, aes(x=x, y=value, col=variable)) + geom_line()
于 2013-02-04T18:19:37.943 回答
1

只需将您的时间序列放入矩阵中:

x = cbind(serie1 = ts(cumsum(rnorm(100)), freq = 12, start = c(2013, 2)),
serie2 = ts(cumsum(rnorm(100)), freq = 12, start = c(2013, 2)))

plot(x)

或者配置绘图区域:

par(mfrow = c(2, 1)) # 2 rows, 1 column
serie1 = ts(cumsum(rnorm(100)), freq = 12, start = c(2013, 2))
serie2 = ts(cumsum(rnorm(100)), freq = 12, start = c(2013, 2))

require(zoo) 
plot(serie1)
lines(rollapply(serie1, width = 10, FUN = mean), col = 'red')
plot(serie2)
lines(rollapply(serie2, width = 10, FUN = mean), col = 'blue')

希望能帮助到你。

PS.:本例中不需要zoo包,可以使用filter功能。您可以使用以下方法提取季节性平均值

s.mean = tapply(serie, cycle(serie), mean)
# January, assuming serie is monthly data
print(s.mean[1])
于 2013-02-04T17:52:40.833 回答