在 R 编程中向绘图添加直线 - abline()函数
R 语言中的abline()
函数用于在图形中添加一条或多条直线。 abline()
函数可用于添加垂直线、水平线或回归线以进行绘图。
Syntax:
abline(a=NULL, b=NULL, h=NULL, v=NULL, …)
Parameters:
a, b: It specifies the intercept and the slope of the line
h: specifies y-value for horizontal line(s)
v: specifies x-value(s) for vertical line(s)
Returns: a straight line in the plot
示例 1:在绘图中添加垂直线
# add line to square plot
# first example : Add one line
plot(cars)
abline(v = 16, col = "darkgreen")
# second example : add 2 lines
# addline to square plot
# change line colors, sizes and types
plot(cars)
abline(v = c(16, 22), col = c("darkgreen", "blue"),
lty = c(1, 2), lwd = c(1, 3))
# third example
set.seed(1200); mydata<-rnorm(180)
hist(mydata, col="darkgreen")
# lwd=line width, lty =linetype
abline(v = mean(mydata), col = "blue", lwd = 4, lty = 4)
输出:
在这里,在上面的示例中,使用 abline() 将直线添加到不同的图形图中
示例 2:添加水平线
# R program to add a horizontal line
# to a plot
# Creating a plot
plot(cars)
# Calling abline() function
abline(h = 60, col = "darkgreen")
输出:
在上面的示例abline()
函数在当前绘图上的指定 'x' 坐标处绘制一条水平线。
示例 3:添加回归线
par(mgp = c(2, 1, 0), mar = c(3, 3, 1, 1))
# Fit regression line
require(stats)
reg<-lm(dist ~ speed, data = cars)
coeff = coefficients(reg)
# equation of the line :
eq = paste0("y = ", round(coeff[1], 1), "*x ",
round(coeff[2], 1))
# plot
plot(cars, main = eq)
abline(reg, col = "darkgreen")
输出:
在上面的示例中,使用直线方程和abline()
函数添加了直线,并绘制了速度和距离之间的关系。