Adding vertical markers to indicate specific time events

We may 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.

Getting ready

We will only use the basic R functions for this recipe. Make sure you are at the R prompt and load the openair.csv dataset:

air<-read.csv("openair.csv")

How to do it...

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"))
How to do it...

How it works...

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 co-ordinate by using the as.Date() function. Note that the original time series plotted also contains the timestamp in addition to the dates. Since we didn't specify a time, the line was plotted at the start of the specified date 25/12/2003 00:00.

There's more...

Let's look at another example, where we want to draw a vertical marker line on Christmas day of 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")
There's more...

We created a sequence of the Christmas dates for each year using the seq() function, which takes 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset