combine time series plot by using R

 ̄綄美尐妖づ 提交于 2021-02-11 17:55:38

问题


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

回答1:


Just put your time series inside a matrix:

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)

Or configure the plot region:

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

hope it helps.

PS.: zoo package is not needed in this example, you could use the filter function. You can extract the seasonal mean with:

s.mean = tapply(serie, cycle(serie), mean)
# January, assuming serie is monthly data
print(s.mean[1])



回答2:


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.

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

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

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

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

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

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

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


来源:https://stackoverflow.com/questions/14692234/combine-time-series-plot-by-using-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!