存在异常值时,在ggplot箱图上标记晶须

时间:2019-06-03 20:32:38

标签: r ggplot2 boxplot outliers quantile

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

我尝试使用下面的代码:annotate boxplot in ggplot2,但是从factor(cyl)= 8(蓝色)的输出中可以看到,绝对最小值和最大值被标记了,而不是晶须的终点。

这是输出:enter image description here

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()

在给定的示例中,我要标记因子(cyl)上的晶须,而不是离群值。

感谢大家提供的任何帮助。

2 个答案:

答案 0 :(得分:2)

箱线图使用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()

enter image description here

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

答案 1 :(得分:0)

欢迎

这类作品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()
相关问题