Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R abline() Function - Adding Reference Lines

R abline() Function - Adding Reference Lines

R Language Examples R Language Examples

The R abline() function is used to add straight reference lines to an existing plot.

It can draw horizontal, vertical, or sloped lines, often used to mark means, thresholds, or trend lines.

The syntax of the abline() function is as follows:

abline(a = NULL, b = NULL, h = NULL, v = NULL,

       col = "black", lty = 1, lwd = 1)

Parameter Description:

Example

Scatter chart

x

<-

1

:

20

y

<-

x

3

rnorm

(

20

,

0

,

5

)

plot

(

x, y, main

=

"Data and Trend Line"

,

     xlab

=

"X"

, ylab

=

"Y"

,

     

col

=

"blue"

, pch

=

16

)

Add Regression Trend Line

abline

(

lm

(

y ~ x

)

,

col

=

"red"

, lwd

=

2

)

Add Horizontal Reference Line (mean of y)

abline

(

h

=

mean

(

y

)

,

col

=

"green"

, lty

=

2

, lwd

=

2

)

Add Vertical Reference Line

abline

(

v

=

10

,

col

=

"purple"

, lty

=

3

, lwd

=

2

)

Legend

legend

(

"topleft"

,

       

legend

=

c

(

"Regression Line"

,

"Mean"

,

"x=10"

)

,

       

col

=

c

(

"red"

,

"green"

,

"purple"

)

,

       lty

=

c

(

1

,

2

,

3

)

, lwd

=

2

)

Running the above code displays a scatter plot with a regression line, a mean line, and a vertical reference line.

R Language Examples R Language Examples