2

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.

pogibas
  • 27,303
  • 19
  • 84
  • 117
stollenm
  • 348
  • 1
  • 2
  • 11
  • 2
    You will have to at some level do the equivalent of the technique in the question you linked to. Namely, you'll need to generate a data frame that defines the rectangles. This can probably be done fairly automatically, though. You'll want one data frame with the xmin, xmax, ymin, ymax values for each rectangle and then a column that will be mapped to fill. – joran Mar 21 '18 at 14:35

2 Answers2

4

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.

pogibas
  • 27,303
  • 19
  • 84
  • 117
1

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