'How to fill area below geom_line plot in ggplot with geom_rect?
This is my plot:
library(ggplot2)
economics <- economics %>% mutate(year = year(economics$date))
ggplot(economics,aes(year, unemploy))+
geom_line() +
geom_rect(aes(xmin = 1970,xmax = 1975,
ymin = 0, ymax = unemploy))
I want to fill the area below the line plot between the years 1970 and 1975. But it's not working.
What am I doing wrong?
Solution 1:[1]
The issue is that in ymax
we are using the whole column 'unemploy', it should be the max
value of 'unemploy' within that range of year
library(ggplot2)
library(dplyr)
library(lubridate)
economics %>%
mutate(year = year(date)) %>%
ggplot(aes(year, unemploy)) +
geom_line() +
geom_rect(aes(xmin = 1970,xmax = 1975,
ymin = 0,
ymax = max(.data[['unemploy']][between(.data[['year']], 1970, 1975)]))) +
theme_bw()
Solution 2:[2]
You can choose a ymax
that makes sense to you. For example, I set ymax = 4800
:
library(ggplot2)
ggplot(economics,aes(year, unemploy))+
geom_rect(aes(xmin = 1970,xmax = 1975,
ymin = 0, ymax = 4800), fill = "lightblue", alpha = .5) +
geom_line()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | bird |