楼主: complicated
3358 5

[学习分享] 【版块活动】一月一主题讨论 [推广有奖]

  • 3关注
  • 18粉丝

已卖:10份资源

副教授

65%

还不是VIP/贵宾

-

威望
0
论坛币
6463 个
通用积分
3868.8149
学术水平
88 点
热心指数
86 点
信用等级
58 点
经验
21958 点
帖子
506
精华
0
在线时间
1425 小时
注册时间
2007-6-16
最后登录
2024-4-20

楼主
complicated 在职认证  发表于 2014-6-1 17:11:43 |AI写论文

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币
本月主题:R绘图那些事儿



讨论框架:包括但不限于以下几个方面(欢迎补充)
(1)基于R base相关函数实现常用统计图形的绘制,包括常用图表类型及特有参数,画板布局、坐标轴、辅助图形和注释的应用。力求不借助各种额外包,得到简洁、细致的可视化输出。(2)展现ggplot2/lattice等图形功能的强大之处,或图形功能强大,或代码简洁

参与方法(以跟帖形式):
(1)分享资料
(2)分享使用和学习心得
(3)直接参与讨论(也欢迎提问)

奖励方法
(1)将有价值的回帖设为精彩回复或直接编辑到主题帖中,供坛友学习
(2)只要是具有学习价值或者讨论价值的回帖,基于论坛币的奖励
(3)请不要进行无意义的回帖,诸如顶、学习一下等,表达支持可以通过给回帖评分的形式
(4)对参与活动特别热心且有突出贡献的坛友可推荐为本版热心会员或后备版主

温馨提示
(1)分享资料包括好的书籍、博文以及之前论坛的精彩回帖等,考虑到R的更新速度,请在分享前确认资料的有效性。
(2)鼓励免费分享,不建议收取论坛币,对于好的资料会有丰厚的论坛币补偿。
(3)R毕竟只是一个工具,在分享使用经验欢迎附上使用过程中的背景知识。
(4)建议对于回帖正文,除了部分难以翻译的英文关键词,请不要使用英文。

感谢大家对活动的倡议和努力,欢迎大家提出更多好的意见建议。

二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:版块活动 Lattice ggplot2 gplot 分享资料 主题

密码被盗??

沙发
complicated 在职认证  发表于 2014-6-1 17:21:40
还是我先来一个哈,整理了一个基础绘图的框架,包括单离散变量、单连续变量、多变量、参数设定等内容。
已经发布至https://github.com/dcshallot/visualization, 欢迎参与完善!
完整的代码见下:

  1. # File-Name:       base plot.R           
  2. # Date:            2014-06-01                  
  3. # Author:          Chong Ding (chong.ding83@gmail.com)
  4. # Purpose:         讨论常见图形的命令、参数和效果,尽量用R基础功能实现,效果不输excel
  5. # Data Used:       iris, VADeaths
  6. # Packages Used:   MASS,RColorBrewer
  7. # R 基础绘图 v1.0

  8. ### 离散变量图,一般都用汇总后的数据

  9. ## 条形图

  10. # 频数统计条形图
  11. barplot( table(iris[,5]) )

  12. # 统计汇总条形图
  13. l <- aggregate( Sepal.Length ~ Species, data= iris, mean)
  14. x <- barplot( l[,2] ,  col=terrain.colors(3) , xlim=c(0,5), ylim=c(0,8) ,axe=F, names.arg = l[,1] )
  15. y <- as.matrix( l[,2] )
  16. text( x, y+1, labels=l[,2], col="black" ) #柱顶标注,y +n调节标注高度,横放图则调x+n
  17. legend(legend=l[,1], "right", pch=15, col=terrain.colors(3) )

  18. # 堆砌和分组
  19. l <- table( mtcars$cyl , mtcars$gear);l
  20. barplot( l, beside=T, main = "car tpyes: cyl and gear",
  21.          names.arg=c( "gear=3","gear=4","gear=5"), legend=c("cyl=4", "cly=6", "cyl=8"))
  22. barplot( l, beside=F, main = "car tpyes: cyl and gear",
  23.          names.arg=c( "gear=3","gear=4","gear=5"), legend=c("cyl=4", "cly=6", "cyl=8"))

  24. ##饼图

  25. # Pie Chart with Percentages
  26. slices <- c(10, 12, 4, 16, 8)
  27. lbls <- c("US", "UK", "Australia", "Germany", "France")
  28. pct <- round(slices/sum(slices)*100)
  29. lbls <- paste(lbls, pct) # add percents to labels
  30. lbls <- paste(lbls,"%",sep="") # ad % to labels
  31. pie(slices,labels = lbls, col=rainbow(length(lbls)),
  32.     main="Pie Chart of Countries")

  33. # 3D Exploded Pie Chart
  34. library(plotrix)
  35. slices <- c(10, 12, 4, 16, 8)
  36. lbls <- c("US", "UK", "Australia", "Germany", "France")
  37. pie3D(slices,labels=lbls,explode=0.1,
  38.       main="Pie Chart of Countries ")


  39. ## 点图:适合很多列别的数据

  40. # Dotplot: Grouped Sorted and Colored
  41. # Sort by mpg, group and color by cylinder
  42. x <- mtcars[order(mtcars$mpg),] # sort by mpg
  43. x$cyl <- factor(x$cyl) # it must be a factor
  44. x$color[x$cyl==4] <- "red"
  45. x$color[x$cyl==6] <- "blue"
  46. x$color[x$cyl==8] <- "darkgreen"
  47. dotchart(x$mpg,labels=row.names(x),cex=.7,groups= x$cyl,
  48.          main="Gas Milage for Car Models\ngrouped by cylinder",
  49.          xlab="Miles Per Gallon", gcolor="black", color=x$color)


  50. ### 连续变量图:一般都用原始数据,而非汇总数据做

  51. ## 直方图:连续变量的分布

  52. # 分布函数
  53. h<-hist(x, breaks=10, col="red", xlab="Miles Per Gallon", prob=F ,
  54.         main="Histogram with Normal Curve")
  55. xfit<-seq(min(x),max(x),length=40)
  56. yfit<-dnorm(xfit,mean=mean(x),sd=sd(x)) # 正态分布可以这么画,其他分布参考分布函数
  57. yfit <- yfit*diff(h$mids[1:2])*length(x)
  58. lines(xfit, yfit, col="blue", lwd=2)

  59. # 密度函数
  60. x <- mtcars$mpg
  61. h<-hist(x, breaks=10, col="red", xlab="Miles Per Gallon", prob=T ,
  62.         main="Histogram with Normal Curve")
  63. lines(density(x))

  64. # 离散变量直方图
  65. plot( table(mtcars$carb), type="h" , lwd=5 )
  66. head(iris)


  67. ### 多变量

  68. ## 箱线图:连续变量VS离散变量
  69. boxplot( Petal.Length ~ Species , data = iris , outline = F  ) # 离群值不显示
  70. boxplot( mpg ~ cyl * gear, data = mtcars , varwidth=T ) # 箱体宽度由样本量决定


  71. ## plot族

  72. # 简单漂亮的散点图:两个连续变量之间的关系
  73. plot(cars$dist~cars$speed, # y~x
  74.      main="Relationship between car distance & speed", #Plot Title
  75.      xlab="Speed (miles per hour)", #X axis title
  76.      ylab="Distance travelled (miles)", #Y axis title
  77.      xlim=c(0,30), #Set x axis limits from 0 to 30 ylim=c(0,140), #Set y axis limits from 0 to  30140  xaxs="i", #Set x axis style as internal
  78.      yaxs="i", #Set y axis style as internal  
  79.      col="red", #Set the colour of plotting symbol to red
  80.      pch=19) #Set the plotting symbol to filled dots

  81. # 分类散点图
  82. # 先将鸢尾花的类型转化为整数1 、2 、3,便于使用向量
  83. idx = as.integer(iris[["Species"]])
  84. plot(iris[, 3:4], pch = c(24, 21, 25)[idx], col = c("black","red", "blue")[idx], panel.first = grid())
  85. legend("topleft", legend = levels(iris[["Species"]]), col = c("black", "red", "blue"),
  86.        pch = c(24, 21, 25), bty = "n")

  87. # 散点矩阵图
  88. pairs( ~ Sepal.Length + Sepal.Width + Petal.Length +Petal.Width, data=iris)

  89. # 用散点图表示时间序列数据
  90. data <- VADeaths
  91. plot(data[,1] ,type="b" , lwd =2, xaxt="n" , ylim=c(0, 75) ,
  92.      main ="Death Rates in Virginia (1940)", xlab="age", ylab="Death Rate"  )
  93. axis( 1, at=1:nrow(data) ,labels = row.names(data) )
  94. lines( data[,2], type="b" , lwd =2, col="red" )
  95. lines( data[,3], type="b" , lwd =2, col="orange" )
  96. lines( data[,4], type="b" , lwd =2, col="purple" )
  97. legend( 4,30 , legend=colnames(data) , lty=1, lwd=2, pch=21, bty="n" ,
  98.         col=c("black","red","orange","purple") , cex =0.8, inset=0.01)
  99. grid()

  100. ## matplot 分类散点图,强化类别差异的表现
  101. nam.var <- colnames(iris)[-5]
  102. nam.spec <- as.character(iris[1+50*0:2, "Species"])
  103. iris.S <- array(NA, dim = c(50,4,3),
  104.                 dimnames = list(NULL, nam.var, nam.spec))
  105. for(i in 1:3) iris.S[,,i] <- data.matrix(iris[1:50+50*(i-1), -5])
  106. matplot(iris.S[, "Petal.Length",], iris.S[, "Petal.Width",], pch = "SCV",
  107.         col = rainbow(3, start = 0.8, end = 0.1),
  108.         sub = paste(c("S", "C", "V"), dimnames(iris.S)[[3]],
  109.                     sep = "=", collapse= ",  "),
  110.         main = "Fisher's Iris Data")

  111. ### 复杂图形(复杂一点而已)

  112. ## 对应分析:两个或多个变量之间的对应关系
  113. library(MASS)
  114. cal<-corresp(USPersonalExpenditure,nf=2) ;
  115. biplot(cal,expand=1.5, xlim=c(-0.5 , 0.5), ylim=c(-0.1 , 0.15))
  116. abline(v=0,h=0,lty=3)

  117. ## 系统聚类:样本距离的衡量
  118. dist <-dist(scale(iris[,c(1:4)]))
  119. hc <- hclust(dist, "ward")
  120. plclust(hc,hang=-1 ,  labels=iris[,5]  )
  121. re<-rect.hclust(hc,k=4,border="red")

  122. # 随机点的艺术作品
  123. par(mar = c(0.2, 0.2, 0.2, 0.2), mfrow = c(2, 2))
  124. for (n in c(63, 60, 76, 74)) {
  125.   set.seed(711)
  126.   plot.new()
  127.   size = c(replicate(n, 1/rbeta(2, 1.5, 4)))
  128.   center = t(replicate(n, runif(2)))
  129.   center = center[rep(1:n, each = 2), ]
  130.   color = apply(replicate(2 * n, sample(c(0:9,
  131.                                           LETTERS[1:6]), 8, TRUE)), 2, function(x) sprintf("#%s", paste(x, collapse = "")))
  132.   points(center, cex = size, pch = rep(20:21, n),  col = color)
  133.   box()
  134. }
  135. dev.off()

  136. # 热力图,用于展现相同数值在两个维度上的水平/相关系数
  137. library(RColorBrewer)
  138. data <- VADeaths
  139. pal=brewer.pal(4,"YlOrRd")
  140. breaks<-c(0, 15, 26, 44, 72)
  141. layout(matrix(data=c(1,2),  nrow=1, ncol=2), widths=c(8,1),
  142.        heights=c(1,1))  ## 画一个空白的图形画板,按照参数把图形区域分隔好
  143. ## 看layout的分割可以这样:
  144. ## xx <- layout(matrix(data=c(1,2),  nrow=1, ncol=2), widths=c(8,1), heights=c(1,1)) ; layout.show(xx)
  145. par(mar = c(2,6,4,1 ), oma=c(0.1, 0.1 ,0.1 , 0.1), mex = 1.2 ) #Set margins for the heatmap
  146. image(x=1:nrow(data),
  147.       y=1:ncol(data),
  148.       z=data,axes=FALSE,
  149.       xlab="Month",   ylab="", main="Sales Heat Map" ,
  150.       col=pal[1:(length(breaks)-1)],
  151.       breaks=breaks ) # breaks 颜色块对应的数值(数值分组),要比颜色数量多1个
  152. axis(1, col="white",las=1 , at=1:nrow(data), labels=rownames(data)  )
  153. axis(2, col="white",las=1 , at=1:ncol(data), labels=colnames(data)  )
  154. abline(h=c(1:ncol(data))+0.5, v=c(1:nrow(data))+0.5,  col="white",lwd=2,xpd=FALSE)
  155. # 画标尺
  156. breaks2 <- breaks[-length(breaks)]  # breaks 少一个
  157. par(mar = c(2,1,4,2))
  158. image(x = 1, y= 0:length(breaks2),
  159.       z=t(matrix(breaks2))*1.001,
  160.       col=pal[1:length(breaks)-1],
  161.       axes=FALSE,breaks=breaks,
  162.       xlab="", ylab="",xaxt="n")
  163. axis(4,at=0:(length(breaks2)-1), labels=breaks2, col="white", las=1)
  164. abline(h=c(1:length(breaks2)),col="white",lwd=2, xpd=F )
  165. dev.off()

  166. ### 参数参考

  167. # 玩线条形状
  168. x <- c(1:5); y <- x # create some data
  169. par(pch=22, col="red") # plotting symbol and color
  170. par(mfrow=c(2,4)) # all plots on one page
  171. opts = c("p","l","o","b","c","s","S","h")
  172. for(i in 1:length(opts)){
  173.   heading = paste("type=",opts[i])
  174.   plot(x, y, type="n", main=heading)
  175.   lines(x, y, type=opts[i])
  176. }
  177. dev.off()

  178. # 玩颜色
  179. library( RColorBrewer)
  180. display.brewer.all(n=10, exact.n=FALSE) # 调色板
  181. col= brewer.pal( n  ,"Set1") # 引用颜色

  182. # 玩坐标轴
  183. x <- c(1:10); y <- x; z <- 10/x
  184. # 为一个坐标在右边创建额外页边空间
  185. par(mar=c(5, 4, 4, 8) + 0.1)
  186. # 绘制 x 相对 y
  187. plot(x, y,type="b", pch=21, col="red",
  188.      yaxt="n", lty=3, xlab="", ylab="")
  189. # 添加 x 相对 1/x
  190. lines(x, z, type="b", pch=22, col="blue", lty=2)
  191. # 在左边画一条轴线
  192. axis(2, at=x,labels=x, col.axis="red", las=0)
  193. # 用小字体标记在右边画一条轴线
  194. axis(4, at=z,labels=round(z,digits=2),
  195.      col.axis="blue", las=2, cex.axis=0.7, tck=-.01)
  196. # 为右边轴线添加标题
  197. mtext("y=1/x", side=4, line=3, cex.lab=1,las=2, col="blue")
  198. # 添加主标题,底和左轴标签
  199. title("An Example of Creative Axes", xlab="X values",
  200.       ylab="Y=X")
  201. dev.off()

  202. # 玩辅助线和图例
  203. plot(1:10, type = "n", xlim = c(0, 20), ylim = c(0, 20)) # 不作图,只画出框架,且指定坐标轴范围
  204. lines(1:10, abs(rnorm(10)))  # 10个正态随机数绝对值的波动线
  205. # 不同的直线
  206. abline(a = 0, b = 1, col = "gray")
  207. abline(v = 2, lty = 2)
  208. abline(h = 2, lty = 2)
  209. #添加文本
  210. text(8, 3, "abline(a = 0, b = 1)")
  211. # 添加箭头
  212. arrows(8, 3.5, 6, 5.7, angle = 40)
  213. # 参数用了向量:不同灰度的线段
  214. segments(rep(3, 4), 6:9, rep(5, 4), 6:9, col = gray(seq(0.2, 0.8, length = 4)))
  215. text(4, 9.8, "segments")
  216. dev.off()

  217. ####################################

  218. # 待增补
复制代码

已有 2 人评分经验 论坛币 学术水平 热心指数 信用等级 收起 理由
jmpamao + 60 + 60 + 3 + 3 + 3 精彩帖子
ltx5151 + 60 + 60 精彩帖子

总评分: 经验 + 120  论坛币 + 120  学术水平 + 3  热心指数 + 3  信用等级 + 3   查看全部评分

密码被盗??

藤椅
complicated 在职认证  发表于 2014-6-1 17:31:36
再附上之前总结的R base绘图功能mind map,调整了一下结构,供参考

R base plot.jpg (126.67 KB)

R base plot.jpg

已有 2 人评分经验 学术水平 热心指数 信用等级 收起 理由
ltx5151 + 100 精彩帖子
ywh19860616 + 3 + 3 + 3 精彩帖子

总评分: 经验 + 100  学术水平 + 3  热心指数 + 3  信用等级 + 3   查看全部评分

密码被盗??

板凳
jmpamao 发表于 2014-6-3 17:37:12
有图片 就更好了
:D

报纸
complicated 在职认证  发表于 2014-6-3 18:23:26
jmpamao 发表于 2014-6-3 17:37
有图片 就更好了
:D
图+代码太纠结,等我学会了markdown的
密码被盗??

地板
rene1929 发表于 2017-1-20 16:02:54
学习了

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注cda
拉您进交流群
GMT+8, 2025-12-22 12:21