简体   繁体   中英

Plot time series and forecast simultaneously wtih legend using ggplot2

I have a time series with forecast and confidence interval data, I wanted to plot them simultaneously with a legend 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)

In a previous question @Matthew Plourde suggested me a nice answer:

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

在此处输入图片说明

Now, I wanted to include a legend with "observations" and "my_forecast". I tryed with

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

but it doesn't display a legend.

You need to move the colour parameters into aes to create a legend.

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM