Change background color between day and night in R base

  Kiến thức lập trình

Im trying to change the background color of a graph. My x axis is the day time in format POSIXct and it have measures each 5 minutes. In the Y-axis I have numeric data of clorophyll (chla) measures and I have added also added solar radiation data (PARuw) using PAR(new = TRUE). Those 3 variables are in a data frame named Spring. This is my plot:

par(mfrow = c(1,1), 
    mar = c(2, 3, 1, 3))

plot(Spring$date_time, Spring$chla, xlab = "", 
     ylab = "", type = "n", ylim=c(0,6), las =1)
points(Spring$date_time, Spring$chla, pch=21, col="forestgreen", 
       bg="forestgreen", cex=.8)

lines(Spring$date_time, Spring$chla, col="forestgreen", lwd=5)

par(new=T)

plot(Spring$date_time, Spring$PARuw, xlab = "", 
     ylab = "", xaxt="n", type = "n", yaxt="n")

points(Spring$date_time, Spring$PARuw, pch=21, col="yellow2", 
       bg="yellow2", cex=.8)

lines(Spring$date_time, Spring$PARuw, col="yellow2", lwd=5)
axis(side = 4, at = seq(0, 1200, by = 200), labels = seq(0, 1200, by = 200), las = 1)

I add head and tail of the data frame:

date_time             PARuw  chla
1 2023-04-23 02:00:00 1.954 4.735
2 2023-04-23 02:05:00 1.971 4.769
3 2023-04-23 02:10:00 1.736 4.671
4 2023-04-23 02:15:00 1.586 4.616
5 2023-04-23 02:20:00 1.566 4.912
6 2023-04-23 02:25:00 1.686 4.615 

date_time              PARuw  chla
283 2023-04-24 01:30:00 2.439 5.511
284 2023-04-24 01:35:00 2.250 5.402
285 2023-04-24 01:40:00 2.443 5.381
286 2023-04-24 01:45:00 2.330 5.386
287 2023-04-24 01:50:00 2.220 5.310
288 2023-04-24 01:55:00 2.472 5.313

enter image description here

I have tryed to differentiate day and night using PARuw > 20 (if this is true then day) and use this on polygon(function) but I dont know how to do it well.

New contributor

javi cabezas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT