R abline() Function - Adding Reference Lines
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:
-
a, b The intercept and slope of the line, that is, y = a + b*x.
-
h The y value of a horizontal line.
-
v The x value of a vertical line.
-
lty Line type: 1 = solid, 2 = dashed, 3 = dotted.
-
lwd Line width.
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