Fixing tick labels/grid lines with a date/time plot in base R using lubridate()

Viewed 64

I apologize that this isn't question isn't clean - I don't know how make this into a good reproducible example.

I have a base R plot where I'm trying to do two things: get clean axis labels on the tick marks and add gridlines that match with these tick marks and so far I have been unsuccessful. I'm looking for either grid lines with correct labels (i.e. all the dates) or axis labels that don't look like two of the same label on top of each other. I attached the graph I'm getting down below as well as my code. I used lubridate() to transform my date/time columns in my csv file into one column, called newdate. I would appreciate any help - I've been trying to do this for quite some time with no success and I'm almost there. Thank you!

PS4T1$newdate <- with(PS4T1, as.POSIXct(paste(date, time), format="%m-%d-%Y %H:%M"))
st <- substr(PS4T1$date, 12, 13) == '00'

plot(average ~ newdate, data=PS4T1, type='b', col='blue', xaxt='n')
axis(1, PS4T1$newdate[st], labels=F)
mtext(strftime(PS4T1$newdate[st], '%b %d'), 1, at=PS4T1$newdate[st])
grid(nx=NA, ny=NULL)
abline(v=axis.POSIXct(1, pretty(PS4T1$newdate[st])),col = "lightgray", lty = "dotted", lwd = par("lwd"))

enter image description here

1 Answers

You may just use abline(v=dat$date[st], ...) to align vertical grid lines with the subsetted dates.

(The deeper reason for this is that "POSIXt" format is the number of seconds since 1970-01-01 - the so called unix epoch - in integers, labelled as date (similar to factors); compare Sys.time() and as.numeric(Sys.time()).)

In mtext you omitted the line= argument which defaults to zero (the repeated 1, 1 in my former answer was no typo, out of laziness I left out the arguments). You could use line=.75 which gets the labels a little closer.

st <- substr(dat$date, 12, 13) == '00'

plot(dat, type='b', col='blue', xaxt='n')
axis(1, dat$date[st], labels=F)
mtext(strftime(dat$date[st], '%b %d'), side=1, line=.75, at=dat$date[st])
grid(nx=NA, ny=NULL)
abline(v=dat$date[st], col="lightgray", lty="dotted", lwd=par("lwd"))

enter image description here

Data:

set.seed(42)
dat <- data.frame(
  date=seq.POSIXt(as.POSIXct('2021-06-22'), as.POSIXct('2021-06-29'), 'hour'),
  v=runif(169)
)
Related