【问题标题】:Align violin plots with dodged box plots将小提琴图与闪避箱线图对齐
【发布时间】:2015-01-16 17:09:18
【问题描述】:

我有这个数据框

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 = 0.1, outlier.colour = NA)

但是,箱线图与小提琴图不一致。告诉 ggplot 做这样的覆盖缺少什么论据?

谢谢!

【问题讨论】:

  • 我不确定您所说的“对齐”到底是什么意思。可能设置position?见help("position_dodge")

标签: r ggplot2 plot boxplot violin-plot


【解决方案1】:

您需要为geoms 显式设置躲避的width

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) 


更详尽的解释请见What is the width argument in position_dodge?

【讨论】:

  • 我正在寻找一种方法使箱线图充满白色,同时保留箱线图和小提琴的位置,并保持小提琴的颜色。您知道实现此目标的方法吗?
  • @svavil 是的,在geom_boxplot 中,使用group 参数而不是fillggplot(data = df, aes(x = groups, y = value)) + geom_violin(aes(fill = type), position = dodge) + geom_boxplot(aes(group = interaction(type, groups)), width=.1, outlier.colour=NA, position = dodge)。见?aes_group_order
猜你喜欢
  • 1970-01-01
  • 2021-05-01
  • 2015-11-06
  • 2016-07-02
  • 2022-12-09
  • 2015-08-27
  • 1970-01-01
  • 1970-01-01
  • 2022-10-09
相关资源
最近更新 更多