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

11

我有一个时间序列的预测和置信区间数据,我想使用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()

在此输入图片描述

如何将上下行连接成一个颜色?还可以如何设置预测和样本的特定颜色?

2个回答

6
使用 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'))

输入图像描述

编辑

这是另一个选项,灵感来自@rnso的答案。

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

enter image description here


1
我真的很喜欢最后一个选项。请注意,对于我的模拟数据,df5 应该是 df2,upper_bound 应该是 upper,lower_bound 应该是 lower。这只是因为可能会有其他人感兴趣。谢谢 Matthew。 - Uzg
关于@rnso启发的选项,我想添加一个带有观测值和我的预测的图例。我使用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') +scale_colour_manual(values=c(observations='blue', my_forecast='red'))。它显示了没有图例的相同图形,请帮忙…… - Uzg
最好发布一个新问题。 - Matthew Plourde

6

Following may be useful:

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

图片描述

'method'选项也可以在stat_smooth()函数中使用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接