使用ggplot2同时绘制时间序列和预测 [英] Plot time series and forecast simultaneously using ggplot2
本文介绍了使用ggplot2同时绘制时间序列和预测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个预测和置信区间数据的时间序列,我想用ggplot2同时绘制它们。我是这样做的:
set.seed(321)
library(ggplot2)
#创建类似于我的一些虚拟数据
样本< -rnorm(350)
forecast< -rnorm(24)
upper< -forecast + 2 * sd(forecast )
lower <-forecast-2 * sd(预测)
##将数据包装到data.frame中
df1 = data.frame(time = seq (325,350,长度= 26),M =样本[325:350],isin =观测值)b $ b df2 = data.frame(时间= seq(351,374,长度= 24),M =预测,isin = my_forecast)
df3 = data.frame(time = seq(351,374,length = 24),M = upper,isin =upper_bound)
df4 = data.frame(time = seq(351,374 ,长度= 24),M =低,isin =lower_bound)
df = rbind(df1,df2,df3,df4)
## ggplot object
ggplot df,aes(x = time,y = M,color = isin))+ geom_line()
如何加入upper并在一个c下线的olor?我怎样才能设置特定的颜色来预测和采样?
解决方案使用
scale_colour_manual(values = c(observations ='blue',my_forecast ='red',upper_bound ='black',lower_bound ='black'))
pre>
$ b 编辑
scale_colour_manual
$ b $ pre $ g $ pggplot(df,aes(x = time,y = M,color = isin))+ geom_line )+ scale_colour_manual(values = c(observations ='blue',my_forecast ='red',upper_bound ='black',lower_bound ='black'))
pre>
$ b 编辑
这是另一个选项,受@rnso answer的启发。 b
$ b
ggplot(df1,aes(x = time,y = M))+ geom_line(color ='blue')+
geom_smooth aes(x = time,y = M,ymax = upper_bound,ymin = lower_bound),
color ='red',data = df5,stat ='identity')
p>
I have a time series with forecast and confidence interval data, I wanted to plot them simultaneously using ggplot2. I'm doing it by the code below:
set.seed(321)
library(ggplot2)
#create some dummy data similar to mine
sample<-rnorm(350)
forecast<-rnorm(24)
upper<-forecast+2*sd(forecast)
lower<-forecast-2*sd(forecast)
## wrap data into a data.frame
df1 = data.frame(time = seq(325,350,length=26), M = sample[325:350], isin = "observations")
df2 = data.frame(time = seq(351,374,length=24), M = forecast , isin = "my_forecast")
df3 = data.frame(time = seq(351,374,length=24), M = upper ,isin = "upper_bound")
df4 = data.frame(time = seq(351,374,length=24), M = lower, isin = "lower_bound")
df = rbind(df1, df2, df3, df4)
## ggplot object
ggplot(df, aes(x = time, y = M, color = isin)) + geom_line()
How can I join upper and lower lines in one color? and also how can I set specific colors to forecast and sample?
解决方案
Use scale_colour_manual
:
ggplot(df, aes(x = time, y = M, color = isin)) + geom_line() +
scale_colour_manual(values=c(observations='blue', my_forecast='red', upper_bound='black', lower_bound='black'))
edit
This is another option, inspired by @rnso answer.
ggplot(df1, aes(x = time, y = M)) + geom_line(colour='blue') +
geom_smooth(aes(x=time, y=M, ymax=upper_bound, ymin=lower_bound),
colour='red', data=df5, stat='identity')
这篇关于使用ggplot2同时绘制时间序列和预测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文