R语言绘图函数汇总

来源:互联网 发布:数据库的配置 编辑:程序博客网 时间:2024/06/03 10:30
pre name="code" class="java"><pre name="code" class="plain">#数据准备------------  
  1. install.packages("vcd")  
  2. library(vcd)  
  3.   
  4. #6.1 条形图-------------  
  5. #6.1.1 简单条形图----------  
  6. (counts <- table(Arthritis$Improved))  
  7. barplot(counts,main="Simple Bar Plot",xlab = "Improved",ylab = "Frequency")  
  8. barplot(counts,main = "Horizontal Bar Plot",xlab = "Frequency",ylab = "Improved",  
  9.         horiz = T)  
  10. #6.1.2 堆积和分组条形图-------  
  11. (counts <- table(Arthritis$Improved,Arthritis$Treatment))  
  12. barplot(counts,main = "Stacked Bar Plot",xlab = "Treatment",ylab = "Frequency",  
  13.         col = c("red","yellow","green"),legend = rownames(counts))  
  14. barplot(counts,main = "Grouped Bar Plot",xlab = "Treatment",ylab = "Frequency",  
  15.         col = c("red","yellow","green"),legend = rownames(counts),beside = T)  
  16.   
  17. #6.1.3 均值条形图-----------  
  18. states <- data.frame(state.region,state.x77)  
  19. (means <- aggregate(states$Illiteracy,by = list(states$state.region),mean))  
  20. (means <- means[order(means$x),])  
  21. barplot(means$x,names.arg = means$Group.1)  
  22. title("Mean Illiteracy Rate")  
  23. #6.1.4 条形图微调----------  
  24. library(vcd)  
  25. par(mar = c(5,8,4,2))  
  26. par(las = 2)  
  27. (counts <- table(Arthritis$Improved))  
  28. barplot(counts,main = "Treament Outcome",horiz = T,cex.names = 0.8,  
  29.         names.arg = c("No Improvement","Some Improvement","Marked Improvement"))  
  30. #6.1.5 棘状图(堆叠条形图,但是高度为1)------------  
  31. library(vcd)  
  32. attach(Arthritis)  
  33. counts <- table(Treatment,Improved)  
  34. spine(counts,main = "Spinogram Example")  
  35. detach(Arthritis)  
  36.   
  37. #6.2 饼图----------  
  38. par(mfrow = c(2,2))  
  39. par(mar = c(5.1,4.1,4.1,2.1))  
  40. slices <- c(10,12,4,16,8)  
  41. lbls <- c("US","UK","Australia","Germany","France")  
  42. pie(slices,labels = lbls,main = "Simple Pie Chart")  
  43. #  
  44. pct <- round(slices/sum(slices)*100)  
  45. (lbls2 <- paste(lbls," ",pct,"%",sep = ""))  
  46. pie(slices,labels = lbls2,col = rainbow(length(slices)),  
  47.     main = "Pie Chart With Percentages")  
  48. #使用plotrix包做3D饼图  
  49. install.packages("plotrix")  
  50. library(plotrix)  
  51. pie3D(slices,labels = lbls,explode = 0.1,main = "3D Pie Chart")  
  52. #使用table做pie图  
  53. mytable <- table(state.region)  
  54. lbls3 <- paste(names(mytable),"\n",mytable,sep="")  
  55. pie(mytable,labels = lbls3,main = "Pie Chart from a Table\n (with sample sizes)")  
  56. #扇形图  
  57. fan.plot(slices,labels = lbls,main = "Fan Plot")  
  58.   
  59. #6.3 直方图---------  
  60. par(mfrow = c(2,2))  
  61. hist(mtcars$mpg)  
  62. #breaks参数,将横轴分成多少分  
  63. hist(mtcars$mpg,breaks = 12,col = "red",xlab = "Miles Per Gallon",  
  64.      main = "Colored histogram with 12 bins")  
  65. #注意下面的参数freq,freq设置为FALSE之后,y轴表示的是百分比,不是频数  
  66. hist(mtcars$mpg,freq = F,breaks = 12,col = "red",xlab = "Miles Per Gallon",  
  67.      main = "Histogram,rug polt,density curve")  
  68. rug(jitter(mtcars$mpg))  
  69. lines(density(mtcars$mpg),col = "blue",lty = 2)  
  70. #将图形付给参数,可以得到图形的细节,h <- hist(....)  
  71. x <- mtcars$mpg  
  72. h <- hist(x,breaks = 12,col = "red",xlab = "Miles Par Gallon",  
  73.           main = "Histogram with normal curve and box")  
  74. (xfit <- seq(min(x),max(x),length = 40))  
  75. yfit <-dnorm(xfit,mean = mean(x),sd = sd(x))  
  76. yfit <- yfit*diff(h$mids[1:2])*length(x)  
  77. lines(xfit,yfit,col = "blue",lty = 2)  
  78. box()  
  79.   
  80. #6.4 核密度图--------------  
  81. par(mfrow = c(2,1))  
  82. d <- density(mtcars$mpg)  
  83. plot(d)  
  84. plot(d,main = "Kernal Density of Miles Per Gallon")  
  85. polygon(d,col = "red",border = "blue")  
  86. rug(mtcars$mpg,col = "brown")  
  87. #使用sm包在一个图中做多组密度图  
  88. par(mfrow = c(1,1))  
  89. par(lwd=2)  
  90. install.packages("sm")  
  91. library(sm)  
  92. attach(mtcars)  
  93. (cyl.f <- factor(cyl,levels = c(4,6,8),labels = c("4 cylinder","6 cylinder","8 cylinder")))  
  94. sm.density.compare(mpg,cyl,xlab = "Miles Per Gallon")  
  95. title(main = "MPG Distribution by Car Cylinders")  
  96. colfill <- c(2:length(levels(cyl.f)))  
  97. legend(locator(1),levels(cyl.f),fill = colfill)  
  98. detach(mtcars)  
  99.   
  100. #6.5 箱线图---------  
  101. boxplot(mtcars$mpg,main = "Box Plot",ylab = "Miles per Gallon")  
  102. #输出箱图的信息  
  103. boxplot.stats(mtcars$mpg)  
  104. #6.5.1 使用箱图进行比较--------  
  105. boxplot(mpg~cyl,data = mtcars,main = "Car Mileage Data",xlab = "Number of Cylinders",  
  106.         ylab = "Miles Per Gallon")  
  107. #varwidth=T使得箱图的宽度和他们的容量成正比  
  108. boxplot(mpg~cyl,data = mtcars,main = "Car Mileage Data",xlab = "Number of Cylinders",  
  109.         ylab = "Miles Per Gallon",notch = TRUE,varwidth = T,col = "red")  
  110. #交叉因子箱图  
  111. mtcars$cyl.f <- factor(mtcars$cyl,levels = c(4,6,8),labels = c("4","6","8"))  
  112. mtcars$am.f <- factor(mtcars$am,levels = c(0,1),labels = c("auto","standard"))  
  113. boxplot(mpg~cyl.f*am.f,data = mtcars,varwidth = T,col = c("gold","darkgreen"),  
  114.         main = "MPG Distribution by Auto Type",xlab = "Auto Type")  
  115. #6.5.2 小提琴图----------  
  116. #这里使用到的包是vioplot  
  117. install.packages("vioplot")  
  118. library(vioplot)  
  119. x1 <- mtcars$mpg[mtcars$cyl == 4]  
  120. x2 <- mtcars$mpg[mtcars$cyl == 6]  
  121. x3 <- mtcars$mpg[mtcars$cyl == 8]  
  122. vioplot(x1,x2,x3,names = c("4 cyl","6 cyl","8 cyl"),col = "gold")  
  123. title("Violin Plots of Miles Per Gallon")  
  124.   
  125. #6.6 点图----------  
  126. #cex参数的作用是设置问文本的尺寸  
  127. dotchart(mtcars$mpg,labels = row.names(mtcars),cex = .7,  
  128.          main = "Gas Mileage for Car Models",xlab = "Miles Per Gallon")  
  129. #分组、排序、着色后的点图  
  130. x <- mtcars[order(mtcars$mpg),]  
  131. x$cyl <- factor(x$cyl)  
  132. x$color[x$cyl == 4] <- "red"  
  133. x$color[x$cyl == 6] <- "blue"  
  134. x$color[x$cyl == 8] <- "darkgreen"  
  135. dotchart(x$mpg,labels = row.names(x),cex = .7,groups = x$cyl,  
  136.          gcolor = "black",#gcolor 参数表示groupcolor  
  137.          color = x$color,pch = 19,#pch参数设置点的类型  
  138.          main = "Gas Mileage for Car Models\ngrouped by cylinder",  
  139.          xlab = "Miles Per Gallon")  
  140.   
  141. #11.1 散点图--------  
  142. attach(mtcars)  
  143. plot(wt,mpg,main = "Basic Scatter plot of MPG vs. Weight",xlab = "Car Weight (lbs/1000)",  
  144.      ylab = "Miles Per Gallon",pch = 10)  
  145. abline(lm(mpg~wt),col = "red",lwd = 2,lty = 1)  
  146. lines(lowess(wt,mpg),col = "blue",lwd = 2,lty = 2)  
  147. #使用car包做更加复杂的散点图,这个图比较难看懂,没什么用  
  148. install.packages("car")  
  149. library(car)  
  150. scatterplot(mpg~wt|cyl,data = mtcars,  
  151.             lwd = 2,  
  152.             main = "Scatter Plot of MPG vs. Weight # Cylinders",  
  153.             xlab = "Weight of Car (lbs/1000)",  
  154.             ylab = "Miles Per Gallon",  
  155.             legend.plot = T,  
  156.             id.method = "identify",  
  157.             labels = row.names(mtcars),  
  158.             boxplots = "xy")  
  159. #11.1.1 散点图矩阵-------  
  160. #upper.panel = NULL 设置矩阵只显示下矩阵  
  161. pairs(~mpg+disp+drat+wt,data = mtcars,main = "Basic Scatter Plot Matrix",upper.panel = NULL)  
  162. #car包中的scatterplotMatrix() 函数也可以生成散点图矩阵,并有以下可选操作:  
  163. #?1以某个因子为条件绘制散点图矩阵;  
  164. #?2包含线性和平滑拟合曲线;  
  165. #?3在主对角线放置箱线图、密度图或者直方图;  
  166. #?4在各单元格的边界添加轴须图。  
  167. library(car)  
  168. scatterplotMatrix(~mpg+disp+drat+wt,data = mtcars,spread = F,lty.smoooth = 2,  
  169.                   main = "Scatter Polt Matrix via car Package")  
  170. scatterplotMatrix(~mpg+disp+drat+wt|cyl,data = mtcars,spread = F,  
  171.                   diagonal = "histogram",#diagonal设置对角线类型  
  172.                   main = "Scatter Polt Matrix via car Package")  
  173. #gclus包中的cpairs() 函数提供了一个有趣的散点图矩阵变种。  
  174. #它含有可以重排矩阵中变量位置的选项,可以让相关性更高的变量更靠近主对角线。  
  175. #该函数还能对各单元格进行颜色编码来展示变量间的相关性大小  
  176. install.packages("gclus")  
  177. library(gclus)  
  178. mydata <- mtcars[c(1,3,5,6)]  
  179. mydata.corr <- abs(cor(mydata))  
  180. mycolors <- dmat.color(mydata.corr)  
  181. myorder <- order.single(mydata.corr)  
  182. cpairs(mydata,myorder,panel.colors = mycolors,gap = .5,  
  183.        main = "Variables Ordered and Colorsed by Correlation")  
  184. #11.1.2 高密度散点图(热力图)----------  
  185. set.seed(1234)  
  186. n <- 10000  
  187. c1 <- matrix(rnorm(n,0,.5),ncol = 2)  
  188. c2 <- matrix(rnorm(n,3,2),ncol = 2)  
  189. mydata <- rbind(c1,c2)  
  190. mydata <- as.data.frame(mydata)  
  191. names(mydata) <- c("x","y")  
  192. with(mydata,  
  193.      plot(x,y,pch = 19,main = "Scatter Plot with 10,000 Obervations"))  
  194. with(mydata,  
  195.      smoothScatter(x,y,main = "Scatterplot Colored by Smoothed Densities"))  
  196. #hexbin包中的hexbin() 函数将二元变量的封箱放到六边形单元格中(图形比名称更直观)。示例如下  
  197. install.packages("hexbin")  
  198. library(hexbin)  
  199. with(mydata,{  
  200.   bin  <- hexbin(x,y,xbins = 50)  
  201.   plot(bin,main = "Hexagonal Binning with 10,000 Obervations")  
  202. })  
  203. #IDPmisc包中的iplot() 函数也可通过颜色来展示点的密度(在某特定点上数据点的数目)  
  204. install.packages("IDPmisc")  
  205. library(IDPmisc)  
  206. with(mydata,  
  207.      iplot(x,y,main = "Image Scatter Plot with Color Indicating Density"))  
  208. #11.1.3 三维散点图-----  
  209. #使用scatterplot3d包  
  210. install.packages("scatterplot3d")  
  211. library(scatterplot3d)  
  212. attach(mtcars)  
  213. scatterplot3d(wt,disp,mpg,main = "Basic 3D Scatter plot")  
  214. #在3d图中增加z轴线  
  215. scatterplot3d(wt,disp,mpg,pch = 16,highlight.3d = T,type =  "h",  
  216.               main = "Basic 3D Scatter plot")  
  217. #在3d图中增加一个回归面  
  218. s3d <- scatterplot3d(wt,disp,mpg,pch = 16,highlight.3d = T,type =  "h",  
  219.                      main = "Basic 3D Scatter plot")  
  220. fit <- lm(mpg~wt+disp)  
  221. s3d$plane3d(fit)  
  222. #交互式3维散点图  
  223. #使用rgl包,交互性的,可以用鼠标  
  224. install.packages("rgl")  
  225. library(rgl)  
  226. plot3d(wt,disp,mpg,col = "red",size = 5)  
  227. #以下使用Rcmdr包,旋转  
  228. install.packages("Rcmdr")  
  229. library(Rcmdr)  
  230. scatter3d(wt,disp,mpg)  
  231. #11.1.4 气泡图------  
  232. r <- sqrt(disp/pi)  
  233. symbols(mtcars$wt,mtcars$mpg,circles = r,  
  234.         inches = .3,#inches参数控制圆圈基准大小,默认1英寸  
  235.         fg = "white",  
  236.         bg = "lightblue",  
  237.         main = "Bubble Plot with point size proportional to displacement",  
  238.         ylab = "Miles Per Gallon",  
  239.         xlab = "Weight of Car (lbs/1000)")  
  240. text(mtcars$wt,mtcars$mpg,rownames(mtcars),cex = .6)  
  241. detach(mtcars)  
  242.   
  243. #11.2 折线图---------  
  244. oper <- par(no.readonly = T)  
  245. par(mfrow = c(1,2))  
  246. t1 <- subset(Orange,Tree == 1)  
  247. plot(t1$age,t1$circumference,xlab = "Age (days)",  
  248.      ylab = "Circumference (mm)",main = "Orange Tree 1 Growth")  
  249. plot(t1$age,t1$circumference,xlab = "Age (days)",  
  250.      ylab = "Circumference (mm)",main = "Orange Tree 1 Growth",type = "b")  
  251. par(oper)  
  252. #在一幅图中画多个折线图  
  253. Orange$Tree <- as.numeric(Orange$Tree)  
  254. ntrees <- max(Orange$Tree)  
  255. xrange <- range(Orange$age)  
  256. yrange <- range(Orange$circumference)  
  257. plot(xrange,yrange,type = "n",xlab = "Age (days)",ylab = "Circumference (mm)")  
  258. colors <- rainbow(ntrees)  
  259. linetype <- 1:ntrees  
  260. plotchar <- 18:(18+ntrees)  
  261. for (i in 1:ntrees) {  
  262.   tree <- subset(Orange,Tree == i)  
  263.   lines(tree$age,tree$circumference,type = "b",  
  264.         lwd = 2,lty = linetype[i],col = colors[i],pch = plotchar[i])  
  265. }  
  266. title("Tree Growth","example of line polt")  
  267. legend(xrange[1],yrange[2],1:ntrees,cex=.8,col = colors,  
  268.        pch = plotchar,lty = linetype,title = "Tree")  
  269.   
  270. #11.3 相关图(不常用)---------  
  271. #使用到corrgram包  
  272. options(digits = 2)  
  273. install.packages("corrgram")  
  274. library(corrgram)  
  275. corrgram(mtcars,order = T,lower.panel = panel.shade,upper.panel = panel.pie,  
  276.          text.panel = panel.txt,main = "Correlogram of mtcars intercorrelations")  
  277.   
  278. #11.4 马赛克图--------  
  279. ftable(Titanic)  
  280. library(vcd)  
  281. mosaic(Titanic,shade = T,legend = T)  
  282. mosaic(~Class+Sex+Age+Survived,Titanic,shade = T,legend = T)  
  283.   
  284. #16.2 lattic包---------  
  285. library(lattice)  
  286. histogram(~height|voice.part,data = singer,  
  287.           main = "Distribution of Heights by Voice Pitch",  
  288.           xlab = "Height (inches)")  
  289. contourplot(volcano)  
  290. levelplot(volcano)  
  291. cloud(volcano)  
  292. wireframe(volcano)  
  293. bwplot(mtcars$mpg)  
  294. parallelplot(mtcars[1:3])  
  295. stripplot(mtcars$mpg~factor(mtcars$cyl))  
  296. splom(mtcars[c(1,3,4,5)])  
  297. #16.2.1 条件变量---------  
  298. (displacement <- equal.count(mtcars$disp,number = 3,overlap = 0))#overlap设置重叠部分  
  299. xyplot(mtcars$mpg~mtcars$wt|displacement,  
  300.        main = "Miles per Gallon vs. Weight by Engine Displacement",  
  301.        xlab = "Weight",ylab = "Mile per Gallon",  
  302.        layout = c(3,1),aspect = 1.5)  
  303. #16.2.2 面板函数-----------  
  304. mypanel <-function(x,y){  
  305.   panel.xyplot(x,y,pch=19)  
  306.   panel.rug(x,y)  
  307.   panel.grid(h=-1,v=-1)  
  308.   panel.lmline(x,y,col = "red",lwd = 1,lty = 2)  
  309. }  
  310. xyplot(mtcars$mpg~mtcars$wt|displacement,  
  311.        main = "Miles per Gallon vs. Weight by Engine Displacement",  
  312.        scales = list(cex=.8,col = "red"),  
  313.        xlab = "Weight",ylab = "Mile per Gallon",  
  314.        layout = c(3,1),aspect = 1.5,panel = mypanel,index.cond = list(c(2,1,3)))  
  315. #16.2.3 分组变量---------  
  316. mtcars$transmission <- factor(mtcars$am,levels = c(0,1),labels = c("Automatic","Manual"))  
  317. colors <- c("red","blue")  
  318. lines <- c(1,2)  
  319. points <- c(16,17)  
  320. key.trans <- list(title = "Trasmission",space = "bottom",columns = 2,  
  321.                   text = list(levels(mtcars$transmission)),  
  322.                   points = list(pch = points,col = colors),  
  323.                   lines = list(col = colors,lty = lines),  
  324.                   cex.title = 1,cex = .9)  
  325. densityplot(~mpg,data = mtcars,groups = transmission,  
  326.             main = "MPG Distribution by Transmission Type",  
  327.             xlab = "Mile per Gallon",  
  328.             pch = points,lty = lines,col = colors,lwd = 2,jitter = .005,  
  329.             key = key.trans)  
  330. #16.2.5 页面摆放-----------  
  331. graph1 <- histogram(~height|voice.part,data = singer,  
  332.                     main = "Heights of Choral Singers by Voice Part")  
  333. graph2 <- densityplot(~height,data = singer,groups = voice.part,  
  334.                       plot.points = F,auto.key = list(columns = 4))  
  335. plot(graph1,split = c(1,1,1,2))  
  336. plot(graph2,split = c(1,2,1,2),#split 参数说明,c(列位置号码,行位置号码,列数,行数)  
  337.      newpage = F)  
  338. plot(graph1,position = c(0,.3,1,1))  
  339. plot(graph2,position = c(0,0,1,.3),#position = c(xmin, ymin, xmax, ymax)   
  340.      newpage = F)  
  341.   
  342. #16.3 ggplot2包---------  
  343. install.packages("ggplot2")  
  344. library(ggplot2)  
  345. mtcars$cylinder <- as.factor(mtcars$cyl)  
  346. qplot(cylinder,mpg,data = mtcars,geom = c("boxplot","jitter"),fill = cylinder,  
  347.       main = "Box plots with superimposed data points",  
  348.       xlab = "Number of Cylinder",ylab = "Miles per Gallon")  
  349. transmission <- factor(mtcars$am,levels = c(0,1),labels = c("Automatic","Manual"))  
  350. qplot(wt,mpg,data = mtcars,color = transmission,shape = transmission,  
  351.       gemo = c("point","smooth"),  
  352.       method = lm,formula = y~x,  
  353.       xlab = "Weight",ylab = "Miles Per Gallon",  
  354.       main = "Regiession Example")  
  355. qplot(wt,mpg,data = mtcars,facets = transmission~cylinder,size = hp)  
  356. data(singer,package = "lattice")  
  357. qplot(height,data = singer,geom = c("density"),  
  358.       facets = voice.part~.,fill = voice.part)  
  359.   
  360. #16.4 交互式图形-----------  
  361. plot(mtcars$wt,mtcars$mpg)  
  362. identify(mtcars$wt,mtcars$mpg,labels = row.names(mtcars))  
0 0
原创粉丝点击