How to Remove Rows with Missing Data in R
How to Create an Array in R
How to Use Arithmetic Vector Operations in R

How to Add Lines to a Plot in R

In R, you add lines to a plot in a very similar way to adding points, except that you use the lines() function to achieve this.

But first, use a bit of R magic to create a trend line through the data, called a regression model. You use the lm() function to estimate a linear regression model:

fit <- lm(waiting~eruptions, data=faithful)

The result is an object of class lm. You use the function fitted() to extract the fitted values from a regression model. This is useful, because you can then plot the fitted values on a plot. You do this next.

To add this regression line to the existing plot, you simply use the function lines(). You also can specify the line color with the col argument:

> plot(faithful)
> lines(faithful$eruptions, fitted(fit), col="blue")

Another useful function is abline(). This allows you to draw horizontal, vertical, or sloped lines. To draw a vertical line at position eruptions==3 in the color purple, use the following:

> abline(v=3, col="purple")

Your resulting graphic should have a vertical purple line at eruptions==3 and a blue regression line.


To create a horizontal line, you also use abline(), but this time you specify the h argument. For example, create a horizontal line at the mean waiting time:

> abline(h=mean(faithful$waiting))

You also can use the function abline() to create a sloped line through your plot. In fact, by specifying the arguments a and b, you can draw a line that fits the mathematical equation y = a + b*x. In other words, if you specify the coefficients of your regression model as the arguments a and b, you get a line through the data that is identical to your prediction line:

> abline(a=coef(fit)[1], b=coef(fit)[2])

Even better, you can simply pass the lm object to abline() to draw the line directly. (This works because there is a method abline.lm().) This makes your code very easy:

> abline(fit, col = “red”)
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
How to Use Standard Operations in a Matrix in R
How to Evaluate Linear Data with R
How to Know When to Care About Warnings in R
How to Look at the Structure of a Factor in R
How to Juggle Dimensions and Replace Values in a Matrix in R