原贴:ggplot2中如何去除boxplot中的outlier?_ccpacer_新浪博客
http://blog.sina.com.cn/s/blog_4a0824490102wejs.html
-------------------------------------------------------------------------------------------------------------------
问题描述:在处理数据时有时发现由于部分特别离散的孤点导致boxplot自身被压缩的很扁,但是往往我们只想看boxplot本身还不是外面那些孤点,因此如何去除这些孤点,并且不影响boxplot自身的分布呢?(仅把boxplot自身放大)
参考帖子:
(1)http://stackoverflow.com/questions/5677885/ignore-outliers-in-ggplot2-boxplot
总结:
(1)不显示outlier方法1:geom_boxplot(outlier.shape = NA)
(2)不显示outlier方法2:geom_boxplot(outlier.colour = NA)
但是上述两种方法仅仅是不显示孤点,并没有放大boxplot。要放大boxplot不能简单的使用scale_y_continuous或者scale_x_continuous,这会引起ggplot在新设置的范围内重新计算绘图,可能会改变图。比如有一些图输出confidence interval或者smooth line时。具体参考:http://docs.ggplot2.org/current/coord_cartesian.html
这时需要用笛卡尔坐标对图进行单纯的放大:
ylim1<-boxplot.stats(dat$value)$stats[c(1, 5)] #统计boxplot的the extreme of the lower whisker and the extreme of the upper whisker.
p + coord_cartesian(ylim = ylim1*4) #放大boxplot
备注(1):boxplot.stats的用法介绍:
https://stat.ethz.ch/R-manual/R-devel/library/grDevices/html/boxplot.stats.html
stats:一个长度为5的向量,包含下lower whisker, Q1, median, Q3, upper whisker.
a vector of length 5, containing the extreme of the lower whisker, the lower ‘hinge’(Q1), the median, the upper ‘hinge’(Q3) and the extreme of the upper whisker.
备注(2):whisker是boxplot的上下须,一般是IQR的1.5倍,不过在boxplot.stats中可以通过coef来定义。
参考wiki: https://en.wikipedia.org/wiki/Box_plot