【问题标题】:How to exclude outliers when using geom_boxplot() + geom_jitter() in R在 R 中使用 geom_boxplot() + geom_jitter() 时如何排除异常值
【发布时间】:2020-04-21 04:06:43
【问题描述】:

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

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

【问题讨论】:

  • geom_jitter() 没有理由自行丢弃异常值。您必须手动过滤要绘制的数据点或手动定义哪些点是异常值,然后再将其输入geom_jitter()

标签: r data-visualization


【解决方案1】:

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

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

【讨论】:

  • 我认为透明度选项很好 - 我不喜欢用看起来像单个点的情节,但它们已被完全审查。
【解决方案2】:

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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-16
    • 1970-01-01
    • 2021-08-31
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    相关资源
    最近更新 更多