在 R 编程中向绘图添加线 - lines()函数
R 编程语言中的lines()函数用于将不同类型、颜色和宽度的线条添加到现有绘图中。
Syntax: lines(x, y, col, lwd, lty)
Parameters:
- x, y: Vector of coordinates
- col: Color of line
- lwd: Width of line
- lty: Type of line
使用 R 中的 lines()函数将线条添加到绘图中
用于演示的样本散点图:
在这里,我们将使用数据集创建散点图。
R
# R program to create a scatter plot
# Creating coordinate vectors
x <- c(1.3, 3.5, 1.4, -3.1, 5.7, 2.4,
3.3, 2.5, 2.3, 1.9, 1.8, 2.3)
y <- c(2.5, 5.8, 2.1, -3, 12, 5, 6.2,
4.8, 4.2, 3.5, 3.7, 5.2)
# Plotting the graph
plot(x, y, cex = 1, pch = 3,
xlab ="x", ylab ="y",
col ="black")
R
# R program to add lines into plots
# Creating coordinate vectors
x <- c(1.3, 3.5, 1.4, -3.1, 5.7,
2.4, 3.3, 2.5, 2.3, 1.9, 1.8, 2.3)
y <- c(2.5, 5.8, 2.1, -3, 12, 5,
6.2, 4.8, 4.2, 3.5, 3.7, 5.2)
# Plotting the graph
plot(x, y, cex = 1, pch = 3, xlab ="x",
ylab ="y", col ="black")
# Creating coordinate vectors
x2 <- c(4.3, 1.2, -2.5, -0.4)
y2 <- c(3.5, 4.6, 2.5, 3.2)
# Plotting a line
lines(x2, y2, col = "red",
lwd = 2, lty = 1)
R
# R program to add lines into plots
# Creating coordinate vectors
x <- c(1.3, 3.5, 1.4, -3.1, 5.7, 2.4,
3.3, 2.5, 2.3, 1.9, 1.8, 2.3)
y <- c(2.5, 5.8, 2.1, -3, 12, 5, 6.2,
4.8, 4.2, 3.5, 3.7, 5.2)
# Plotting the graph
plot(x, y, cex = 1, pch = 3,
xlab ="x", ylab ="y",
col ="black")
lines(x, y, col = "red")
输出:
示例 1:使用lines() 函数向散点添加一条线。
R
# R program to add lines into plots
# Creating coordinate vectors
x <- c(1.3, 3.5, 1.4, -3.1, 5.7,
2.4, 3.3, 2.5, 2.3, 1.9, 1.8, 2.3)
y <- c(2.5, 5.8, 2.1, -3, 12, 5,
6.2, 4.8, 4.2, 3.5, 3.7, 5.2)
# Plotting the graph
plot(x, y, cex = 1, pch = 3, xlab ="x",
ylab ="y", col ="black")
# Creating coordinate vectors
x2 <- c(4.3, 1.2, -2.5, -0.4)
y2 <- c(3.5, 4.6, 2.5, 3.2)
# Plotting a line
lines(x2, y2, col = "red",
lwd = 2, lty = 1)
输出:
示例 2:使用点将点添加到 R 中的绘图
在这里,我们将创建一个散点图,然后我们将使用 lines()函数连接线。
R
# R program to add lines into plots
# Creating coordinate vectors
x <- c(1.3, 3.5, 1.4, -3.1, 5.7, 2.4,
3.3, 2.5, 2.3, 1.9, 1.8, 2.3)
y <- c(2.5, 5.8, 2.1, -3, 12, 5, 6.2,
4.8, 4.2, 3.5, 3.7, 5.2)
# Plotting the graph
plot(x, y, cex = 1, pch = 3,
xlab ="x", ylab ="y",
col ="black")
lines(x, y, col = "red")
输出: