一、曲线图
从R自带的airquality中获取一些数据做示例:
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")
上面的points函数也可以用lines函数代替。改变plot( )、points( )或lines( )函数的type参数可以获得不同类型图形。type参数的意义:
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) }
然后就可以直接使用了,用数据的10%作为误差示例:
plot.error(x, y1, sd = y1 * 0.1, col = "red") plot.error(x, y2, sd = y2 * 0.1, col = "seagreen")
除这种直接的方法外,有人编写的一些用于R软件包提供了误差棒设置功能,比如gplots和ggplot2。以后再说。
三、图例设置
对于包含多系列数据,上面的图形还缺少一个元素:图例。它的设置函数是legend( ),有很多参数。
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")
四、平滑曲线
用spline函数获取平滑数据,再用lines/points/curve等函数可以做出平滑曲线,但spline函数要求x值是递增的:
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")
原文来自:http://blog.csdn.net/u014801157/article/details/24372327