ggplot:geom_boxplot和geom_jitter

时间:2014-02-21 21:05:41

标签: r ggplot2

将数据点与方框图对齐。

DATA:

data<-structure(list(score = c(0.058, 0.21, -0.111, -0.103, 0.051, 
0.624, -0.023, 0.01, 0.033, -0.815, -0.505, -0.863, -0.736, -0.971, 
-0.137, -0.654, -0.689, -0.126), clin = structure(c(1L, 1L, 1L, 
1L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 1L), .Label = 
c("Non-Sensitive", 
"Sensitive "), class = "factor"), culture = structure(c(1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L
), .Label = c("Co-culture", "Mono-culture"), class = "factor"), 
    status = structure(c(2L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 
    2L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L), .Label = c("new", "old"
    ), class = "factor")), .Names = c("score", "clin", "culture", 
"status"), class = "data.frame", row.names = c(NA, -18L))

CODES:

p<-ggplot(data, aes(culture, as.numeric(score),fill=status))

p+geom_boxplot(outlier.shape = NA)+
   theme_bw()+scale_fill_grey(start = 0.8, end = 1)+
   labs(title="title", x="", y="score",fill="", colour="")+
   geom_jitter(aes(colour = clin), alpha=0.9, 
   position=position_jitter(w=0.1,h=0.1))

RESULT

如您所见,使用geom_jitter绘制的数据点与boxplot不对齐。我知道我需要为geom_jitter提供aes元素 - 但我不知道如何正确地执行它。

1 个答案:

答案 0 :(得分:1)

我不认为你能做到这一点,因为箱形图的位置是由道奇算法驱动的,而不是明确的美学,尽管如果其他人想出办法,我会很好奇。这是一个解决方法:

p<-ggplot(data, aes(status, as.numeric(score),fill=status))
p+geom_boxplot(outlier.shape = NA)+
  theme_bw()+scale_fill_grey(start = 0.8, end = 1)+
  labs(title="title", x="", y="score",fill="", colour="")+
  geom_jitter(aes(colour = clin), alpha=0.9, 
              position=position_jitter(w=0.1,h=0.1)) +
  facet_wrap(~ culture)

enter image description here

通过使用culture的构面,我们可以为status指定明确的审美,然后允许geom_jittergeom_boxplot对齐。希望这足够接近你的目的。