避免在 ggplot2 中使用 geom_point 进行绘图叠加

Ker*_*Ber 3 r data-visualization ggplot2

在 ggplot2 中, geom_point 默认在当前绘图上绘图。例如,在调用 geom_boxplot 后调用 geom_point 会导致绘制在箱线图上的点:

ggplot(iris, aes(x = "All", y = Sepal.Length)) +
  geom_boxplot() +
  geom_point(aes(color=Species), position = "jitter") 
Run Code Online (Sandbox Code Playgroud)

带有重叠点的箱线图

有没有办法将点分别绘制到侧面,而不是在箱线图上?

在我的特殊情况下,我想这样做是因为点模糊了绘图(即使是透明的等),这里的示例数据集不是问题。

eip*_*i10 5

您可以通过为箱线图和点提供单独的 x 值来分别绘制它们:

ggplot(iris, aes(y = Sepal.Length)) +
  geom_boxplot(aes(x="Boxplot")) +
  geom_point(aes(x="Points", color=Species), 
             position = position_jitter(width=0.15, height=0)) 
Run Code Online (Sandbox Code Playgroud)

另一种选择是按物种使用箱线图:

ggplot(iris, aes(y = Sepal.Length)) +
  geom_boxplot(aes(x="All Data"), width=0.5) +
  geom_boxplot(aes(x="By Species", colour=Species), width=0.5,
               position=position_dodge(width=0.6)) 
Run Code Online (Sandbox Code Playgroud)

下面是两个图的样子:

在此处输入图片说明