0

I am trying to make a line graph with background colors, like the accepted answer here. I can make a simple line graph, but when I add the rectangle geom, it throws an error.

Set up data for line and rectangles:

library(ggplot2)
  
df <- data.frame(
  date = c('1980-09-01', '1981-12-01', '1982-03-01', '1983-06-01', '1984-08-01'),
  number = c(4,8,7,9,2)
)
df$date <- as.Date(df$date)

rects <- data.frame(
  name = c('A', 'B', 'C'),
  start = c('1980-09-01', '1981-05-15', '1983-02-22'),
  end = c('1981-05-15', '1983-02-22', '1984-05-23')
)
rects$start <- as.Date(rects$start)
rects$end <- as.Date(rects$end)

Make and display a simple line graph:

p <- ggplot(data=df, aes(x=date, y=number)) +
  geom_line() +
  geom_point() +
  scale_x_date(date_breaks = "1 year", date_labels = "%Y")
p

So far it works fine. But then, attempt to add rectangles in the background:

p + geom_rect(data = rects, mapping=aes(xmin = start, xmax = end,
                                        ymin = -Inf, ymax = Inf, fill = name), alpha = 0.4)

This throws the error Error in FUN(X[[i]], ...) : object 'number' not found. I can't understand this error, because number was part of the df dataset and original p graph that worked fine, not part of the additional geom_rect code. What is going on?

Cenlle
  • 37
  • 4

1 Answers1

1

Since you've placed aes(x=date, y=number) in the global ggplot object, all layers will inherit those mappings. Since those values aren't available for the data in the geom_rect layer, you either need to explicitly turn off the inheritance.

  geom_rect(data = rects, inherit.aes=FALSE, mapping=aes(xmin = start, xmax = end,
                                    ymin = -Inf, ymax = Inf, fill = name), alpha = 0.4)

or remap those values to NULL

  geom_rect(data = rects, mapping=aes(xmin = start, xmax = end, x=NULL, y=NULL,
                                    ymin = -Inf, ymax = Inf, fill = name), alpha = 0.4)
MrFlick
  • 195,160
  • 17
  • 277
  • 295