I'm trying to shade a certain area of time series plot using geom_rect
.
I used the code below to create the time series plot
library(ggplot2)
set.seed(123)
date <- as.Date(seq(as.Date("2014-01-01"), as.Date("2015-12-31"), by = 1), format="%Y-%m-%d")
a <- runif(730, 3000, 120000)
df <- data.frame(date, a)
ggplot() +
geom_line(data = df, aes(x = date, y = a))
I tried to create the rectangle using geom_rect
following the answer to this question
library(lubridate)
rectangle <- data.frame(xmin = decimal_date(as.Date(c("2014-10-01"))),
xmax = decimal_date(as.Date(c("2015-02-01"))),
ymin = -Inf, ymax = Inf)
ggplot() +
geom_line(data = df, aes(x = date, y = a)) +
geom_rect(data = rectangle, aes(xmin=xmin, xmax = xmax, ymin = ymin, ymax = ymax),
fill = "red", alpha = 0.5)
I got this error
Error: Invalid input: date_trans works with objects of class Date only
Any suggestions how to fix that would be appreciated.