gpt4 book ai didi

r - 向 geom_histogram 添加带有每个 bin 或列的百分比的标签

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

我的问题是用组显示直方图列百分比(在 ggplot 中)。
我有两组,我绘制直方图
例子:

ggplot(data, aes(x = variable)) +
geom_histogram(aes(group = grp, fill = grp, y=(..count../sum(..count..))), col = NA, alpha = 0.35) +
stat_bin(aes(y=(..count../sum(..count..)), label=(..count../sum(..count..)), group=grp), geom="text",position=position_stack(vjust=0.5))
当我跑到上面时,我得到了总百分比 label=(..count../sum(..count..))但我想看到直方图列(箱)中的百分比,在任何箱中总和为 100%
例如:
  • Bin1: 20%;80%
  • Bin2:30%;70% 等等。
  • 等等...

  • 如果您想使用 mtcars,请查看以下示例代码:
    ggplot(mtcars, aes(x = qsec)) +
    geom_histogram(aes(group = am, fill = am, y=(..count../sum(..count..))), col = NA, alpha = 0.35) +
    stat_bin(aes(y=(..count../sum(..count..)), label=(..count../sum(..count..)), group=am), geom="text",position=position_stack(vjust=0.5))
    你有什么想法吗?

    最佳答案

    也许这就是你正在寻找的。我的方法使用辅助功能和一些 dplyr计算每个 bin 中每个组的比例:

    library(ggplot2)
    library(dplyr)

    f <- function(x, count, group) {
    data.frame(x, count, group) %>%
    add_count(x, wt = count) %>%
    group_by(x, group) %>%
    mutate(prop = count / n) %>%
    pull(prop)
    }

    ggplot(mtcars, aes(x = qsec)) +
    geom_histogram(
    aes(
    group = factor(am), fill = factor(am),
    y = f(..x.., ..count.., ..group..)
    ),
    col = NA, alpha = 0.35, binwidth = 1
    ) +
    stat_bin(
    aes(
    y = f(..x.., ..count.., ..group..),
    label = scales::percent(f(..x.., ..count.., ..group..), accuracy = 1), group = am
    ),
    binwidth = 1, geom = "text", position = position_stack(vjust = 0.5)
    )

    关于r - 向 geom_histogram 添加带有每个 bin 或列的百分比的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64576401/

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