gpt4 book ai didi

r - ggplot 中的标准化条形高度

转载 作者:行者123 更新时间:2023-12-01 10:42:28 25 4
gpt4 key购买 nike

我正在尝试将两组计数数据与 ggplot 进行比较。数据集的长度不同,我无法弄清楚如何将条形高度标准化为每个数据集中的行数。请参阅下面的代码示例:

示例数据集

set.seed(47)
BG.restricted.hs = round(runif(100, min = 47, max = 1660380))
FG.hs = round(runif(1000, min = 0, max = 1820786))

dat = data.frame(x = c(BG.restricted.hs, FG.hs),
source = c(rep("BG", length(BG.restricted.hs)),
rep("FG", length(FG.hs))))
dat$bin = cut(dat$x, breaks = 200)

第一次尝试:没有标准化。由于数据集的大小,条形高度非常不同!
ggplot(dat, aes(x = bin, fill = source)) +
geom_bar(position = "identity", alpha = 0.2) +
theme_bw() +
scale_x_discrete(breaks = NULL)

第二次尝试:尝试使用 ..count.. 属性进行标准化
ggplot(dat,aes(x = bin, fill = source))+
geom_bar(aes(y = ..count../sum(..count..)), alpha=0.5, position='identity')

这产生了视觉上相同的结果,仅缩放了整体 y 轴。似乎 ..count.. 没有查看“源”列中的标签,尽管进行了数小时的试验,但我似乎无法找到一种方法来做到这一点。这可能吗?

最佳答案

stat_bin也返回 density: density of points in bin, scaled to integrate to 1所以

ggplot(dat,aes(x = bin, fill = source)) + 
stat_bin(aes(group=source, y=..density..))

关于r - ggplot 中的标准化条形高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28969436/

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