R 使用ggplot2同时绘制时间序列和预测

R 使用ggplot2同时绘制时间序列和预测,r,plot,ggplot2,R,Plot,Ggplot2,我有一个带有预测和置信区间数据的时间序列,我想用ggplot2同时绘制它们。我是按照下面的代码来做的: 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 da

我有一个带有预测和置信区间数据的时间序列,我想用ggplot2同时绘制它们。我是按照下面的代码来做的:

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()
set.seed(321)
图书馆(GG2)
#创建一些类似于我的虚拟数据

样本使用
比例颜色手册

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

编辑

这是另一个选项,灵感来自@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')

以下内容可能有用:

ggplot() + 
  geom_line(data=df1, aes(x = time, y = M, color = isin)) + 
  stat_smooth(data=df2, aes(x = time, y = M, color = isin))


“方法”选项也可以用于stat_smooth()

我非常喜欢最后一个选项。考虑到df5应该是df2,我的模拟数据的上限应该是上限,下限应该是下限。只是因为别人可能对你感兴趣。谢谢Matthew。关于@rnso激发的选项,我想添加一个带有观察和我的预测的传奇。我使用ggplot(df1,aes(x=time,y=M))+geom_线(color='blue')+geom_平滑(aes(x=time,y=M,ymax=upper_bound,ymin=lower_bound),color='red',data=df5,stat='identity')+scale_color_手册(values=c(观测值='blue',我的预测值='red))。它在没有传奇的情况下展示了同一个情节,没有任何帮助……最好发布一个新问题。