Home > Software engineering >  How to highlight different days for a date-time data?
How to highlight different days for a date-time data?

Time:04-01

Suppose that I have data in date-time format like this. The times are not necessarily evenly distributed. Some days may have more times, some days may have less or none.

date    time    value
2022-01-01  08:20   1
2022-01-01  10:30   2
2022-01-02  14:05   3
2022-01-02  17:50   4
2022-01-03  11:35   5
...

Suppose f is a data.frame of the data. I have the following code to plot the data.

f$idx=seq_len(nrow(f))
with(f, plot(idx, value, type='p', xaxt='n', xlab=''))
with(f, text(idx, par('usr')[3]-0.02, srt = 45, adj = 1, xpd = NA, labels = paste(date, time), cex = 0.5))

But it is hard to see the boundary of days. Is there an easy way to highlight different days in basic R graphics (for example, interleave two different colors for alternating days as the background)?

No solutions in ggplot2 or other graphics packages are needed. This question is only for basic R graphics.

CodePudding user response:

Define startOfDate to be the start of each date and use that to draw vertical lines separating the days.

date <- f$date
startOfDate <- match(date, date)
plot(value ~ idx, f, type = "p", xaxt = "n", xlab = "")
abline(v = startOfDate, lty = 3, col = "grey")
text(startOfDate, par('usr')[3] - 0.05, srt = 45, labels = date,
  adj = 1, xpd = NA, cex = 0.5)

or add this to shade alternate days (not shown):

ix <- setdiff(seq(2, max(f$idx), 2), max(f$idx))
rect(ix, par('usr')[3], ix   1, par('usr')[4], col = adjustcolor("lightgrey", 0.5))

screenshot

Note

f in reproducible form.

f <- structure(list(date = c("2022-01-01", "2022-01-01", "2022-01-02", 
"2022-01-02", "2022-01-03"), time = c("08:20", "10:30", "14:05", 
"17:50", "11:35"), value = 1:5, idx = 1:5), row.names = c(NA, 
-5L), class = "data.frame")

CodePudding user response:

For the color thing you could exploit the differences of the dates.

f$col <- cumsum(c(1, diff(as.Date(f$date))))   1

with(f, plot(idx, value, type='p', xaxt='n', xlab=''))
axis(1, axTicks(1), labels=FALSE)
with(f, text(idx, par('usr')[3]-0.3, srt = 45, adj = 1, xpd = NA, 
             labels = paste(date, time), cex = 0.7, 
             col=col))

enter image description here

  • Related