【发布时间】:2014-12-17 02:49:43
【问题描述】:
我有一个包含预测和置信区间数据的时间序列,我想使用 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)
在上一个问题中@Matthew Plourde 给了我一个不错的答案:
ggplot(df1, aes(x = time, y = M)) + geom_line(colour='blue') +
geom_smooth(aes(x=time, y=M, ymax=upper, ymin=lower),
colour='red', data=df2, stat='identity')
现在,我想包含一个带有“观察”和“my_forecast”的图例。我试过了
ggplot(df1, aes(x = time, y = M)) + geom_line(colour='blue') +
geom_smooth(aes(x=time, y=M, ymax=upper, ymin=lower),
colour='red', data=df2, stat='identity')+ scale_colour_manual(values=c(observations='blue', my_forecast='red'))
但它不显示图例。
【问题讨论】:
标签: r ggplot2 time-series