首页 文章

在ggplot2 stat_binhex中计算垃圾箱的百分比

提问于
浏览
4

我正在生成不同组所面对的数据点的binhex图 . 每个组可能具有不同的总点数,因此,不是每个bin值是绝对点数,我希望它是该组中总点数的百分比 . 这是我现在正在尝试的:

d <- data.frame(grp= c(rep('a',10000), rep('b',5000)), 
                x= rnorm(15000), 
                y= rnorm(15000))
ggplot(d, aes(x= x, y= y)) + 
     stat_binhex(aes(fill= ..count../sum(..count..)*100)) + 
     facet_wrap(~grp)

它是否正确? sum(..count..) 是否按每个方面生成总点数(组'a'为10000,组'b'为5000),或两个方面的结果为15000?

1 回答

  • 5

    你是对的 .

    > ggplot(d, aes(x= x, y= y)) + stat_binhex(aes(fill= {print(sum(..count..));..count../sum(..count..)*100})) + facet_wrap(~grp)
    [1] 10000
    [1] 10000
    [1] 5000
    

    这意味着数据被分为10000和5000个元素(忽略第一个输出),这是您所期望的 .

    但更容易,你可以使用 ..density..*100

    ggplot(d, aes(x= x, y= y)) + stat_binhex(aes(fill= ..density..*100)) + facet_wrap(~grp)
    

相关问题