我有一个包含预测和置信区间数据的时间序列,我想使用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')
现在,我想在&#34;观察&#34;中加入一个传奇。和&#34; my_forecast&#34;。我尝试了
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'))
但它没有显示图例。
答案 0 :(得分:3)
您需要将colour
参数移至aes
以创建图例。
ggplot(df1, aes(x = time, y = M)) + geom_line(aes(colour = 'blue')) +
geom_smooth(aes(x = time, y = M, ymax = upper, ymin = lower, colour = 'red'),
data = df2, stat = 'identity') +
scale_colour_manual("", values = c("blue", "red"),
labels = c("observations", "my forecast"))