Подтвердить что ты не робот

Временные ряды и прогноз времени одновременно с использованием ggplot2

У меня есть временные ряды с данными прогноза и доверительного интервала, я хотел их построить, используя 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()

enter image description here

Как я могу присоединить верхнюю и нижнюю строки одного цвета? а также как я могу задать конкретные цвета для прогнозирования и выборки?

4b9b3361

Ответ 1

Используйте 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

изменить

Это еще один вариант, основанный на ответе @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

Ответ 2

Следующее может быть полезным:

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' может также использоваться в stat_smooth()