熊荣川
六盘水师范学院生物信息学实验室
xiongrongchuan@126.com
http://blog.sciencenet.cn/u/Bearjazz
箱体图,或箱形图是科学研究、统计分析中常常用到的统计图形。毫无疑问R语言能绘制各种各样的箱体图。下面是来自R自身帮助包中的实例(http://127.0.0.1:13367/library/graphics/html/boxplot.html)。此处只是将相应的效果图片补充完整,增加参考性和便捷性。部分地方有我们自己的中文注释,但是不值一提。
## boxplot on a formula:
boxplot(count ~ spray, data = InsectSprays, col ="lightgray")
# *add* notches (somewhat funny here):
boxplot(count ~ spray, data = InsectSprays,
notch = TRUE, add = TRUE, col = "blue")
#使用add选项把新的图叠加的上一个图上
#使用notch选项,画出“缺口”如果两个箱形图缺口部分不重叠,说明中值差异显著
boxplot(decrease ~ treatment, data =OrchardSprays,
log = "y", col = "bisque")
#将y值设为log scale
rb <- boxplot(decrease ~ treatment, data= OrchardSprays, col = "bisque")
title("Comparing boxplot()s andnon-robust mean +/- SD")
#使用title函数加标题
#在上图上叠加均值和标准差
mn.t <- tapply(OrchardSprays decrease,OrchardSprays treatment, mean)
sd.t <- tapply(OrchardSprays decrease,OrchardSprays treatment, sd)
xi <- 0.3 + seq(rb$n)
points(xi, mn.t, col = "orange",pch = 18)
arrows(xi, mn.t - sd.t, xi, mn.t + sd.t,
code = 3, col = "pink", angle = 75, length = .1)
#下面演示怎样用表格中的几列数据做箱形图(之前的数据都是在同一列的哦)
## boxplot on a matrix:
mat <- cbind(Uni05 = (1:100)/21, Norm =rnorm(100),
`5T` = rt(100, df = 5), Gam2 = rgamma(100, shape = 2))
boxplot(as.data.frame(mat),
main = "boxplot(as.data.frame(mat), main = ...)")
#旋转、水平作图,箱体图
par(las = 1) # all axis labels horizontal
boxplot(as.data.frame(mat), main ="boxplot(*, horizontal = TRUE)",
horizontal = TRUE)
## Using 'at = ' and adding boxplots --example idea by Roger Bivand :
#使用at选项制定箱体图输出的位置
boxplot(len ~ dose, data = ToothGrowth,
boxwex = 0.25, at = 1:3 - 0.2,
subset = supp == "VC", col = "yellow",
main = "Guinea Pigs' Tooth Growth",
xlab = "Vitamin C dose mg",
ylab = "tooth length",
xlim = c(0.5, 3.5), ylim = c(0, 35), yaxs = "i")
#叠加到上图,at选项使得位置错开
#对部分类别数据作图
boxplot(len ~ dose, data = ToothGrowth, add= TRUE,
boxwex = 0.25, at = 1:3 + 0.2,
subset = supp == "OJ", col = "orange")
legend(2, 9, c("Ascorbic acid","Orange juice"),
fill = c("yellow", "orange"))
#添加图例,
## more examples in help(bxp)
转载自:http://blog.sciencenet.cn/blog-508298-746662.html