带有抖动点的箱线图的额外点(ggplot2)

extra point at boxplot with with jittered points (ggplot2)

我使用下面的代码来探索 ggplot2 的箱线图。

MyData<-data.frame(CASES=c(rep("Good",10),rep("NotGood",10)), NUMBERS=c(2,3,1,5,6,3,2,6,8,3,1,3,6,8,17,3,2,5,7,20))

library(ggplot2)
MyBoxplot <- ggplot(MyData, aes(x=CASES, y=NUMBERS)) + 
  geom_boxplot()
MyBoxplot+ geom_jitter(shape=16, position=position_jitter(0.2))

我注意到,如果我的数据没有任何异常值 (Good),那么箱线图应该有 10 个点。但是如果有一些离群值(NotGood),那么离群值会加倍。

有什么问题?

正如@stefan 所说,geom_boxplot() 会自动将离群值绘制为与您的 x 值对齐的点,因此离群点会出现两次。没有function/argument从geom_boxplot()中“移除”离群点;但是,您可以通过 outlier.color=.

使箱线图中的离群点透明来获得相同的效果

例如,以下面的数据集为例,它有一些离群值。我调整了 geom_jitter() 中的形状,以便更容易看出哪些点来自异常值(而不是 geom_jitter)。

library(ggplot2)

set.seed(1234)
df <- data.frame(x=rep(c('A','B'), each=100), y=c(rnorm(100, 10, 20), rnorm(100, 30, 50)))

ggplot(df, aes(x, y)) +
  geom_boxplot() +
  geom_jitter(position=position_jitter(0.2), shape=3)

如果我们设置 outlier.color=NA,这会使箱线图中的异常值变得“透明”,因此在图中不再观察到它们:

ggplot(df, aes(x, y)) +
  geom_boxplot(outlier.color=NA) +
  geom_jitter(position=position_jitter(0.2), shape=3)