从ggplot2中的stat_summary中删除异常值

问题描述 投票:0回答:1

我有这部分代码可以用我的数据生成箱线图:

p <- ggplot(meltData, aes(x=variable, y=value)) + 
  geom_boxplot()+  geom_boxplot(outlier.colour="red", outlier.shape=1,outlier.size=2)+
stat_summary(geom="text", fun=quantile,
             aes(label=sprintf("%1.1f", ..y..), color=factor(variable)),
             position=position_nudge(x=0.0), size=3.5,show_guide = FALSE)+
  ggtitle("Species measurements")+
  ggeasy::easy_center_title()
p

我有这个输出: enter image description here

我希望能够在箱线图上看到上部和下部晶须数字作为最大值和最小值(而不是异常值数字)。例如,在第 5 个箱线图上,我们可以看到最大数量为 72,但这是一个异常值,最大值应约为 56。

r ggplot2 boxplot outliers
1个回答
1
投票

如果我正确理解您的目的,您想要创建箱线图以及显示上下晶须数字的文本,并且图中不应显示异常值。如果这是真的,那么我同意@Death Metal 的观点,即您可能想要过滤每个类别的异常值。

但是,由于您没有提供可重现的数据,因此这里有一个与您的数据类似的虚拟数据。

dat <- data.frame(var.A = c(iris$Sepal.Length, c(20,21,22)), 
                  var.B = c(iris$Petal.Length, c(20,21,22)))
meltData <- dat %>% pivot_longer(cols = c(var.A, var.B), 
                                 values_to = "value", 
                                 names_to = "variable")

ggplot(meltData, aes(x=variable, y=value)) + geom_boxplot()

清楚地显示异常值

enter image description here

以下是在应用箱线图之前过滤异常值的方法:

meltData %>% group_by(variable) %>%
     filter(value != (boxplot(value))$out) %>% 
     ggplot(aes(x = variable, y = value)) + 
     geom_boxplot() + stat_summary(geom="text", 
                                   fun=quantile,aes(label=sprintf("%1.1f", ..y..), 
                                                    color=factor(variable)),
                                   position=position_nudge(x=0.0), 
                                   size=3.5,show_guide = FALSE)+
     ggtitle("Species measurements")+
     ggeasy::easy_center_title()
#Warning message:
#`show_guide` has been deprecated. Please use `show.legend` instead. 

结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.