有异常值时在 ggplot boxplot 上标记胡须

Label whiskers on ggplot boxplot when there are outliers

我想在 ggplot 的箱线图中标记胡须的末端,而不是最小值和最大值,这在我的数据中通常是离群值。

我试过使用此处找到的代码:annotate boxplot in ggplot2,但正如您从 factor(cyl)=8(蓝色)的输出中看到的那样,绝对最小值和最大值已标记,不是胡须末端的点。

这是输出:

ggplot(mtcars, aes(x=factor(cyl), y=mpg, fill=factor(cyl))) + 
  geom_boxplot(width=0.6) +
  stat_summary(geom="text", fun.y=quantile,
           aes(label=sprintf("%1.1f", ..y..), color=factor(cyl)),
           position=position_nudge(x=0.33), size=3.5) +
theme_bw()

在给出的示例中,我希望标记 factor(cyl) 上的胡须,而不是离群值。

感谢大家提供的帮助。

箱线图使用 boxplots.stats。您可以直接在 stat_summary:

中使用它
ggplot(mtcars, aes(x=factor(cyl), y=mpg, fill=factor(cyl))) + 
  geom_boxplot(width=0.6) +
  stat_summary(
    aes(label=sprintf("%1.1f", ..y..), color=factor(cyl)),
    geom="text", 
    fun.y = function(y) boxplot.stats(y)$stats,
    position=position_nudge(x=0.33), 
    size=3.5) +
  theme_bw()

如果您只需要胡须,只需使用 boxplot.stats(y)$stats[c(1, 5)] 即可。

欢迎

有点像 tm,我不明白为什么 8 个气缸坏了

library(tidyverse)

outlier_range <- function(x) {
  first_quantile  <-  quantile(x,0.25)
  third_quantile <-  quantile(x,0.75)
  iqr <- IQR(x)
  outlier_lower <- max(min(x), first_quantile  - 1.5 * iqr)
  outlier_higher <- min(max(x), third_quantile + 1.5 * iqr) 

  return(c(outlier_lower, outlier_higher))
}


ggplot(mtcars) +
  aes(x=factor(cyl), y=mpg, fill=factor(cyl)) + 
  geom_boxplot(width=0.6) +
  theme_bw() +
  stat_summary(geom="text", fun.y=outlier_range,
               aes(label=sprintf("%1.1f", ..y..), color=factor(cyl)),
               position=position_nudge(x=0.33), size=3.5)

背着@Axeman:

ggplot(mtcars, aes(x=factor(cyl), y=mpg, fill=factor(cyl))) + 
  geom_boxplot(width=0.6) +
  stat_summary(
    aes(label=sprintf("%1.1f", ..y..), color=factor(cyl)),
    geom="text", 
    fun.y = function(y) boxplot.stats(y)$stats[c(1,5)],
    position=position_nudge(x=0.33), 
    size=3.5) +
  theme_bw()