stollenm
stollenm

Reputation: 358

Dynamically change background color of ggplot2

In R, suppose I have a logical vector of the same length as the data. I would like to change the background color of the ggplot depending on the logical vector.

In the example below background_change is the logical vector.

library(ggplot2)
background_change <- economics$unemploy < 7777
ggplot(economics, aes(date, psavert)) + geom_line()

Note that this is different from other questions posted on stackoverflow which do the background change manually. This is to tedious for my application.

Upvotes: 3

Views: 1554

Answers (2)

Brian Levey
Brian Levey

Reputation: 53

Here is a slight variation on this answer that does not require manually adjusting the size parameter. This works by adding 1 month to the xmax argument.

ggplot(economics, aes(date, psavert)) + 
   geom_rect(aes(xmin = date, xmax = date+months(1), 
                 ymin = -Inf, ymax = Inf, 
                 fill = unemploy < 7777), 
                 show.legend = FALSE) +
   geom_line()

enter image description here

Upvotes: 1

pogibas
pogibas

Reputation: 28309

Not a perfect solution, but works for a given example.

For each value generate geom_rect with color defined by unemploy < 7777 and coordinates x as xmin, xmax (start = end).

thresholdUnemploy <- 7777
library(ggplot2)
ggplot(economics, aes(date, psavert)) + 
    geom_rect(aes(xmin = date, xmax = date,
                  ymin = -Inf, ymax = Inf,
                  color = unemploy < thresholdUnemploy),
              size = 0.7,
              show.legend = FALSE) +
    geom_line()

enter image description here

Why this is not perfect: depending on the density of the x-axis points you might need to adjust size of geom_rect.

Upvotes: 4

Related Questions