在R中使用geom_boxplot()+ geom_jitter()时如何排除离群值

时间:2020-04-21 04:06:43

标签: r data-visualization

我有一个名为mpg的数据集。我有兴趣绘制箱形图(上面带有点),以查看变量drv(动力传动系统的类型)和cty(每加仑城市英里数)之间的关系。 下面是我的代码: ggplot(data=mpg,mapping=aes(x=drv,y=cty))+geom_boxplot(outlier.shape = NA)+geom_jitter()

是否可以从geom_jitter()中排除异常值?

Plot

2 个答案:

答案 0 :(得分:2)

您可以使用outlier.shape=NA隐藏geom_boxplot的离群值。对于geom_jitter,您可以使用透明度来隐藏离群值,但是必须首先定义这些离群值。

mpg %>%
  group_by(drv) %>%
  mutate(cty.show = as.numeric(  # so ggplot doesn't complain about alpha being discrete
    between(cty, 
            quantile(cty)[2] - 1.5*IQR(cty),
            quantile(cty)[4] + 1.5*IQR(cty)))) %>% 
  ggplot(aes(drv, cty)) + 
  geom_boxplot(outlier.shape = NA) + 
  geom_jitter(aes(alpha=cty.show), show.legend=FALSE) +
  scale_alpha_continuous(range = c(0, 1)) # otherwise outliers only partially transparent.

enter image description here

对于第二个图,可以根据需要调整y极限。

答案 1 :(得分:1)

geom_jitter()没有论据自行丢弃异常值的理由。您需要通过定义哪些点是异常值来手动过滤要绘制的数据点。

library(dplyr)
library(ggplot2)

mpg %>%
  group_by(drv) %>%
  mutate(cty_filtered = case_when(cty - quantile(cty)[4] > 1.5*IQR(cty) ~ NA_real_,
                                  quantile(cty)[2] - cty > 1.5*IQR(cty) ~ NA_real_,
                                  TRUE ~ cty)) %>%
  ggplot() + geom_boxplot(aes(drv, cty)) + geom_jitter(aes(drv, cty_filtered))