gpt4 book ai didi

r - ggplot2:如何根据另一个变量改变箱线图的宽度?

转载 作者:行者123 更新时间:2023-12-04 12:27:27 25 4
gpt4 key购买 nike

我创建了一个箱线图,显示某些物种 $spe 的散布距离 $dist,我希望箱子的宽度与再生密度成正比这些物种。我使用了“varwidth”和重量美学,如下所示,但这仍然不正确,因为它仍然与观察次数成正比,而不仅仅是与再生密度成正比...

(对于密度,我计算了每个物种的比例,所以它从 10 到 100。它在 data_dist2$prop2 列中给出)

p <- ggplot(data_dist2, aes(x = reorder(spe, prop2), y = dist)) + 
coord_flip() +
geom_boxplot(varwidth = TRUE, alpha=0.3, aes(weight=data_dist2$prop2), fill='grey10')

您知道如何使箱线图与我的 prop2 列完全成比例吗?

再生例子:

structure(list(spe = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L), .Label = c("Abies concolor", "Picea abies", "Sequoia semp."
), class = "factor"), dist = c(0, 0, 3, 3, 4, 4, 25, 46, 59,
113, 113, 9, 12, 12, 12, 15, 22, 22, 22, 22, 35, 35, 36, 49,
85, 85, 90, 5, 5, 1, 1, 8, 13, 48, 48, 52, 52, 52, 65, 89), prop2 = c(92.17,
92.17, 92.17, 92.17, 92.17, 92.17, 92.17, 92.17, 92.17, 92.17,
92.17, 10.9, 10.9, 10.9, 10.9, 10.9, 10.9, 10.9, 10.9, 10.9,
10.9, 10.9, 10.9, 10.9, 10.9, 10.9, 10.9, 100, 100, 100, 100,
100, 100, 100, 100, 100, 100, 100, 100, 100)), row.names = c(NA,
-40L), class = "data.frame")

最佳答案

权重似乎并不是为此而设计的,但您可以对其进行一些修改。首先请注意,赋予每个组的权重是观察值权重的总和,因此如果您对每个物种的观察值不同,那么您可能需要将 prop2 更改为当前值除以按组中观察的数量。 (我无法从你的例子中判断这是否适用)

然后请注意,宽度与重量的平方根成正比,因此更改您的代码以将其反转:

p <- ggplot(data_dist2, aes(x = reorder(spe, prop2), y = dist)) + 
coord_flip() +
geom_boxplot(varwidth = TRUE, alpha=0.3, aes(weight=data_dist2$prop2^2), fill='grey10')

关于r - ggplot2:如何根据另一个变量改变箱线图的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60528555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com