In this recipe, we will learn how to choose the formatting of time axis labels, instead of just using the defaults.
We will only use the basic R functions for this recipe. Make sure that you are at the R prompt and load the openair.csv
dataset:
air<-read.csv("openair.csv")
Let's redraw our original example involving plotting air pollution data from the last recipe, but with labels for each month and year pairing:
plot(air$nox~as.Date(air$date,"%d/%m/%Y %H:%M"),type="l", xaxt="n", xlab="Time", ylab="Concentration (ppb)", main="Time trend of Oxides of Nitrogen") xlabels<-strptime(air$date, format = "%d/%m/%Y %H:%M") axis.Date(1, at=xlabels[xlabels$mday==1], format="%b-%Y")
In our original example involving plotting air pollution data in the last recipe, we only formatted the date/time vector to pass as a x
argument to plot()
, but the axis labels were chosen automatically by R as the years 1998, 2000, 2002, and 2004. In this example, we drew a custom axis with labels for each month and year pairing.
We first created an xlabels
object of the POSIXlt
class by using the strptime()
function. Then, we used the axis.Date()
function to add the x axis. The axis.Date()
function is similar to the axis()
function and takes the side
and at
arguments. In addition, it also takes the format argument that we can use to specify the format of the labels. We specified the at
argument as a subset of xlabels
for only the first day of each month by setting mday=1
. The "%b-%Y"
format value means an abbreviated month name with full year.
18.118.166.45