While creating a ggplot chart using geom_rect, I encountered the following error:
Error in `geom_rect()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error in `FUN()`:
! object 'Weekly_Sales' not found
My code:
ggplot(data = df1, aes(x = Date, y = Weekly_Sales)) +
geom_rect(data = df2, color = 'white',aes(xmin = as.Date(xmin),
ymin = ymin, xmax = as.Date(xmax), ymax = ymax, fill = changes),alpha = .4) +
geom_line(color = 'orange', size = 1.25) +
scale_fill_manual(values = c('blue', 'green'))
The Weekly_Sales column is in the df1 dataset.
>Solution :
You need to add inherit.aes = F inside geom_rect.
inherit.aes
If FALSE, overrides the default aesthetics, rather than combining with them.
ggplot(data = df1, aes(x = Date, y = Weekly_Sales)) +
geom_rect(data = df2, inherit.aes = F, color = 'white',aes(xmin = as.Date(xmin),
ymin = ymin, xmax = as.Date(xmax), ymax = ymax, fill = changes),alpha = .4) +
geom_line(color = 'orange', size = 1.25) +
scale_fill_manual(values = c('blue', 'green'))