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

标签 r ggplot2 bar-chart

我正在尝试将两组计数数据与 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/

相关文章:

r - ggplot2 条形图的多个子组

python - 类型错误 : bar() got multiple values for keyword argument 'height'

r - 使用纵向数据集计算随时间变化的百分比

带分数的 r 标签图

r - #include <Rcpp11> 文件未找到错误

r - 自定义轴中断间隔

python - 无法在 python pandas 中获得未堆叠的条形图

javascript - Flot条形图设计

r - 如何使用 sjPlot 在 R Shiny 中报告 html 表?

r - R中核矩阵的快速计算