如何将小提琴图与箱形图对齐

时间:2014-11-19 08:52:48

标签: r plot ggplot2 boxplot

我有这个数据框

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)))

我想将其绘制为小提琴情节,与窄框图对齐并按

分组

变量类型:

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

然而,箱形图并没有与大提琴图对齐,告诉ggplot做这样覆盖的缺失参数是什么?

谢谢!

1 个答案:

答案 0 :(得分:16)

您需要明确为width s设置躲闪的geom

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) 

enter image description here