# 使用 R 中的 Lines() 函数在绘图中添加一条线

Jinku Hu 2024年2月15日

## 在 R 中使用 `lines()` 函数的绘图中添加一条线

`lines()` 函数是 R `graphics` 包的一部分，用于向绘图添加线条。首先，应该调用 `plot` 函数来构造一个图，其中有一个由前两个参数指定的变量映射。请注意，表示 y 轴坐标的第二个参数是可选的。绘制绘图后，我们可以调用 `lines()` 函数并根据需要传递坐标向量以将线条添加到绘图中。`plot` 函数不需要为 `lines()` 函数绘制折线图。

``````library(stats)
library(babynames)
library(dplyr)

plot(cars\$speed, cars\$dist, type = "l", col = "red",
main = "Title of the Plot",
xlab = "Speed (mph)",
ylab = "Stopping Distance (Feet)")

lines(cars\$speed, cars\$dist/4 , col = "green")

legend("topleft", c("line 1", "line 2"),
lty = c(1,1),
col = c("red", "green"))
``````

## 在 R 中使用 `points` 的绘图中添加点

`lines()` 函数类似，`graphics` 包提供了 `points()` 函数来在图中绘制点。以下示例演示了在同一绘图上进行两条线和点映射的场景。但是请注意，原始折线图是使用 `plot` 函数绘制的。

``````library(stats)
library(babynames)
library(dplyr)

plot(cars\$speed, cars\$dist, type = "l", col = "red",
main = "Title of the Plot",
xlab = "Speed (mph)",
ylab = "Stopping Distance (Feet)")
points(cars\$speed, cars\$dist, col = "blue" )

lines(cars\$speed, cars\$dist/4 , col = "green")
points(cars\$speed, cars\$dist/4 , col = "black")

legend("topleft", c("line 1", "line 2"),
lty = c(1,1),
col = c("red", "green"))
``````

## `plot` 和 `lines` 函数调用顺序影响绘图的比例

``````library(stats)
library(babynames)
library(dplyr)

dat <- babynames %>%
filter(name %in% c("Alice")) %>% filter(sex=="F")
dat2 <- babynames %>%
filter(name %in% c("Mary")) %>% filter(sex=="F")

plot(dat\$year, dat\$n, type = "l", col = "blue",
main = "Women born with different names",
xlab = "Year",
ylab = "Number of babies born")
lines(dat2\$year, dat2\$n, col = "red")
``````

``````library(stats)
library(babynames)
library(dplyr)

dat <- babynames %>%
filter(name %in% c("Alice")) %>% filter(sex=="F")
dat2 <- babynames %>%
filter(name %in% c("Mary")) %>% filter(sex=="F")
dat3 <- babynames %>%
filter(name %in% c("Mae")) %>% filter(sex=="F")

plot(dat2\$year, dat2\$n, type = "l", col = "blue",
main = "Women born with different names",
xlab = "Year",
ylab = "Number of babies born")
lines(dat\$year, dat\$n, col = "red")
lines(dat3\$year, dat3\$n, col = "orange")

legend("topright", c("Mary", "Alice", "Mae"),
lty = c(1,1,1),
col = c("blue", "red", "orange"))
``````

DelftStack.com 创始人。Jinku 在机器人和汽车行业工作了8多年。他在自动测试、远程测试及从耐久性测试中创建报告时磨练了自己的编程技能。他拥有电气/电子工程背景，但他也扩展了自己的兴趣到嵌入式电子、嵌入式编程以及前端和后端编程。