0

I'm modifying a stacked/grouped bar plot and would like to change the panel/background color based on the year. Here's the data that I'm working with, a data frame called melted.

Year D_or_I Value Scenario
2023 MPO D 7350 MPO
2024 MPO D 1671 MPO
2025 MPO D 9454 MPO
2026 MPO D 2415 MPO
2027 MPO D 4250 MPO
2023 MPO I 2166 MPO
2024 MPO I 787 MPO
2025 MPO I 1816 MPO
2026 MPO I 4364 MPO
2027 MPO I 3331 MPO
2023 MPOE D 4121 MPOE
2024 MPOE D 8937 MPOE
2025 MPOE D 9288 MPOE
2026 MPOE D 1861 MPOE
2027 MPOE D 1858 MPOE
2023 MPOE I 7892 MPOE
2024 MPOE I 4408 MPOE
2025 MPOE I 6866 MPOE
2026 MPOE I 405 MPOE
2027 MPOE I 2475 MPOE

I have gotten the stacked bars like I want them using the following code.

ggplot(melted, aes(x = Scenario, y = Value, fill = D_or_I)) + 
  geom_bar(stat = 'identity', position = 'stack') + facet_grid(~ Year, switch="both") +
  ggtitle("Figure 2. Numbers and Stuff","For your Enjoyment") +
  theme(strip.text.x.bottom = element_text(angle = 90), axis.text.x=element_blank(), axis.ticks.x=element_blank(),
  legend.position="top",plot.title = element_text(hjust = 0.5), plot.subtitle = element_text(hjust = 0.5)) +
  guides(fill=guide_legend(title=element_blank())) +
  scale_fill_manual(values = c('#2980b9','#3498db','#f39c12','#f1c40f')) +
  scale_y_continuous(labels = scales::comma,breaks = seq(0,20000,2500)) + 
  ylab('Number (unit)') + xlab('Year') +
  theme(plot.margin = margin(1,1,1,1, "cm"))

Which produces this plot.

Now, I'd love to change the color of the background/panel (the part that's light grey) so that it varies for a series of years, say 2023-2025 one color and 2026-2027 a different color. Any help appreciated!

Nate
  • 1
  • 1

1 Answers1

1

You can draw an infinite geom_rect where the fill is determined by the year. This is easier if you use ggnewscale to allow two fill scales:

library(ggplot2)
library(ggnewscale)

ggplot(melted, aes(x = Scenario, y = Value)) + 
  geom_rect(xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf, 
            inherit.aes = FALSE, aes(fill = factor(Year)), alpha = 0.1) +
  scale_fill_discrete(guide = "none") +
  new_scale_fill() +
  geom_bar(aes(, fill = D_or_I), stat = 'identity', position = 'stack') + 
  facet_grid(~ Year, switch="both") +
  ggtitle("Figure 2. Numbers and Stuff","For your Enjoyment") +
  theme(strip.text.x.bottom = element_text(angle = 90), 
        axis.text.x=element_blank(), 
        axis.ticks.x=element_blank(),
        legend.position="top",
        plot.title = element_text(hjust = 0.5), 
        plot.subtitle = element_text(hjust = 0.5)) +
  guides(fill=guide_legend(title=element_blank())) +
  scale_fill_manual(values = c('#2980b9','#3498db','#f39c12','#f1c40f')) +
  scale_y_continuous(labels = scales::comma,breaks = seq(0,20000,2500)) + 
  ylab('Number (unit)') + xlab('Year') +
  theme(plot.margin = margin(1,1,1,1, "cm"))

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87