箱线图
2020-05-28 本文已影响0人
BeeBee生信
箱线图适合直观展示数据的分布。下图显示箱线图的构成,实际作图也可以根据自己需要进行一定调整/取舍。

其中 m 是中位值,在箱线图里是箱子里面的横线。IQR(Interquartile Range)是上下四分位的间距,上下四分位值是箱线图里箱子上下边。须线是在距离箱子边界1.5 IQR 内最大/最小离群值/异常值(Outlier),超过这个范围的离群值用点表示。箱子宽度可以用于表示样本数量,大约是 宽度。可以用缺口表示中位数的95% CI(Confidence Interval), 范围大约是
, 不过要数据符合正态分布或者样本量比较大才好。下面的图展示如果样本量太小时,强行加入95% CI 缺口甚至超过箱子的范围。

用 ggplot2
做箱线图时默认不展示样本量和95% CI, 如下。
library(tidyverse, quietly = TRUE)
p <- ggplot2::ggplot(diamonds, aes(cut, carat))
p + geom_boxplot(aes(fill=cut)) + theme_classic()

参数调一下可以显示。
p + geom_boxplot(aes(fill=cut), notch = TRUE, varwidth = TRUE) + theme_classic()

很多箱线图喜欢加 P 值,可以自己做统计检验然后用 geom_text
添加到图上。假设做 Kruskal–Wallis test
> kruskal.test(diamonds$carat, diamonds$cut)
Kruskal-Wallis rank sum test
data: diamonds$carat and diamonds$cut
Kruskal-Wallis chi-squared = 1785.5, df = 4, p-value < 2.2e-16
P 值是非常显著的,把他标图上去。
> p + geom_boxplot(aes(fill=cut), notch = TRUE, varwidth = TRUE) +
+ geom_segment(x=1, y=5.2, xend=5, yend=5.2) +
+ geom_text(x = 3, y = 5.3, label = "***") +
+ geom_text(x = 2, y = 5.7, label = "Kruskal–Wallis test") +
+ scale_y_continuous(limits = c(0, 6)) + theme_classic()

[参考]
Krzywinski, Martin, and Naomi Altman. "Visualizing samples with box plots: use box plots to illustrate the spread and differences of samples." Nature Methods 11.2 (2014): 119-121.