Adding marker lines at specific X and Y values

Sometimes we may only want to draw one or a few lines to indicate specific cut-off or threshold values. In this recipe, we will learn how to do that using the abline() function.

Getting ready

We will use the base graphics library for this recipe, so all you need to do is run the recipe at the R prompt. It is good practice to save your code as a script to use again later.

How to do it...

Let's draw a vertical line at the month of September in the rainfall graph for Tokyo:

rain <- read.csv("cityrain.csv")
plot(rain$Tokyo,type="b",lwd=2,
xaxt="n",ylim=c(0,300),col="black",
xlab="Month",ylab="Rainfall (mm)",
main="Monthly Rainfall in Tokyo")
axis(1,at=1:length(rain$Month),labels=rain$Month)

abline(v=9)
How to do it...

How it works...

To draw marker lines with abline() at specific X or Y locations, we have to set the v (as in vertical) or h (as in horizontal) arguments respectively. In the example, we set v=9 (the index of the month September in the Month vector).

There's more...

Now let's add a red dotted horizontal line to the graph to denote a high rainfall cutoff of 150 mm:

abline(h=150,col="red",lty=2)
There's more...
..................Content has been hidden....................

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