如何在具有多个组/条件的箱线图中更改一个箱线的宽度?

时间:2020-04-29 16:36:26

标签: r ggplot2 width boxplot

我是R的初学者,他试图制作一个箱形图,显示在两种不同情况下,随着时间的推移在不同点上某种产品的肿瘤积累。我想到了以下图片:

Boxplot with multiple groups + condition

我使用了以下代码:

ggplot(tumor, aes(x=time_point, y=IA, fill=condition)) + ggtitle ("Tumor accumulation") + xlab("Time post-injection (h)") + ylab("%IA/kg") + geom_boxplot()+ geom_point(position=position_jitterdodge(0))+ scale_x_discrete(limits=c("2", "24", "96", "144")) + scale_fill_brewer(palette="Paired") + theme_minimal() + expand_limits(y=0)

因为没有条件C1和144小时时间点的数据,所以最右边的框的外观要大得多。我似乎无法弄清楚如何在不更改其余框的情况下更改单个框的宽度。

1 个答案:

答案 0 :(得分:1)

这应该可以帮助您。首先,让我使用示例数据集和示例箱线图:

df <- data.frame(
    samplename=c(rep("A", 10), rep("B1", 10), rep("B2", 10)),
    grp=c(rep("Group A", 10), rep("Group B", 20)),
    y=c(rnorm(10), rnorm(10, 0.2), rnorm(10, 0.35, 0.1))
)

ggplot(df, aes(grp, y)) +
    geom_boxplot(aes(fill=grp, group=samplename))

enter image description here

这为您提供了一个类似于示例的图。左侧的框被扩展以填充整个x美学,而右侧的框被拆分(正式术语为“躲避”),以使B1 + B2的总和= B的宽度。

要解决此问题,可以使用preserve='single'函数中包含的position_dodge()参数,该参数必须应用于position=的{​​{1}}参数。这就是我的意思:

geom_boxpot

enter image description here

这通过将所有单个框(躲避或其他方式)设置为相同的宽度来解决宽度问题,但这也意味着属于“ Group A”的框仍被躲避到左侧。在添加ggplot(df, aes(grp, y)) + geom_boxplot(aes(fill=grp, group=samplename), position=position_dodge(preserve='single')) 之前,这是一个问题(电影字幕:“ position_dodge的返回!”)。只需将其替换为position_dodge2()即可解决此问题,并且所有框都与其x轴值对齐:

position_dodge()

enter image description here