使用 R 组合时间序列图 [英] combine time series plot by using R

查看:59
本文介绍了使用 R 组合时间序列图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wanna combine three graphics on one graph. The data from inside of R which is " nottem ". Can someone help me to write code to put a seasonal mean and harmonic (cosine model) and its time series plots together by using different colors? I already wrote model code just don't know how to combine them together to compare.

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)))

推荐答案

这张图很难读懂,因为你的三组值太相似了.不过,如果您只想将所有这些都绘制在样本图上,您可以使用模型生成的系数轻松完成.

This graph is pretty hard to read, because your three sets of values are so similar. Still, if you want to simply want to graph all of these on the sample plot, you can do it pretty easily by using the coefficients generated by your models.

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

Step 1: Plot the raw data. This comes from your original code.

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

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

Step 2: Set up x-values for the mean and cosine plots.

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

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

Step 3: Plot the seasonal means by repeating the coefficients from the first model.

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

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

Step 4: Calculate the y-values for the cosine function using the coefficients from the second model, and then plot.

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

ggplot 变体:如果您决定为您的情节切换到流行的ggplot2"包,您可以这样做:

ggplot variant: If you decide to switch to the popular 'ggplot2' package for your plot, you would do it like so:

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()

这篇关于使用 R 组合时间序列图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆