MacroChair
MacroChair

Reputation: 77

How to add geom_rect to geom_line plot

I am plotting a time series of returns and would like to use NBER recession dating to shade recessions, like FRED graphs do.

The recession variable is in the same data frame and is a 1, 0 variable for: 1 = Recession, 0 = Expansion.

The idea is to use geom_rect and alpha = (Recession == 1) to shade the areas where Recession == 1.

The code for the gg_plot is below. Thanks for the help!

ERVALUEplot <- ggplot(data = Alldata)+
  geom_line(aes(x = Date, y = ERVALUE), color = 'red')+ 
  geom_rect(aes(x = Date, alpha = (Alldata$Recession ==1)), color = 'grey')

Upvotes: 0

Views: 541

Answers (1)

teunbrand
teunbrand

Reputation: 37903

I think your case might be slightly simplified by using geom_tile() instead of geom_rect(). The output is the same but the parametrisation is easier.

I have presumed your data had a structure roughly like this:

library(ggplot2)
set.seed(2)

Alldata <- data.frame(
  Date = Sys.Date() + 1:10,
  ERVALUE = cumsum(rnorm(10)),
  Recession = sample(c(0, 1), 10, replace = TRUE)
)

With this data, we can make grey rectangles wherever recession == 1 as follows. Here, I've mapped it to a scale to generate a legend automatically.

ggplot(Alldata, aes(Date)) +
  geom_tile(aes(alpha = Recession, y = 1), 
            fill = "grey", height = Inf) +
  geom_line(aes(y = ERVALUE), colour = "red") +
  scale_alpha_continuous(range = c(0, 1), breaks = c(0, 1))

Created on 2021-08-25 by the reprex package (v1.0.0)

Upvotes: 1

Related Questions