简体   繁体   English

ggplot boxplot 但框扩展到第 5 个和第 95 个百分位数

[英]ggplot boxplot but with boxes extending to 5th and 95th percentiles

I would like to have a boxplot summarize the distribution of some underlying data, but in place of the whiskers extending to the 5th and 95th, I would like the boxes to extend to the 5th and 95th.我想要一个箱线图来总结一些基础数据的分布,但代替延伸到第 5 和第 95 次的胡须,我希望将这些方框延伸到第 5 次和第 95 次。

Standard boxplot with outliers and whiskers removed:去除异常值和须线的标准箱线图:

library("ggplot2")
p <- ggplot(mtcars, aes(factor(cyl), mpg))
p + geom_boxplot(outlier.shape = NA, coef = 0)

在此处输入图片说明 Boxplot with whiskers at 5th and 95th:在第 5 和第 95 处带有胡须的箱线图:

p + stat_summary(geom = "boxplot", 
                 fun.data = function(x) setNames(quantile(x, c(0.05, 0.25, 0.5, 0.75, 0.95)), 
                                                 c("ymin", "lower", "middle", "upper", "ymax")))

在此处输入图片说明

But what I really want is the boxes (no whiskers) to extend to the 5th and 95th, so a combination of both of these modifications.但我真正想要的是将盒子(没有胡须)扩展到第 5 个和第 95 个,因此将这两种修改结合起来。 Is there a way to specify the box-generating function in stat_summary() ?有没有办法在stat_summary()指定框生成函数?

This might be a slightly "hacky" method of doing it, but the easiest way might be to just use geom_segment for each cylinder class.这可能是一种稍微“hacky”的方法,但最简单的方法可能是对每个圆柱类使用geom_segment This will allow you to specify the width of the boxplot and the values that you want the boxplot to reach.这将允许您指定箱线图的宽度以及您希望箱线图达到的值。 But you could then play around with aes() and also add in a median line using stat_summary() if desired.但是,您可以使用aes()并根据需要使用stat_summary()添加中线。

library(ggplot2)
p <- ggplot(mtcars, aes(factor(cyl), mpg))
p + geom_segment(aes(x = 4, xend = 4, y = quantile(subset(mtcars, mtcars$cyl==4)$mpg,0.95), yend = quantile(subset(mtcars, mtcars$cyl==4)$mpg, 0.05)), color = 'firebrick1', lwd = 28)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM