r - 使用ggplot2绘制时间序列并同时进行预测

标签 r plot 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()

如何将一种颜色的上下线条连接起来?以及如何设置特定的颜色来进行预测和采样?

最佳答案

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

编辑

这是另一种选择,其灵感来自@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')

关于r - 使用ggplot2绘制时间序列并同时进行预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26042774/

相关文章:

r - 带R的点云覆盖的区域

r - R中图形的pdf中有难看的白线

r - 在google colab中安装 "TopicModels"包时出错

python - 如何基于相同的日期时间 x 轴同时绘制两个不同的数据框列

r - 在 Rstudio、knitr、Rmarkdown 中没有渲染的一些图

r - 如何在 R 中的 facet_grid 图上注释 R-sq 和 p-value?

r - 使用 ggplot2 和分组变量创建圆环图

r - 将一个单元格中的多个值分成多个单元格

python - 在图例中使用 pandas.DataFrame.plot 的临时标签

r - ggplot2 等高线图中的自定义级别?