# R语言基础教程3：曲线图、误差线和图例

### 一、曲线图

set.seed(1000)
datax <- as.matrix(na.omit(airquality))
x <- sample(1:nrow(datax), 20)
y1 <- datax[x, 1]
y2 <- datax[x, 2]
labs <- c("Ozone", "Solar.R")

1、用plot函数先绘制出不含数据点和标题的图形区。使用参数type="n"就可以不绘制数据点：

x <- 1:length(y1)
plot(x, y1, type = "n", xlab = "", ylab = "", ylim = range(y1, y2) * c(0.5,
1.15))

2、后面可以从容地添加其他数据和图形元素。基本方法和前面介绍散点图的方法是相同的，只是points函数引入了新参数“type”，表示图形种类。这个参数在plot函数里面也是可以使用的。

points(x, y1, type = "o", pch = 1, col = "red", lty = 1, lwd = 2)
points(x, y2, type = "o", pch = 2, col = "seagreen", lty = 1, lwd = 2)
title(main = "The Figure Title", xlab = "X Label", ylab = "Y Label")

type = "p" ：散点图
type = "l" ：曲线图
type = "b" ：包含点的曲线图
type = "c" ：类型b去掉点
type = "o" : 也是曲线图，线穿过点
type = "h" ：垂直线
type = "s" ：阶梯图
type = "S" ：另外一种阶梯图
type = "n" ：不绘制数据

### 二、误差线

R base绘图包里面没有直接绘制误差线的函数，不知道为什么。但是要设置误差线其实也很简单，写个绘制误差线的小函数:

plot.error <- function(x, y, sd, len = 1, col = "black") {
len <- len * 0.05
arrows(x0 = x, y0 = y, x1 = x, y1 = y - sd, col = col, angle = 90, length = len)
arrows(x0 = x, y0 = y, x1 = x, y1 = y + sd, col = col, angle = 90, length = len)
}

plot.error(x, y1, sd = y1 * 0.1, col = "red")
plot.error(x, y2, sd = y2 * 0.1, col = "seagreen")

### 三、图例设置

legend("top", legend = labs, cex = 0.8, lty = 1, lwd = 2, pch = c(1, 2), col = c("red",
"seagreen"), inset = 0.01, horiz = TRUE, box.col = "white")

### 四、平滑曲线

x <- 1:length(y1)
plot(x, y1, pch = 1, col = "red", ylim = range(y1, y2) * c(0.5, 1.15))
lines(spline(x, y1, n = 1000, method = "fmm"), col = "red")
points(x, y2, pch = 2, col = "seagreen")
lines(spline(x, y2, n = 1000, method = "natural"), col = "seagreen")
plot.error(x, y1, sd = y1 * 0.1, col = "red")
plot.error(x, y2, sd = y2 * 0.1, col = "seagreen")
legend("topright", legend = labs, cex = 0.8, lty = 1, pch = c(1, 2), col = c("red",
"seagreen"), inset = 0.01, box.col = "white")

• 本文由 整理发表
• 网站部分文章源自互联网，若未正确标注来源，请联系管理员更新。文章转载，请务必保留本文链接