We might wish to indicate specific points of importance or measurements in a time series, where there is a significant event or change in the data. In this recipe, we will learn how to add vertical markers using the abline()
function.
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 take our air pollution time series example again and draw a red vertical line on Christmas day, 25/12/2003
:
plot(air$nox~as.Date(air$date,"%d/%m/%Y %H:%M"),type="l", xlab="Time", ylab="Concentration (ppb)", main="Time trend of Oxides of Nitrogen") abline(v=as.Date("25/12/2003","%d/%m/%Y"))
As we have seen before in the recipe introducing abline()
, we drew a vertical line in the example by setting the v
argument to the date we want to mark. We specified 25/12/2003
as the X coordinate by using the as.Date()
function. Note that the original time series plotted also contains the timestamp in addition to the dates. As we didn't specify a time, the line was plotted at the start of the specified date, 25/12/2003 00:00
.
Let's look at another example, where we want to draw a vertical marker line on Christmas every year:
markers<-seq(from=as.Date("25/12/1998","%d/%m/%Y"), to=as.Date("25/12/2004","%d/%m/%Y"), by="year") abline(v=markers,col="red")
We created a sequence of the Christmas dates for each year using the seq()
function, which takes the from
, to
, and by
arguments. Then, we passed this vector to the abline()
function as v
.
One important thing to note is that, by default, R does not deal with gaps in a time series. There can be missing values denoted by NA
and, as you can see in the previous examples, the graphs show gaps in those places. However, if any dates or time intervals are missing from the actual dataset, then R draws a line connecting the data points before and after the gap instead of leaving it blank. In order to remove this connecting line, we must fill in the missing time intervals in the gap and set the y
values to NA
.
3.144.17.43