通过 ggplot2 抑制小提琴图中分散的抖动点

Restrain scattered jitter points within a violin plot by ggplot2

以下是在ggplot2中生成小提琴图的方法:

ggplot(violin,aes(x=variable,y=log(value+0.5),color=Group)) + 
  geom_violin(scale="width") + 
  geom_jitter(aes(group=Group), position=position_jitterdodge()) + 
  stat_summary(fun.y="mean",geom="crossbar", mapping=aes(ymin=..y.., ymax=..y..), 
     width=1, position=position_dodge(),show.legend = FALSE) + 
  theme(axis.text.x = element_text(angle = 45, margin=margin(0.5, unit="cm")))

结果图如下所示;

如你所见,一些点在小提琴形状的边界之外抖动,我需要这些点在小提琴的内部。我玩过不同程度的抖动,但都取得了成功。我将不胜感激任何实现这一目标的指示。

ggbeeswarm 具有 geoms quasirandom 和 beeswarm,它们正是您要搜索的内容:https://github.com/eclarke/ggbeeswarm

选项 1

使用包 geom_beeswarm 中的函数 geom_quasirandom:

The quasirandom geom is a convenient means to offset points within categories to reduce overplotting. Uses the vipor package.

library(ggbeeswarm)
p <- ggplot(mpg, aes(class, hwy))
p + geom_violin(width = 1.3) + geom_quasirandom(alpha = 0.2, width = 0.2)

选项 2

不是一个令人满意的答案,因为通过限制水平抖动我们破坏了处理重叠的目的。但是您可以扩大小提琴图的宽度 (width = 1.3),并使用 alpha 来提高透明度并限制水平抖动 (width = .02)。

p <- ggplot(mpg, aes(class, hwy))
p + geom_violin(width = 1.3) + geom_jitter(alpha = 0.2, width = .02)

这是一个有点老的问题,但我认为有更好的解决方案。

正如@Richard Telford 在评论中指出的那样,geom_sina 是 IMO 的最佳解决方案。

模拟数据

df <- data.frame(data=rnorm(1200), 
                 group=rep(c("A","A","A", "B","B","C"),
                           200)
                 )

制作情节

ggplot(df, aes(y=data,x=group,color=group)) +
  geom_violin()+
  geom_sina()

结果

希望这对您有所帮助。