簡體   English   中英

Romove異常值來自ggplot2中的stat_summary

[英]Romove outliers from stat_summary in ggplot2

我有這部分代碼可以用我的數據生成箱線圖:

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

我有這個輸出: 在此處輸入圖像描述

我希望能夠在我的箱線圖上看到上下須數作為最大值和最小值(而不是異常值)。 例如,在第 5 個箱線圖中,我們可以看到最大數字為 72,但這是一個異常值,最大值應約為 56。

如果我正確理解您的目的,您希望創建箱線圖以及顯示上下胡須編號的文本,並且圖中不應顯示異常值。 如果這是真的,那么我同意@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()

這清楚地顯示了異常值

在此處輸入圖像描述

以下是在應用箱線圖之前過濾異常值的方法:

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. 

結果:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM