在 R 中,如何使抖动 (geom_jitter()) 保持在相应的箱线图内而不延伸到相邻的箱线图?

In R, how to make the jitter (geom_jitter()) stay inside its correspondant boxplot without extending over the neighboring boxplots?

我想找到一种方法让抖动保持在它自己的箱线图中,而不延伸到相邻的箱线图。

到目前为止,我看了这个答案:

但其中 none 确实解决了我的问题;主要区别在于我在 X 轴上的时间轴上有 3 个组 运行。

我目前的代码:

ggplot(longitudinal, mapping= aes(x = Time, y = Values), shape= Diagnose)+
geom_boxplot(aes(color = Diagnose), outlier.shape = NA ) +
geom_jitter(aes(color= Diagnose, shape=Diagnose)  ,alpha = 0.5)

图像输出:

如你所见,抖动服从时间点分布(T0,T1,T2,T3),但是当涉及到诊断(Diagnose)时,它与其他框重叠。

这是我的数据的示例:

structure(list(Time = c("T0", "T0", "T0", "T0", "T0", "T0", "T0", 
"T0", "T0", "T1", "T1", "T1", "T1", "T1", "T1", "T1", "T1", "T2", 
"T2", "T2", "T2", "T2", "T2", "T2", "T2", "T2", "T3", "T3", "T3", 
"T3", "T3", "T3", "T3", "T3", "T3"), Diagnose = c("PDD", "PDD", 
"PDD", "PD-MCI", "PD-MCI", "PD-MCI", "PD", "PD", "PD", "PD", 
"PD", "PD-MCI", "PD-MCI", "PD-MCI", "PDD", "PDD", "PDD", "PD", 
"PD", "PD", "PD-MCI", "PD-MCI", "PD-MCI", "PDD", "PDD", "PDD", 
"PD", "PD", "PD", "PD-MCI", "PD-MCI", "PD-MCI", "PDD", "PDD", 
"PDD"), Values = c(13.47, 14.25, 15, 20, 19.57, 15, 15, 17.54, 
18, 16.93, 11.42, 18, 15, 19.48, 15, 11, 15, 18.03, 11, 15, 17.85, 
19, 15, 15, 17.85, 20, 15, 19, 14.11, 12, 18.31, 16, 17.36, 20, 
12)), row.names = c(NA, -35L), class = c("tbl_df", "tbl", "data.frame"
))

这是使用 position = position_jitter() , position=position_jitterdodge(), position_dodge, position_jitterdodge( dodge.width= ) 等... 如您所见,这包含了中央箱线图中的所有抖动。

谢谢!

指定闪避宽度

+ geom_jitter(width = 0.05)

geom_point(position = position_jitter(width = 0.05))

差不多!您正在寻找的是 geom_point(position = position_jitterdodge())。您还可以使用 jitter.width

调整宽度
 ggplot(df, mapping= aes(x = Time, y = Values))+
  geom_boxplot(aes(color = Diagnose), outlier.shape = NA ) +
  geom_point(aes(color= Diagnose, shape=Diagnose), alpha = 0.5, 
                 position = position_jitterdodge(jitter.width = 0.1))