Evaluation of columns in ggplot with two datasets

Hi - I was making a ggplot in which I was bringing in data from two sources. The plot I wanted: use tibble 1 to make a geom line, and the second tibble to make a background highlight for negative values.

library(tidyverse)
tibble1 <- tibble (x = 1:270,
                   y = sin(x),
                   z = rep(LETTERS[1:3], 90))

boundaries <- tibble (x = tibble1$x,
                      ymin = min(tibble1$y),
                      ymax = 0)

## Mapping the aes with the main ggplot call throws an error
ggplot(tibble1, aes(x = x, y = y))+
    
    geom_line() +
    geom_ribbon(data = boundaries,
                aes(x = x, ymin = ymin, ymax = ymax),
                fill = "yellow",
                alpha = 0.3) +
    facet_wrap(~z, ncol = 1)

### Doing it in the geom_line works fine

 ggplot(tibble1 )+
    
    geom_line(aes(x = x, y = y)) +
    geom_ribbon(data = boundaries,
                aes(x = x, ymin = ymin, ymax = ymax),
                fill = "yellow",
                alpha = 0.3) +
    facet_wrap(~z, ncol = 1)

Created on 2021-09-07 by the reprex package (v2.0.1)

What I have noticed is that if I add the aes evaluation within the first ggplot call ggplot(tibble1, aes(x = x, y = y)), then it throws an error

Error in FUN(X[[i]], ...) : object 'y' not found

But if I move the aes evaluation within the geom_line, then everything works.

I think there is something I don't about why this is happening - is this normal behaviour for ggplot2? OR is it a bug?

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.