12

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

## ggplot object 
ggplot(df, aes(x = time, y = M, color = isin)) + geom_line()

enter image description here

How can I join upper and lower lines in one color? and also how can I set specific colors to forecast and sample?

2 Answers 2

7

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

enter image description here

edit

This is another option, inspired by @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')

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

I really like the last option. Take in account that df5 should be df2, upper_bound should be upper and lower_bound should be lower for my simulated data. Just because somebody else could be interested in. Thanks Matthew.
About the option inspire by @rnso, I wanted to add a legend with observations and my_forecoast. I use 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')). It dislayed the same plot without a legend, any help...
best to post a new question.
7

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

enter image description here

'method' option can also be used in stat_smooth()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.