0

I am trying to shade several sections of a time series plot using “geom_rect”. However, I have the error message “Error in as.Date.default(date) : do not know how to convert 'date' to class “Date”. Why ? and how to fix this ?

Here is a reproducible example:

  library(ggplot2)
  dat <- data.frame(date=seq.Date(as.Date('2005-01-01'), as.Date('2016-12-31'),length.out=100), y=runif(100)) 
  print(dat)
  block <- data.frame(level = c('A','B', "C"), 
                       ymn = -Inf, 
                       ymx = Inf,
                       xmn = c(as.Date('2006-01-01'), as.Date('2010-01-01'), as.Date('2014-01-01')),
                       xmx = c(as.Date('2006-12-31'), as.Date('2010-12-31'), as.Date('2014-12-31')))
  print(block)

  ggplot(data=dat, aes(x=as.Date(date), y=y)) + 
    geom_line(size = 1) +
    geom_rect(data=block,aes(xmin=as.Date(xmn),xmax=as.Date(xmx),ymin=ymn,ymax=ymx, fill=level), alpha = 0.3)
Nell
  • 559
  • 4
  • 20
  • 1
    You might need an `inherit.aes = FALSE` in `geom_rect`. It might be seeing the global `x` you defined. – aosmith Jun 07 '18 at 20:56
  • The column `date` already is a Date object, as are the date columns in `block`. Take out the `as.Date` calls in all your `aes` and this works – camille Jun 07 '18 at 21:05
  • Great ! it works by adding `inherit.aes = FALSE` in `geom_rect` ! Thanks very much for your help ! – Nell Jun 07 '18 at 22:20

1 Answers1

0

This will work:

ggplot(data=dat, aes(x=as.Date(dat$date), y=dat$y))

or

ggplot(data=dat, aes(x=dat$date, y=dat$y))

The next option will work as well:

ggplot(data=dat, aes(x=as.Date(dat$date), y=dat$y)) + 
  geom_line(size = 1)

but your real problem is that the block object is not the right shape to match data the way you're using it, but that's an unrelated problem.

Hack-R
  • 22,422
  • 14
  • 75
  • 131
  • 3
    Referencing the name of the data frame inside `aes`, such as `y = dat$y`, can be really prone to bugs – camille Jun 07 '18 at 21:03
  • @camille Could you be specific? I've never experienced any bug – Hack-R Jun 07 '18 at 21:16
  • There are a lot of SO posts where something weird happens in a ggplot, and it turns out the issue is a scoping problem introduced by using the dataframe name inside `aes`. ggplot expects to get bare column names, so you're better off feeding it what it wants. Here's one post illustrating this: https://stackoverflow.com/questions/22244500/why-ggplot2-pie-chart-facet-confuses-the-facet-labelling/22245032#22245032 – camille Jun 07 '18 at 21:32