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.

1
  • 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, 2018 at 14:35

2 Answers 2

Reset to default

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.