title: Fill background of ggplot conditionally in R
body: <p>I would like to fill the background of a ggplot in <code>R</code> with a specific color. </p>
  
  <p>The dataframe contains 3 columns: <code>time</code>, <code>value</code>, and <code>color</code>. </p>
  
  <pre><code>df &lt;- data.frame(time = seq(1, 100, 1), 
                   value = c(runif(n = 45, min = 1, max= 10), runif(10, 40, 50), runif(45, 70, 90)), 
                   color = c(rep("green", 45), rep("orange", 10), rep("red", 45))) 
  </code></pre>
  
  <p>I am able to fill background of the plot in the following manner:</p>
  
  <pre><code>library(tidyverse)
  
  ggplot(df) + 
    geom_line(aes(x = time, y = value)) + 
    annotate("rect", xmin=-Inf, xmax= 45, ymin = -Inf, ymax = Inf, alpha = 0.2, fill = "green") +
    annotate("rect", xmin=45, xmax= 55, ymin = -Inf, ymax = Inf, alpha = 0.2, fill = "orange") +
    annotate("rect", xmin=55, xmax= Inf, ymin = -Inf, ymax = Inf, alpha = 0.2, fill = "red") 
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/tqMuC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tqMuC.jpg" alt="enter image description here"></a></p>
  
  <p><strong>Question</strong></p>
  
  <p>In the example above, the background <code>fill</code> is 'hard coded'. Is there a more convenient/automated way to find the <code>xmin</code> and <code>xmax</code> values of the borders between the color transitions?</p>