如何改变多组条件的boxplot中一个boxplot的宽度?

问题描述 投票:0回答:1

我是R的初学者,想做一个boxplot,显示某产品在不同时间点的肿瘤积累情况,有两种不同的条件。我想出了下面的图片。

带多组+条件的boxplot

我用了这个代码。

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小时时间点的数据,所以最右边的方框的外观要大得多。我似乎无法弄清楚如何在不改变其余部分的情况下改变这个单框的宽度。

r ggplot2 width boxplot
1个回答
1
投票

这应该会对你有所帮助。 首先,让我用一个示例数据集和一个示例boxplot。

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= 的论点 geom_boxpot. 我的意思是这样的。

ggplot(df, aes(grp, y)) +
    geom_boxplot(aes(fill=grp, group=samplename),
        position=position_dodge(preserve='single'))

enter image description here

这就解决了你的宽度问题,让所有的单独盒子(无论是否闪避)都是一样的宽度,但这也意味着属于 "A组 "的盒子仍然是向左闪避的。 这是一个问题,在通过添加以下内容来解决之前,它是一个问题 position_dodge2() 电影字幕:"定位_躲避的回归!")。 只需将其替换为 position_dodge() 修正了这个问题,你可以让所有的方框与它们的X轴值对齐。

ggplot(df, aes(grp, y)) +
    geom_boxplot(aes(fill=grp, group=samplename),
        position=position_dodge2(preserve='single'))

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.