r - 计算 ggplot2 stat_binhex 中 bin 的百分比

标签 r ggplot2

我正在生成由不同组划分的数据点的 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 ?

最佳答案

你是对的。

> 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 个元素(忽略第一个输出),正如您所期望的。

但更简单的是,您可以使用..密度..*100

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

关于r - 计算 ggplot2 stat_binhex 中 bin 的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8950753/

相关文章:

R 通过使用facet_wrap和数据子集的函数调用传递ggplot参数

r - 如何在ggplot中添加表达式到标签

r - 如何以编程方式生成 70 多个变量的 ggplot?

r - 使用 R 包 : readxl and writing to a csv 按列合并多个 .xlsx 文件时出现标题前有垃圾文本的问题

r - 按列名索引到数据帧的末尾 - R

R:加速 'table()' 数据表对象的操作

反转图中 x 轴的比例

R 绘图自定义数据格式变体

r - 在 R 中根据调整后的生存曲线绘制累积事件

r - 使用 ggplot 以编程方式绘制热门事件的子事件 : R