箱线图内限和外限

简介

关于箱线图横线的问题,参考维基百科MBA智库百科我们大约知道了它一般应该代表Q1-1.5IQR和Q3+1.5IQR的内限。

ggplot2可视化

下面箱线图的横线,我认为可以称为类似柱状图的误差线。

  1. 一类分组
ggplot(data = ToothGrowth) + 
  geom_boxplot(aes(x = supp, y = len)) +
  stat_boxplot(aes(x = supp, y = len),
               geom ='errorbar', width = 0.3)
  1. 二类分组

当分组内存在下级分组时,和前面提到的一样ggplot2 函数会分组混乱,出现横线错位的情况。

  1. 解决办法
    我们可以 产生一个新的分组变量,使其同时包含两个分组信息。
ggplot(data = ToothGrowth) + 
  geom_boxplot(aes(x = supp_dose , y = len, color = factor(dose))) +
  stat_boxplot(aes(x = supp_dose , y = len, color = factor(dose)),
               geom ='errorbar', width = 0.3)

重点

geom_boxplot {ggplot2}的函数说明:
The upper whisker extends from the hinge to the largest value no further than 1.5 * IQR from the hinge (where IQR is the inter-quartile range, or distance between the first and third quartiles). The lower whisker extends from the hinge to the smallest value at most 1.5 * IQR of the hinge.

由此可见,ggplot2的boxplot是通过伸出直线的方式指出了内限范围内的最大值和最小值,而不是指出内限区域;由此,我认为box_plot函数默认不加横线是因为上述的横线存在一定误导情况,可能需要特别注明。

计算内限

如果我们想要用ggplot2画标准的横线(内限),需要自己计算出相应内限进行添加。

range_calculater <- function(x) {
  qs <- c(0, 0.25, 0.5, 0.75, 1)
  qnt <-  as.numeric(stats::quantile(x, 
                                     probs = qs, 
                                     na.rm = TRUE))
  iqr <- diff(qnt[c(2, 4)])
  lower <- qnt[2] - 1.5 * iqr
  higher <- qnt[4] + 1.5 * iqr
  df <- rbind(lower, higher)
  return(df)
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容