Shadowing your ggplot lines. Forecasting confidence interval use case.

[This article was first published on R | TypeThePipe, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

R ggplot2 plot of the forecast(in red) and it's condidence intervals(in blue) using geom_ribbon function.

Yesterday I was asked to easily plot confidence intervals at ggplot2 chart. Then I came up with this shadowing ggplot2 feature called geom_ribbon().

It’s not a trivial issue as long as you need to gather your data in order to achieve a tidy format. When you already have this data frame, all you need is geom_ribbon().

By using the following commented code you are able to show not only your point estimated forecast but also its confidence or prediction intervals.

library(tidyverse)
huron <- data.frame(year = 1875:1972, 
 value = LakeHuron,
 std = runif(length(LakeHuron),0,1))

huron %>% 
 ggplot(aes(year, value)) + 
 geom_ribbon(aes(ymin = value - std,
 ymax = value + std), # shadowing cnf intervals
 fill = "steelblue2") + 
 geom_line(color = "firebrick",
 size = 1) # point estimate

For a multi-line plot, you should include the colour and group aesthetic as follows:

library(tidyverse)
huron <- data.frame(year = rep(1875:1972,2), 
 group = c(rep("a",98),rep("b",98)),
 value = c(LakeHuron, LakeHuron + 5),
 std = runif(length(LakeHuron)*2,0,1))

huron %>% 
 ggplot(aes(year, value, fill = group)) + 
 geom_ribbon(aes(ymin = value - std,
 ymax = value + std,
 group=group),
 fill = "steelblue2") + 
 geom_line(color = "firebrick", size = 1)

You can see related R visualizations and tips on TypeThePipe

To leave a comment for the author, please follow the link and comment on their blog: R | TypeThePipe.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)