0

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.

Community
  • 1
  • 1
shiny
  • 3,380
  • 9
  • 42
  • 79
  • 2
    Just get rid of the `decimal_date()`. See G. Grothendieck's comment on your linked question: *Also note that its not ggplot that requires dates of the form used here but that the `ts` data has them. Had the problem provided `Date` class data, say, then ggplot could use it via `scale_x_date`.* – Gregor Thomas Mar 07 '16 at 22:58

1 Answers1

1

This works:

library(lubridate)
rectangle <- data.frame(xmin = as.Date(c("2014-10-01")),
                        xmax = 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)

Just remove decimal_date()

saladi
  • 3,103
  • 6
  • 36
  • 61