实验6:初级绘图
一:实验目的与要求
1:了解R语言中各种图形元素的添加方法,并能够灵活应用这些元素。
2:了解R语言中的各种图形函数,掌握常见图形的绘制方法。
二:实验内容
【直方图】
Eg.1:画出cars数据集中speed的直方图
|------------------|
| hist(cars$speed) |
![](https://file.jishuzhan.net/article/1779369117942288385/273aa595a757ec88827d0ba8f50beeeb.webp)
【条形图】
Eg.1:VADeaths数据集的条形图------beside=T,horiz=F
|-------------------------------|
| barplot(VADeaths, beside = T) |
![](https://file.jishuzhan.net/article/1779369117942288385/f6b0413b99c663e67fda65ba7cc6cee9.webp)
Eg.2:VADeaths数据集的条形图------beside=F,horiz=T
|-------------------------------|
| barplot(VADeaths, beside = T) |
![](https://file.jishuzhan.net/article/1779369117942288385/d981e58ae32ce0a8f4b9b8c1b8586073.webp)
Eg.3:VADeaths数据集的条形图------beside=T,horiz=T
|------------------------------------------|
| barplot(VADeaths, beside = T, horiz = T) |
![](https://file.jishuzhan.net/article/1779369117942288385/db8d38e768db8503947020d9b9904fbf.webp)
【饼图】
Eg.1:数据集VADeaths展示不同人群死亡率的占比情况
|-------------------------------------------------------------------------------------------------------------------------------|
| percent <- colSums(VADeaths)*100/sum(VADeaths) pie(percent, labels = paste0(colnames(VADeaths),'\n',round(percent,2),'%')) |
![](https://file.jishuzhan.net/article/1779369117942288385/e257f4d80d6286190a2bb07751d165b2.webp)
【散点图】
Eg.1:cars数据集的速度与刹车距离的散点图,绘制方法1
|-------------------------------|
| plot(cars[, 1], cars[,2]) |
Eg.2:cars数据集的速度与刹车距离的散点图,绘制方法2
|------------|
| plot(cars) |
![](https://file.jishuzhan.net/article/1779369117942288385/b1446d040c2c76bed0649ae4ad4dae85.webp)
【散点矩阵图】
Eg.1:iris数据集为例,用pairs函数绘制散点矩阵图
|-------------------------------------------------------------------------------------------------------------|
| # 方法1 pairs(iris[,1:4]) # 方法2 pairs(~Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data=iris) |
![](https://file.jishuzhan.net/article/1779369117942288385/01c6587852a0c7e0fa8a53e85766cf95.webp)
【多变量相关矩阵图】
Eg.1:mtcars数据集绘图
|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| install.packages("corrgram") library(corrgram) corrgram(mtcars, order=TRUE, upper.panel=panel.ellipse, main="Correlogram of mtcars intercorrelations") corrgram(mtcars, order=TRUE, upper.panel=panel.pts, lower.panel=panel.pie,main="Correlogram of mtcars intercorrelations") corrgram(mtcars, order=TRUE, upper.panel=panel.conf, lower.panel=panel.cor,main="Correlogram of mtcars intercorrelations") |
[1] 相关图,主对角线上方绘制置信椭圆和平滑拟合曲线,主对角线下方绘制阴影
![](https://file.jishuzhan.net/article/1779369117942288385/72f3a126cb4c5bc031d5c44e81f5bd2d.webp)
[2] 相关图,主对角线上方绘制散点图,主对角线下方绘制饼图
![](https://file.jishuzhan.net/article/1779369117942288385/58334b32f275dceea2954c1f0dc9e628.webp)
[3] 相关图,主对角线上方绘制置信区间,主对角线下方绘制相关系数
![](https://file.jishuzhan.net/article/1779369117942288385/b292b55166b26f1ac1d1de6688cfdc30.webp)
【核密度图】
Eg.1:
|--------------------------------------------------------------------------------------|
| install.packages("sm") library(sm) sm.density.compare(mtcarswt, factor(mtcarscyl)) |
![](https://file.jishuzhan.net/article/1779369117942288385/68efe53d5af44b948ff0dd0d9fcabb6b.webp)
【小提琴图】
Eg.1:mtcars数据集wt的小提琴图
|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| install.packages("vioplot") library(vioplot) attach(mtcars) par(mfrow=c(1,2)) vioplot(wt[cyl == 4], wt[cyl == 6], wt[cyl == 8], border = "black", col = "lightgreen", rectCol = "blue", horizontal = TRUE) title(main = '小提琴图') boxplot(wt~cyl, main = '箱线图', horizontal=TRUE, pars=list(boxwex=0.1),border="blue") par(mfrow = c(1, 1)) |
![](https://file.jishuzhan.net/article/1779369117942288385/ed634b0871f4e1afcacad71973017c02.webp)
【QQ图】
Eg.1:mtcars数据集wt的QQ图
|---------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| qqnorm(wt) qqline(wt) qqplot(qt(ppoints(length(wt)), df = 5), wt,xlab = "Theoretical Quantiles", ylab = "Sample Quantiles", main = "Q-Q plot for t dsn") qqline(wt) |
![](https://file.jishuzhan.net/article/1779369117942288385/5c51073a94d5cbe2300c61b0e87b536a.webp)
![](https://file.jishuzhan.net/article/1779369117942288385/3d148fd2cdfad28ffb980228bafa2ca4.webp)
【星状图】
Eg.1:
|---------------------------------|
| stars(mtcars,draw.segments = T) |
![](https://file.jishuzhan.net/article/1779369117942288385/bd434ccb40f6b07a4272b1b76101762e.webp)
【等高图】
Eg.1:
|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| library(KernSmooth) mtcars1 = data.frame(wt, mpg) est = bkde2D(mtcars1, apply(mtcars1, 2, dpik)) contour(estx1, estx2, est$fhat, nlevels = 15, col = "darkgreen", xlab = "wt",ylab = "mpg") points(mtcars1) |
![](https://file.jishuzhan.net/article/1779369117942288385/1510dd9e6255f277b6a185277bc9bb18.webp)
![](https://file.jishuzhan.net/article/1779369117942288385/8bd13dede2a918bb784d54345dc8d014.webp)
【固定颜色选择函数】
Eg.1:查看前20种颜色
|------------------|
| colors()[1:20] |
![](https://file.jishuzhan.net/article/1779369117942288385/e31b62ee1b8f1df6d1272e80953f8101.webp)
Eg.2:打印657种颜色
|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| par(mfrow = c(length(colors())%/%60 + 1, 1)) par(mar=c(0.1,0.1,0.1,0.1), xaxs = "i", yaxs = "i") for(i in 1:(length(colors())%/%60 + 1)){ barplot(rep(1,60),col=colors()[((i-1)*60+1):(i*60)],border=colors()[((i-1)*60+1):(i*60)],axes=F) box() } |
![](https://file.jishuzhan.net/article/1779369117942288385/649e070037edcdcc67be74a01ba52f3c.webp)
Eg.3:固定调色板
|------------------------------------------------------------------|
| palette() palette(colors()[1:10]) palette() palette('default') |
![](https://file.jishuzhan.net/article/1779369117942288385/542a6f43884e3b79c5ddaf920aac122d.webp)
Eg.4:在不同Species使用不同的颜色绘制散点,以便区分种类
|-------------------------------------------------------------------------------------------------------------------------------------------------------------|
| # 方法1 plot(irisSepal.Length, irisSepal.Width, col = irisSpecies) # 方法2 plot(irisSepal.Length, iris$Sepal.Width, col = rep(palette()[1:3], each = 50)) |
![](https://file.jishuzhan.net/article/1779369117942288385/724fe4cc68d8f742ba380e0d0229c054.webp)
Eg.5:渐变色生成函数调色板的颜色样式
|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| rgb<-rgb(red=255,green=1:255,blue=0,max=255) par(mfrow=c(6,1)) par(mar=c(0.1,0.1,2,0.1), xaxs="i", yaxs="i") barplot(rep(1,255),col= rgb,border=rgb,main="rgb") barplot(rep(1,100),col=rainbow(100),border=rainbow(100),main="rainbow(100))") barplot(rep(1,100),col=heat.colors(100),border=heat.colors(100),main="heat.colors(100))") barplot(rep(1,100),col=terrain.colors(100),border=terrain.colors(100),main="terrain.colors(100))") barplot(rep(1,100),col=topo.colors(100),border=topo.colors(100),main="topo.colors(100))") barplot(rep(1,100),col=cm.colors(100),border=cm.colors(100),main="cm.colors(100))") |
![](https://file.jishuzhan.net/article/1779369117942288385/ce22634646a5083c25d5f1bc40fe0fe6.webp)
【RColorBrewer依赖包】
Eg.1:颜色展示
|-------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| par(mfrow = c(1,3)) library(RColorBrewer) par(mar=c(0.1,3,0.1,0.1)) display.brewer.all(type="seq") display.brewer.all(type="div") display.brewer.all(type="qual") |
![](https://file.jishuzhan.net/article/1779369117942288385/04e2cbf3a6a1570848a530502b577f8e.webp)
Eg.2:绘制颜色散点图
|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| library(RColorBrewer) par(mfrow = c(1,2)) my_col <- brewer.pal(3,'RdYlGn') plot(irisSepal.Length, irisSepal.Width, col = rep(my_col, each =50)) plot(irisSepal.Length, irisSepal.Width, col = rep(rainbow(3), each = 50)) |
![](https://file.jishuzhan.net/article/1779369117942288385/c76660af9b9dad9e70538823e49027a8.webp)
【axis函数绘图】
Eg.1:
|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| plot(c(1:12), col="white", xaxt="n", yaxt="n", ann = FALSE) axis(1, at=1:12, col.axis="red", labels=month.abb) axis(2, at=seq(1,12,length=10), col.axis="red", labels=1:10, las=2) axis(3, at=seq(1,12,length=7), col.axis="blue", cex.axis=0.7, tck=-0.01, labels = c("Mon", "Tues", "Wed", "Thu", "Fri", "Sat", "Sun")) axis(4, at=seq(1,12,length=11), col.axis="blue", cex.axis=0.7, tck=-0.01, labels=seq(0, 1, 0.1),las=2) |
![](https://file.jishuzhan.net/article/1779369117942288385/3f72011bd23e964b0b31e05c24084748.webp)
【legend函数绘制图例】
Eg.1:
|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| local=c("bottomright", "bottom", "bottomleft", "left", "topleft", "top", "topright", "right", "center") par(mar = c(4,2,4,2), pty='m') plot(c(0:10), col = "white") legend(3, 8, "图例在(3,8)") legend(1, 13, "图例在(11,11)", xpd=T) for(i in 1:9){ legend(local[i],paste("图例在",local[i])) } |
![](https://file.jishuzhan.net/article/1779369117942288385/831657a45c3840ea0760f621231e165f.webp)
【par函数】
Eg.1:
|-----------------------------------------------------------------------------------|
| mfrow1=par(mfrow=c(2,3)) for(i in 1:6){ plot(c(1:i),main=paste("I'm image:",i)) } |
![](https://file.jishuzhan.net/article/1779369117942288385/623accabb23bb4688d3763e0239c9d4d.webp)
【layout函数】
Eg.1:
|-----------------------------------------------------------------------------------------------------------------------------------|
| mat<-matrix(c(1,1,2,3,3,4,4,5,5,6), nrow = 2, byrow = TRUE) layout(mat) for(i in 1:6){ plot(c(1:i),main=paste("I'm image:",i)) } |
![](https://file.jishuzhan.net/article/1779369117942288385/0aa0d0e211020e64b5da002dd37afc74.webp)
【保存图形】
Eg.1:
|---------------------------------------------------------------------------------|
| jpeg(filename = "C:/Users/86158/Desktop/iris.jpg") plot(iris[,1:4]) dev.off() |
![](https://file.jishuzhan.net/article/1779369117942288385/1a2cf8aab1152c39beb2a00b0f92cd43.webp)
![](https://file.jishuzhan.net/article/1779369117942288385/291663250cf08652133f2211a50b7a07.webp)
Eg.2:657种颜色的打印并保存为PDF文件格式
|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| pdf("colors-bar.pdf", height=120) par(mar = c(0,10,3,0)+0.1,yaxs="i") barplot(rep(1, length(colors())), col = rev(colors()), names.arg=rev(colors()),horiz = T, las = 1, xaxt="n", main = expression("Bars of colors in"~ italic(colors()))) dev.off() |
![](https://file.jishuzhan.net/article/1779369117942288385/f87fa166fd2f327d1b5b80d3fb83cc56.webp)
![](https://file.jishuzhan.net/article/1779369117942288385/a51d8a305a851bd4ac4bda33536678c9.webp)
![](https://file.jishuzhan.net/article/1779369117942288385/a95cd72b5de8459cd095820404f4abfe.webp)
三:课堂练习
【练习1】PPT-08,第18页,iris箱线图
Eg.1:合并显示
|----------------------------------------------------------------------------------------------------------------------------|
| par(mfrow = c(1,2)) boxplot(iris[1:4], main = '单独的箱线图') boxplot(Sepal.Length ~ Species, data = iris, main = '组间比较的箱线图') |
![](https://file.jishuzhan.net/article/1779369117942288385/e2d8f7b464c221e00bb095764f161883.webp)
Eg.2:单独显示
|----------------------------------------------------------------------------------------------------------------------------|
| par(mfrow = c(1,1)) boxplot(iris[1:4], main = '单独的箱线图') boxplot(Sepal.Length ~ Species, data = iris, main = '组间比较的箱线图') |
![](https://file.jishuzhan.net/article/1779369117942288385/e61e60e6221a79d8f5e12e81a20089b1.webp)
![](https://file.jishuzhan.net/article/1779369117942288385/ee8af97cd80abccaebf98ce2a345bb68.webp)
【练习2】绘图散点图
Eg.1:
|------------------------------------------------------------------------------------------|
| attach(mtcars) # 绑定数据框mtcars plot(wt, mpg) # 打开图形窗口,绘制散点图 detach(mtcars) # 解除绑定数据框mtcars |
![](https://file.jishuzhan.net/article/1779369117942288385/31f3b767ecced88e4ded4c4fbcf7b551.webp)
【练习3】palette函数的应用
Eg.1:
|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| data(mtcars) par(mfrow = c(1, 1)) plot(mtcarswt, mtcarsmpg, col = "blue") plot(mtcarswt, mtcarsmpg, col = 4) attach(mtcars) str(mtcars) plot(wt, mpg, col = "red", xlim = c(1.3, 5.6), ylim = c(8, 35)) points(wt[cyl == 6], mpg[cyl == 6], col = "green") points(wt[cyl == 8], mpg[cyl == 8], col = "blue") legend(5, 35, c(4, 6, 8), pch = 1, col = c("red", "green", "blue"), bty = "n") |
![](https://file.jishuzhan.net/article/1779369117942288385/cd9a42898583198dfc08e2e060ddb6df.webp)
【练习4】渐变色生成函数
Eg.1:
|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| library(RColorBrewer) attach(mtcars) cl <- brewer.pal(3, "Dark2") # 左图代码,RColorBrewer包配色方案的使用 par(mfrow = c(1, 1)) plot(wt, mpg, col = cl[1]) points(wt[cyl == 6], mpg[cyl == 6], col = cl[2]) points(wt[cyl == 8], mpg[cyl == 8], col = cl[3]) legend(5, 35, c(4, 6, 8), pch = 1, col = cl, bty = "n") |
![](https://file.jishuzhan.net/article/1779369117942288385/bf287ff12a7f029e2914404a58d0d707.webp)
Eg.2:
|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| cl <- rainbow(3) # 右图代码,rainbow函数的使用 plot(wt, mpg, col = cl[1]) points(wt[cyl == 6], mpg[cyl == 6], col = cl[2]) points(wt[cyl == 8], mpg[cyl == 8], col = cl[3]) legend(5, 35, c(4, 6, 8), pch = 1, col = cl, bty = "n") |
![](https://file.jishuzhan.net/article/1779369117942288385/8b681a28cf81dd3dec9ccf84857e2ca7.webp)
【练习5】点的样式
Eg.1:
|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| plot(1, col = "white", xlim = c(1, 8), ylim = c(1, 7)) symbol <- c("*", "、", ".", "o", "O", "0", " + ", " - ", "|") # 创建循环添加点 for (i in c(0:34)) { x <- (i %/% 5) * 1 + 1 y <- 6 - (i %% 5) if (i > 25) { points(x, y, pch = symbol[i - 25], cex = 1.3) text(x + 0.5, y + 0.1, labels = paste("pch = ", symbol[i - 25]), cex = 0.8) } else { if (sum(c(21:25) == i) > 0) { points(x, y, pch = i, bg = "red", cex = 1.3) } else { points(x, y, pch = i, cex = 1.3) } text(x + 0.5, y + 0.1, labels = paste("pch = ", i), cex = 0.8) } } |
![](https://file.jishuzhan.net/article/1779369117942288385/b8351c49ed645d0afc7aa408ccaa3b57.webp)
【练习6】改变点的样式
Eg.1:
|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| attach(mtcars) # 绑定数据框mtcars cyl <- as.factor(cyl) plot(wt, mpg, col = "white") points(wt, mpg, pch = as.integer(cyl) + 1, col = as.integer(cyl) + 1) legend(5, 35, c(4, 6, 8), pch = 2:4, col = 2:4, bty = "n") |
![](https://file.jishuzhan.net/article/1779369117942288385/b3e95b44edee990c37a4ef6b9d3c8b48.webp)
Eg.2:
|---------------------------------------------------------------------------------------------------------------------------------------------------------------|
| plot(wt, mpg, pch = as.integer(cyl) + 1, col = as.integer(cyl) + 1) legend(5, 35, c(4, 6, 8), pch = 2:4, col = 2:4, bty = "n") detach(mtcars) # 解除绑定数据框mtcars |
运行结果:同上图。
【练习7】使用title()展示标题位置
Eg.1:
|----------------------------------------------------------------------------------------------------------------------------------------------------|
| plot(c(0:5), col = "white", xlab = "", ylab = "") title(main = list("主标题", cex = 1.5), sub = list("副标题", cex = 1.2), xlab = "x轴标题", ylab = "y轴标题") |
![](https://file.jishuzhan.net/article/1779369117942288385/517d4f9bdf3309c2946643ad4cb916b0.webp)
【练习8】使用text()展示字体样式、字体大小
Eg.1:
|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| plot(c(0:5), col = "white") text(2, 4, labels = "font = 1:正常字体(默认)", font = 1) text(3, 3, labels = "font = 2:粗体字体", font = 2) text(4, 2, labels = "font = 3:斜体字体", font = 3) text(5, 1, labels = "font = 4:粗斜体字体", font = 4) # 大小 plot(c(0:6), col = "white", xlim = c(1, 8)) text(2, 5, labels = "cex = 0.5:放大0.5倍", cex = 0.5) text(3, 4, labels = "cex = 0.8:放大0.8倍", cex = 0.8) text(4, 3, labels = "cex = 1(默认):正常大小", cex = 1) text(5, 2, labels = "cex = 1.2:放大1.2倍", cex = 1.2) text(6, 1, labels = "cex = 1.5:放大1.5倍", cex = 1.5) |
![](https://file.jishuzhan.net/article/1779369117942288385/4e4c7c745bf1a7e72bc440899a3c75a1.webp)
【练习9】mtext()展示文本位置
Eg.1:
|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| plot(c(0:5), col = "white") mtext("side = 1:下边", side = 1, line = 2); mtext("side = 2:左边" , side = 2, line = 2) mtext("side = 3:上边", side = 3); mtext("side = 4:右边" , side = 4) |
![](https://file.jishuzhan.net/article/1779369117942288385/762c0879fb2f8cbeea0279b47e9f0df8.webp)
【练习10】以mtcars数据集为例,将散点图变为文本字符
Eg.1:
|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| cyl <- as.factor(cyl) plot(wt, mpg, col = "white", xlab = "", ylab = "") text(wt, mpg, cyl, col = as.integer(cyl) + 1) title(main = list("Miles per Gallon vs. Weight by Cylinder", cex = 1.5), xlab = "Weight", ylab = "Miles per Gallon") |
![](https://file.jishuzhan.net/article/1779369117942288385/e6f2ef40e2b12de893d68ddfaea52407.webp)
Eg.2:
|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| plot(wt, mpg, pch = as.character(cyl), col = as.integer(cyl) + 1, xlab = "Weight", ylab = "Miles per Gallon ", main = "Miles per Gallon vs. Weight by Cylinder", cex.main = 1.5) |
运行结果:同上图。
【练习11】线的样式和线的宽度
Eg.1:线的样式
|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| data <- matrix(rep(rep(1:7), 10), ncol = 10, nrow = 7) plot(data[1, ], type = "l", lty = 0, ylim = c(1, 8), xlim = c(-1, 10), axes = F) text(0, 1, labels = "lty = 0") for (i in c(2:7)) { lines(data[i, ], lty = i - 1) text(0, i, labels = paste("lty = ", i - 1)) } |
![](https://file.jishuzhan.net/article/1779369117942288385/68661097fc83e948285cf9576813cb96.webp)
Eg.2:线的宽度
|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| data <- matrix(rep(rep(1:6), 10), ncol = 10, nrow = 6) plot(data[1, ], type = "l", lwd = 0.5, ylim = c(1, 8), xlim = c(-1, 10), axes = F); text(0, 1, labels = "lwd = 0.5") lines(data[2, ], type = "l", lwd = 0.8);text(0, 2, labels = "lwd = 0.8") lines(data[3, ], type = "l", lwd = 1);text(0, 3, labels = "lwd = 1") lines(data[4, ], type = "l", lwd = 1.5);text(0, 4, labels = "lwd = 1.5") lines(data[5, ], type = "l", lwd = 2);text(0, 5, labels = "lwd = 2") lines(data[6, ], type = "l", lwd = 4);text(0, 6, labels = "lwd = 4") |
![](https://file.jishuzhan.net/article/1779369117942288385/1765f4e1cb3f94146052d9e2b9ee649a.webp)
【练习12】添加参考线
Eg.1:
|------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| # 绘制空白画布 plot(c(0:10), col = "white") # 添加水平线 abline(h = c(2, 6, 8)) # 添加垂直线 abline(v = seq(2, 10, 2), lty = 2, col = "blue") # 添加直线y = 2+x abline(a = 2, b = 1) |
![](https://file.jishuzhan.net/article/1779369117942288385/cd835459a893ad7a551d2bc5da2ecfca.webp)
【练习13】添加线段和箭头
Eg.1:
|-----------------------------------------------------------------------------------------------------------------|
| plot(c(0:10), col = "white") segments(2, 1, 4, 8) arrows(4, 0, 7, 3, angle = 30) arrows(4, 2, 7, 5, angle = 60) |
![](https://file.jishuzhan.net/article/1779369117942288385/7a619041e8a95161f925f5ef4f45e07d.webp)
【练习14】添加网格线
Eg.1:
|--------------------------------------------------------------------------------------------------|
| plot(c(0:10), col = "white") # 空白画布 grid(nx = 4, ny = 8, lwd = 1, lty = 2, col = "blue") # 添加网格线 |
![](https://file.jishuzhan.net/article/1779369117942288385/4330a347039b6598f0c9c9b80580fd10.webp)
【练习15】添加坐标轴须
Eg.1:
|-----------------------------------------------------------------------------------------------------------------|
| set.seed(123) # 种子 x <- rnorm(500) # 生成500个标准正态分布的数据 plot(density(x)) # 绘制核密度曲线 rug(x , col = "blue") # 添加坐标轴须 |
![](https://file.jishuzhan.net/article/1779369117942288385/5f91b466fd422d4b92a0566883c5ff4a.webp)
【练习16】以mtcars数据集为例查看不同的线元素函数的用法
Eg.1:
|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| smpg <- (mpg - min(mpg)) / (max(mpg) - min(mpg)) plot(wt, smpg, ylab = "standardized mpg") # 添加核密度曲线图 lines(density(wt), col = "red") # 指向密度曲线的箭头 arrows(1.8, 0.05, 1.5, 0.1, angle = 10, cex = 0.5) text(2, 0.05, "核密度曲线", cex = 0.6) # 添加回归线 abline(lm(smpg ~ wt), lty = 2, col = "green") # 指向回归直线的箭头 arrows(2, 0.5, 2, 0.7, angle = 10, cex = 0.5) text(2, 0.45, "回归线", cex = 0.6) # wt与mpg反向线性相关,添加最大最小值线段表现这种关系 segments(min(wt), max(smpg), max(wt), min(smpg), lty = 3, col = "blue") # 指向最大最小值线段的箭头 arrows(3, 0.8, 2.5, 0.76, angle = 10, cex = 0.5) text(3.3, 0.8, "最大最小值线段", cex = 0.6) # 添加网格线作为背景 grid(nx = 4, ny = 5, lty = 2, col = "grey") |
![](https://file.jishuzhan.net/article/1779369117942288385/a66c21c3fe19852a2875ab0362a6a34e.webp)
Eg.2:
|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| par(mfrow = c(1, 3)) plot(density(wt), col = "red") # 绘制核密度曲线 plot(wt, fitted(lm(mpg ~ wt)), type = "l", lty = 2, col = "green") # 绘制回归线 plot(seq(min(wt), max(wt), length = 100), seq(max(mpg), min(mpg), length = 100), type = "l", lty = 3, col = "blue") # 绘制最大、最小值线 |
![](https://file.jishuzhan.net/article/1779369117942288385/5515107c7861af029d2d12942a63ac74.webp)
【练习17】输出到屏幕
Eg.1:
|----------------------------------------------------------------------------------|
| windows() # 打开图形设备界面 attach(mtcars) plot(wt, mpg) X11() # 打开图形设备界面 plot(wt, mpg) |
![](https://file.jishuzhan.net/article/1779369117942288385/115de6c63441f6d32677f2ad50668ca1.webp)
【练习18】以mtcars为例,生成的直方图
Eg.1:
|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| op <- par(mfrow = c(2, 3), mar = c(4, 4, 2, 0.5), mgp = c(2, 0.5, 0)) hist(wt, main = "freq = TRUE") # 默认的频数直方图,左下,中上,中下,右上,右下 hist(wt, breaks = 5, main = "breaks = 5") # 减小区间段数的直方图 hist(wt, col = "light blue", main = "colored") # 给直方图的柱形添加颜色 hist(wt, freq = FALSE, main = "freq = FALSE") # 概率密度直方图 hist(wt, breaks = 40, main = "breaks = 40") # 增大区间段数的直方图 # 在直方图上添加密度曲线和正态分布概率密度曲线 hist(wt, freq = FALSE, main = "with density curve and normal curve") lines(density(wt), col = "blue") lines(density(rnorm(1e+6, mean(wt), sd(wt))), lty = 2, col = "red") par(op) |
![](https://file.jishuzhan.net/article/1779369117942288385/3c4676b7f54066262a1318598b3ebc7e.webp)
【练习19】绘图箱线图
Eg.1:
|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| set.seed(1234) normal <- rnorm(100, mean(wt), sd(wt)) # 生成100个正态分布数据 op <- par(mfrow = c(1, 3)) boxplot(list(wt, normal), xaxt = "n") # 绘制箱线图 axis(1, at = 1:2, labels = c("wt", "normal")) # 添加坐标轴 rug(wt, side = 2, col = 2); rug(normal, side = 4, col = 3) # 添加坐标轴须 legend("bottomleft", c("wt", "normal"), lty = 1, col = 2:3, bty = "n") # 添加图例 boxplot(list(wt, normal), xaxt = "n", varwidth = TRUE) rug(wt, side = 2, col = 2); rug(normal, side = 4, col = 3) axis(1, at = 1:2, labels = c("wt", "normal")) legend("bottomleft", c("wt", "normal"), lty = 1, col = 2:3, bty = "n") boxplot(wt ~ cyl) rug(wt[cyl == 4], side = 2, col = 2); rug(wt[cyl == 6], side = 4, col = 3) rug(wt[cyl == 8], side = 2, col = 4) legend("topleft", c("4", "6", "8"), lty = 1, col = 2:4, bty = "n") par(op) |
![](https://file.jishuzhan.net/article/1779369117942288385/1c47a5f0987c2dcbd89b6a64b67bf83b.webp)
【练习20】绘图小提琴图
Eg.1:
|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| # 页面分割掉1/2,为与箱线图和核密度图对比而作,小提琴图只需要第二个语句即可 par(fig = c(0, 1, 0.5, 1), mfrow = c(2, 1)) # 绘制小提琴图 library(vioplot) vioplot(wt[cyl == 4], wt[cyl == 6], wt[cyl == 8], border = "black", col = "light green", rectCol = "blue", horizontal = TRUE) # 分割另外1/2页面 par(fig = c(0, 1, 0, .5), mar = c(0, 2, 0, 0.5) , new = TRUE) # 绘制箱线图 boxplot(wt ~ cyl, horizontal = TRUE, pars = list(boxwex = 0.1), border = "blue") # 在箱线图上叠加核密度图 par(fig = c(0, 0.53, 0.1, 0.2), new = TRUE) plot(density(wt[cyl == 4], bw = 0.3), xaxt = "n", yaxt = "n", ann = FALSE, bty = "n") par(fig = c(0.26, 0.56, 0.25, 0.35), new = TRUE) plot(density(wt[cyl == 6], bw = 0.3), xaxt = "n", yaxt = "n", ann = FALSE, bty = "n") par(fig = c(0.33, 1, 0.4, 0.5), new = TRUE) plot(density(wt[cyl == 8], bw = 0.5), xaxt = "n", yaxt = "n", ann = FALSE, bty = "n") |
![](https://file.jishuzhan.net/article/1779369117942288385/dc5950a42685c47363e5bae6a3cfa244.webp)
【练习21】绘图条形图
Eg.1:
|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| bardata <- table(cyl, carb) # 得到表格数据 pal <- RColorBrewer::brewer.pal(3, "Set1") # 颜色调配 op <- par(mfrow = c(2, 2), mar = c(3, 3, 3, 2), mgp = c(1.5, 0.5, 0)) barplot(bardata, col = pal, beside = TRUE, xlab = "carb") # 分组条形图 legend("topright", c("4", "6", "8"), pch = 15, col = pal, bty = "n") barplot(bardata, col = pal, xlab = "carb") # 默认堆砌条形图 legend("topright", c("4", "6", "8"), pch = 15, col = pal, bty = "n") barplot(bardata, col = pal, beside = TRUE, horiz = TRUE, ylab = "carb") # 水平放置的条形图 legend(5.3, 26, c("4", "6", "8"), pch = 15, col = pal, bty = "n", cex = 0.6) barplot(bardata, col = pal, beside = TRUE, ylim = c(0, 7), xlab = "carb") legend("topright", c("4", "6", "8"), pch = 15, col = pal, bty = "n") # 显示数值 text(labels = as.vector(bardata), cex = 0.7, x = c(1.5:23.5)[1:23 %% 4 > 0], y = as.vector(bardata) + 0.5) par(op) |
![](https://file.jishuzhan.net/article/1779369117942288385/393973f5ef32b848c0014a84de0d6610.webp)
【练习22】绘图点图
Eg.1:
|-----------------------------|
| dotchart(bardata, bg = pal) |
![](https://file.jishuzhan.net/article/1779369117942288385/b608495f872b253db50c9b6030909e2a.webp)
【练习23】绘图饼图
Eg.1:
|-------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| percent <- as.vector(table(cyl)) / sum(as.vector(table(cyl))) * 100 # 计算百分比 pie(table(cyl), labels = paste(c("4", "6", "8"), "cylinders:", percent, "%")) # 画饼图 |
![](https://file.jishuzhan.net/article/1779369117942288385/ff9f7fc9aa5a7afdc312656ba94cb257.webp)
【练习24】用methods()查plot()的作图方法
Eg.1:
|-----------------|
| methods("plot") |
![](https://file.jishuzhan.net/article/1779369117942288385/04340fc83f5d8ed12bf074908b4806f3.webp)
【练习25】plot()函数的应用
Eg.1:
|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| plot(density(wt), type = "l") class(density(wt)) # 第一个参数density类,画核密度曲线 plot(table(cyl, vs)); class(table(cyl, vs)) # 第一个参数table类,画马赛克图 opr <- par(mfrow = c(2, 3), mar = c(4, 4, 2, 4)) for (i in 1:6) { plot(lm(mpg ~ wt), i) # 第一个参数lm类,画回归诊断图 } par(opr); class(lm(mpg ~ wt)) plot(mtcars[, c(1, 3:7)]) class(mtcars[, c(1, 3:7)]) # 第一个参数data.frame类,画散点图矩阵 |
![](https://file.jishuzhan.net/article/1779369117942288385/112d8a364b4ad32e84497ce554994cde.webp)
![](https://file.jishuzhan.net/article/1779369117942288385/06cb0c703cd8f022b4851ec2b72659fa.webp)
![](https://file.jishuzhan.net/article/1779369117942288385/2b1c2bc96f571067ffa16bfe5cb20ebd.webp)
![](https://file.jishuzhan.net/article/1779369117942288385/181c519522462d311648071c541143d1.webp)
![](https://file.jishuzhan.net/article/1779369117942288385/f58e4b7d2f09445da913bfdf23b20f2f.webp)
Eg.2:
|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| x <- seq(from = 0, to = 2*pi, length = 10) # 取10个x值 y <- sin(x) # 计算相对应的y值 type <- c("p", "l", "b", "o", "c", "h", "s", "S", "n" ) # 图形类型向量 op <- par(mfrow = c(3, 3), mar = c(4, 4, 1, 1)) for (i in 1:9) { plot(x, y, type = type[i] , main = paste("type:", type[i])) } par(op) |
![](https://file.jishuzhan.net/article/1779369117942288385/b50d1041d45bfc6a0c5bf4b57202b2da.webp)
【练习26】绘图散点图矩阵
Eg.1:绘图对象为公式
|-------------------------------------------------------------------------------------------------------------------|
| pairs( ~ mpg + disp + drat + wt, data = mtcars, col = as.integer(factor(cyl)) + 1, main = "Scatter Plot Matrix") |
![](https://file.jishuzhan.net/article/1779369117942288385/032a8e9f2fcce89840aae50976656df3.webp)
Eg.2:绘图对象为数据框
|---------------------------------------------------------------------------------------------------|
| pairs(mtcars[, c(1, 3, 5, 6)], col = as.integer(factor(cyl)) + 1, main = "Scatter Plot Matrix") |
运行结果:同上图。
Eg.1:
|----------------------------------------------------------------------------------------------------------------------|
| mosaicdata <- ftable(cyl, vs) # 二维列联表 par(mfrow = c(1, 1)) mosaicplot(mosaicdata, shade = TRUE, main = "") # 绘制马赛克图 |
![](https://file.jishuzhan.net/article/1779369117942288385/7187b9ba2db9522125a9ca8d4fa7263b.webp)
【练习28】绘图向日葵散点图
Eg.1:
|-----------------------------------------------------------------|
| sunflowerplot(mpg, cyl, col = "green", seg.col = "light green") |
![](https://file.jishuzhan.net/article/1779369117942288385/cfbdd8f9a15d9372961f03a10a32f273.webp)
【练习29】绘图热图
Eg.1:
|---------------------------------------------------------|
| heatmap(as.matrix(mtcars), col = pal, scale = "column") |
![](https://file.jishuzhan.net/article/1779369117942288385/72b501e4f63388e5219eff870e74fa3c.webp)
四:实验知识点总结
1:初级绘图主要包括以下四个部分------绘制基础图形、修改图形参数、绘制组合图形、保存图形。
2:分析数据分布情况时,可以使用直方图、条形图、饼图、箱线图、散点图等图形。相关图形的使用函数和功能如下图所示。
![](https://file.jishuzhan.net/article/1779369117942288385/deeb483843493d5d89b0129d8e522e1c.webp)
3:R语言绘图函数分类,如下图所示。
![](https://file.jishuzhan.net/article/1779369117942288385/ff7dc87b4f4918483da7878d03589811.webp)
五:遇到的问题和解决方法
**问题1:**在PPT08,第84页中,jpeg设置保存的路径和文件名称、类型处运行会出错。具体的报错如下图所示。
![](https://file.jishuzhan.net/article/1779369117942288385/80f206ee119cd77ece1ee63b51426032.webp)
**解决1:**经过查询后,发现jpeg函数中参数应该是【filename】而不是【filenames】,修改之后即可通过。
**问题2:**安装包可能因为镜像源的问题而无法下载。
**解决2:**换源,可使用【chooseCRANmirror()】代码。