I would like to fill the background of a ggplot in R with a specific color.
The dataframe contains 3 columns: time, value, and color.
df <- 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)))
I am able to fill background of the plot in the following manner:
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")
Question
In the example above, the background fill is 'hard coded'. Is there a more convenient/automated way to find the xmin and xmax values of the borders between the color transitions?


