Abline in R – A Quick Tutorial

Ever needed to add straight lines to an R plot? You can use abline in R to add straight lines to a plot. This R function is great for adding cutoffs or similar limits to an existing R plot.

# abline in r - basic syntax

abline(a = NULL, b = NULL, h = NULL, v = NULL, reg = NULL,
       coef = NULL, col = NULL, lty = NULL, lwd= NULL)

The abline function can accept several arguments, with defaults of NULL:

  • a – The intercept of the line, as a single value
  • b – The slope of a line, as a single value
  • h – the y-value(s) for horizontal line(s)
  • v – the x-value(s) for vertical line(s).
  • coef – a vector of length two giving the intercept and slope
  • reg – a regression object generated by the coef method; intended to simplifying passing trend-lines from a regression calculation
  • col – optional color parameter for the line
  • lty – optional line type parameter
  • lwd – optional line width parameter

Initial Setup – Examples

We’re going to use the airmiles dataset for this tutorial. This is one of the default datasets available in R.

> airmiles

# default plot for abline in r tutorial
> plot (airmiles)
airmiles data frame

As you can see, airmiles is a nice basic timeseries. It shows the growth of airline travel within the US.

Abline in r – Add Horizontal Lines

First, lets start by drawing a horizontal line on the graph. Maybe we are very interested in seeing when the total miles traveled is above 20,000.

# abline in R example - horizontal line

This draws a lovely horizontal line at the y = 20000 level.

abline in r - horizontal

Abline in r – Add Vertical Lines

We can also easily add a vertical line to the graph, similar to a dropline in Excel. Perhaps our client would like to see a line at the year 1955.

# abline in R example - horizontal line
abline(v = 1955)

This draws a lovely horizontal line at the x = 1955 level.

abline in R – Vertical Line

Abline in r – Color and Line Types

Moving past basic black and white, we can easily adapt the abline function to draw lines in color and in different formats.

abline(v=1955, col='blue', lty=2, lwd=5)

Abline in r – Multiple Lines

In this next example, we’re going to draw a range of two lines on the chart. There’s syntax that can simplify this for horizontal lines.

abline(c(5000, 25000), col='blue', lty=2, lwd=4)
abline(5000, 0, col='blue', lty=2, lwd=4)
abline(25000, 0, col='blue', lty=2, lwd=4)

Abline in r – Drawing a slope

For our next example, we will demonstrate how to draw a sloped line.

A slope of 1 is a 45 degree line.

with(airquality, plot(Ozone, Temp))
abline(60, .5, col='blue', lty=2, lwd=4)
abline(60, 0, col='blue', lty=2, lwd=4)
abline(60, 1, col='blue', lty=2, lwd=4)