I am trying to use geom_rect() with dates on the x-axis to show which US political party held the presidency. The default assigns Red to the Democrats and Blue to the Republicans which is the opposite of what I want. I've tried several approaches and no luck
Here is a glimpse of the data. I'm using party
, observation_date
, and end_date
to build the rectangles.
> glimpse(presidential_party)
Observations: 20
Variables: 4
$ president <chr> "Roosevelt", "Taft", "Wilson", "Harding", "Coolidge", "Hoover", "FDR", "Truman", "Eisenh…
$ party <fct> Republican, Republican, Democratic, Republican, Republican, Republican, Democratic, Demo…
$ observation_date <date> 1901-09-01, 1909-03-01, 1913-03-01, 1921-03-01, 1923-08-01, 1929-03-01, 1933-03-01, 194…
$ end_date <date> 1909-03-01, 1913-03-01, 1921-03-01, 1923-08-01, 1929-03-01, 1933-03-01, 1945-04-01, 195…
This is the code that I have
ggplot(deficit, aes(x=observation_date)) +
geom_line(aes(y = summ_surplus_deficit)) +
geom_rect(data = presidential_party,
aes(xmin=observation_date, xmax = end_date,
ymin = -Inf, ymax = Inf,
fill = party, alpha = .10)) +
scale_x_date(date_breaks = "10 years", date_labels = "%Y",
limits = c(min(deficit$observation_date), max(deficit$observation_date)))
How do I tell fill
to use Blue for Dems and Red for Reps
I also tried this with similar results:
pal <- brewer.pal(3, "Set1")
repub <- presidential_party %>%
filter(party == "Republican")
dem <- presidential_party %>%
filter(party == "Democratic")
ggplot(deficit, aes(x=observation_date)) +
geom_line(aes(x=observation_date, y = summ_surplus_deficit)) +
geom_rect(data = repub,
aes(xmin=observation_date, xmax = end_date,
ymin = -Inf, ymax = Inf,
fill = pal[1], alpha = .10)) +
geom_rect(data = dem,
aes(xmin=observation_date, xmax = end_date,
ymin = -Inf, ymax = Inf,
fill = pal[2], alpha = .10)) +
scale_x_date(date_breaks = "10 years", date_labels = "%Y",
limits = c(min(deficit$observation_date), max(deficit$observation_date)))
Strange thing is that I remember there being some code in the original ggplot2 book that did exactly this but I lent it out and never got it back.
Thanks in advance.