沿x轴按组拆分geom_point点

时间:2017-10-27 19:27:54

标签: r ggplot2

这让我感到困惑,我确信我错过了一些简单的事情。任何帮助,将不胜感激。

我希望红色和蓝色点分开,每个设置在第二个图像中的相应箱图上,但是在第一个图像中使用数字x轴。

df <- data.frame(x = rep(c(1, 2, 10), each = 20), 
               g = rep(c("A", "B"), times = 30), 
               y = c(rnorm(60, 0, 1)))

# OK - boxplot by x and g
  ggplot(df, aes(y = y, x = x, fill = g, color = g, group = interaction(x, g))) +
    geom_boxplot() 

# Not OK. The dots are only grouped by x, not g  
  ggplot(df, aes(y = y, x = x, fill = g, color = g, group = interaction(x, g))) +
    geom_point() 

# I want the points to correctly overlay the boxplots
  ggplot(df, aes(y = y, x = x, fill = g, color = g, group = interaction(x, g))) +
    geom_boxplot(alpha = 0.1) +
    geom_point()

enter image description here

(我已经通过x上的刻面修复了它,但我希望将轴作为数字来反映正确的缩放比例)

   ggplot(df, aes(y = y, x = g, fill = g, color = g, group = interaction(x, g))) +
     geom_boxplot(alpha = 0.1) +
     geom_point() +
     facet_wrap(~x)

enter image description here

3 个答案:

答案 0 :(得分:4)

您可以在position=position_dodge(...)中使用geom_point

ggplot(df, aes(y = y, x = x, fill = g, color = g, group = interaction(x, g))) +
  geom_boxplot(alpha = 0.1, width=0.75) +
  geom_point(position = position_dodge(width=0.75))

我还为geom_boxplot定义了一个宽度,以匹配position_dodge中的geom_point宽度。 enter image description here

答案 1 :(得分:3)

如果您还想要抖动,可以使用position_jitterdodge

 ggplot(df, aes(y = y, x = x, fill = g, color = g, group = interaction(x, g))) +
       geom_boxplot(alpha = 0.1, width=0.75) +
       geom_point(position = position_jitterdodge(jitter.width=0.85))

答案 2 :(得分:0)

如果使用geom_beeswarm,您可以使用dodge.width选项

 library(ggbeeswarm)

 ggplot(df, aes(y = y, x = x, fill = g, color = g, group = interaction(x, g))) +
    geom_boxplot(alpha = 0.1, width = 0.75) +
    geom_beeswarm(dodge.width = 0.75)

enter image description here