将小提琴图与躲避箱线图对齐 [英] Align violin plots with dodged box plots

查看:30
本文介绍了将小提琴图与躲避箱线图对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个数据框

set.seed(1234)
x <- rnorm(80, 5, 1)
df <- data.frame(groups = c(rep("group1",20),
                           rep("group2",20),
                           rep("group3",20),
                           rep("group4",20)),
                    value = x,
                    type = c(rep("A", 10),
                           rep("B", 10),
                           rep("A", 10),
                           rep("B", 10),
                           rep("A", 10),
                           rep("B", 10),
                           rep("A", 10),
                           rep("B", 10)))

我想将其绘制为小提琴图,与窄箱线图对齐并按类型"分组:

And I would like to plot it as violin plot, aligned with a narrow box plot and grouped by 'type':

ggplot(data = df, aes(x = groups, y = value, fill = type)) +
  geom_violin()+
  geom_boxplot(width = 0.1, outlier.colour = NA)

然而,箱线图与小提琴图不一致.告诉 ggplot 进行这种叠加的缺失参数是什么?

However, the box plots does not align to the violin plots. What is the missing argument to tell ggplot to do such overlying?

谢谢!

推荐答案

您需要为两个 geom 显式设置躲避的width:

You need to set the width of the dodging explicitly for both geoms:

dodge <- position_dodge(width = 0.4)

ggplot(data = df, aes(x = groups, y = value, fill = type)) +
  geom_violin(position = dodge)+
  geom_boxplot(width=.1, outlier.colour=NA, position = dodge) 

更详尽的解释,请参见什么是position_dodge 中的宽度参数?

这篇关于将小提琴图与躲避箱线图对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆