【问题标题】:Plot time series and forecast simultaneously wtih legend using ggplot2使用 ggplot2 绘制时间序列并与图例同时进行预测
【发布时间】: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


    【解决方案1】:

    您需要将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"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-11
      • 2017-03-04
      • 2017-05-09
      • 2021-05-12
      • 2023-03-18
      • 1970-01-01
      • 2012-12-25
      • 2017-10-03
      相关资源
      最近更新 更多