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:
Here's an example using @Henrik's data: