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

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

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

是否有办法从geom_jitter()中排除异常值?

Plot

r data-visualization
2个回答
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))

0
投票

您可以使用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)

enter image description here


当然,您始终可以通过先过滤掉异常值来完全忽略它们。

mpg %>%
  group_by(drv) %>%
  filter(between(cty, 
            quantile(cty)[2] - 1.5*IQR(cty),
            quantile(cty)[4] + 1.5*IQR(cty))) %>% 
ggplot(aes(drv, cty)) + 
  geom_boxplot() + geom_jitter()
© www.soinside.com 2019 - 2024. All rights reserved.