简体   繁体   English

在 ggplot 中包含极端异常值的指示

[英]Include indication of extreme outliers in ggplot

I have some very, very few outliers in my dataset making the boxplots difficult to read:我的数据集中有一些非常非常少的异常值,使得箱线图难以阅读:

library(ggplot2)
mtcars$mpg[1] <- 60
p <- ggplot(mtcars, aes(factor(cyl), mpg))
p + geom_boxplot()

在此处输入图片说明

Hence, I would like to indicate the extreme outliers like this:因此,我想指出这样的极端异常值:

在此处输入图片说明

Any ideas how to do this in ggplot2 ?任何想法如何在ggplot2做到这ggplot2 Transforming the axis is not an option for me...变换轴对我来说不是一个选择......

This is a start:这是一个开始:

library("ggplot2")
mtcars$mpg[1:2] <- c(50,60)
p <- ggplot(mtcars, aes(factor(cyl), mpg))
p + geom_boxplot()

Define max value:定义最大值:

maxval <- 40

Use dplyr (could also be done in base R or plyr ) to extract outliers and put together the text string:使用dplyr (也可以在 base R 或plyr )提取异常值并将文本字符串放在一起:

library("dplyr")
dd <- mtcars %>% filter(mpg>maxval) %>%
    group_by(cyl) %>%
        summarise(outlier_txt=paste(mpg,collapse=","))

Set max y value and add an arrow plus label:设置最大 y 值并添加箭头加标签:

library("grid") # needed for arrow() function
p2 <- p + geom_boxplot() +
    scale_y_continuous(limits=c(min(mtcars$mpg),maxval))+
       geom_text(data=dd,aes(y=maxval,label=outlier_txt),
                 size=3,vjust=1.5,hjust=-0.5)+
          geom_segment(data=dd,aes(y=maxval*0.95,yend=maxval,
                       xend=factor(cyl)),
                 arrow = arrow(length = unit(0.1,"cm")))
p2

在此处输入图片说明

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

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