Change background colour between day and night in ggplot2 in R

1.1k Views Asked by At

I'm plotting graphs in R from blood pressure measurements stored in Apple's Apple health app following the fantastic blog from Taras Kaduk.

I changed the code for my needs and now I would like to change the background colours from the plot depending on the time value. I have added a column daynight with the two values "night" and "day" ("night"= between 18:00 and 06:00, "day" from 06:00 until 18:00). Is there a way to use this values to switch the background color in the graph, so that all the night periods are darkened? Alternatively I could use directly the datetime value (x axis), that is a POSIXct value.

I did only find examples that do the trick but with one (or a few) fixed date values like this one: Change color background in ggplot2 - R by specific Date on x axis.

Here a dataset and the code I use so far:

Sample data (blood_pressure):
  value      type            datetime daynight         state
1    96 Diastolic 2022-01-10 07:52:48      day Hypertension 1
2   102 Diastolic 2022-01-10 07:09:58      day Hypertension 2
3   109 Diastolic 2022-01-09 19:58:56    night Hypertension 2
4   141  Systolic 2022-01-09 08:27:24      day Hypertension 1
5   146  Systolic 2022-01-10 19:09:19    night Hypertension 1


blood_pressure  %>% 
  ggplot(blood_pressure, aes(datetime, value)) + 
  geom_point()

Here You can see an example plot:

enter image description here

1

There are 1 best solutions below

0
On

Here's an example using @Henrik's data:

d = data.frame(x = seq(from = Sys.time(), by = "1 hour", len = 50), y = 1)
d$hour = as.numeric(format(d$x, "%H"))
d$hour_shade =ifelse(d$hour >= 18 | d$hour <= 6, "gray60", "gray90")
ggplot(d, aes(x, y)) + 
  geom_rect(aes(xmin = x, xmax = lead(x), ymin = -Inf, ymax = Inf,
                fill = hour_shade)) +
  geom_point() +
  scale_fill_identity()

enter image description here