ggplot2向抖动位置添加偏移量

时间:2016-05-04 11:22:55

标签: r plot ggplot2

我的数据看起来像这样

df = data.frame(x=sample(1:5,100,replace=TRUE),y=rnorm(100),assay=sample(c('a','b'),100,replace=TRUE),project=rep(c('primary','secondary'),50))

并使用此代码生成图表

ggplot(df,aes(project,x)) + geom_violin(aes(fill=assay)) + geom_jitter(aes(shape=assay,colour=y),height=.5) + coord_flip()

给了我这个

violin plot with points

这是成为我想要的方式的90%。但是如果每个点都只绘制在匹配测定类型的小提琴图上,我希望如此。也就是说,点的抖动位置被设置为使得三角形仅在上部蓝绿色小提琴图上以及在每个项目类型的底部红色小提琴图中的圆圈。

任何想法如何做到这一点?

2 个答案:

答案 0 :(得分:5)

为了获得理想的结果,最好使用position_jitterdodge,因为这可以让您最好地控制积分的方式,以及#39;:

ggplot(df, aes(x = project, y = x, fill = assay, shape = assay, color = y)) + 
  geom_violin() + 
  geom_jitter(position = position_jitterdodge(dodge.width = 0.9,
                                              jitter.width = 0.5,
                                              jitter.height = 0.2),
              size = 2) + 
  coord_flip()

给出:

enter image description here

答案 1 :(得分:1)

您可以在分析和分析之间使用interaction项目:

p <- ggplot(df,aes(x = interaction(assay, project), y=x)) + 
     geom_violin(aes(fill=assay)) +  
     geom_jitter(aes(shape=assay, colour=y), height=.5, cex=4) 
p +  coord_flip()

可以通过数字缩放的x轴调整标签:

# cbind the interaction as a numeric
df$group <- as.numeric(interaction(df$assay, df$project))
# plot
p <- ggplot(df,aes(x=group, y=x, group=cut_interval(group, n = 4))) + 
     geom_violin(aes(fill=assay)) +  
     geom_jitter(aes(shape=assay, colour=y), height=.5, cex=4) 
p +  coord_flip() + scale_x_continuous(breaks = c(1.5, 3.5), labels = levels(df$project))

enter image description here

相关问题