继续“一图胜千言”系列,箱线图通过绘制观测数据的五数总括,即最小值、下四分位数、中位数、上四分位数以及最大值,描述了变量值的分布情况。箱线图能够显示出离群点(outlier),通过箱线图能够很容易识别出数据中的异常值。
本文利用R语言的ggplot2包,从头带您绘制各式各样的箱线图。
一 绘制基本的箱线图
载入数据及函数包library(ggplot2)library(RColorBrewer)
dose数值 变成因子变量ToothGrowth$dose
1)geom_boxplot绘制基本的箱线图
使用ToothGrowth数据集,dose变量为分类横坐标,对len变量做箱线图ggplot(ToothGrowth, aes(x=dose, y=len)) + geom_boxplot()
旋转箱线图方向并设置notchggplot(ToothGrowth, aes(x=dose, y=len)) + geom_boxplot(notch=TRUE) + coord_flip()
2)修改异常点的属性
设置outlier的 color, shape and sizeggplot(ToothGrowth, aes(x=dose, y=len)) + geom_boxplot(outlier.colour="red", outlier.shape=18,outlier.size=4)