如何在ggplot2的六边形热力图中添加每个六边形的观测数量?
解决方案
要让六边形热力图显示每个区域的观测样本数,你可以通过以下两种方式修改代码:
方式一:调整stat_summary_hex的参数
library(ggplot2) p <- ggplot(diamonds, aes(x = depth, y = carat)) + stat_summary_hex(fun = length, bins = 8) + scale_fill_gradient(low = "blue", high = "red", name = "观测数量") p
- 移除了原代码中
aes里的z = price,因为我们不需要基于价格做汇总 - 将
fun参数从mean改为length,这个函数会返回每个六边形内的样本总数 - 把
scale_fill_gradient2换成scale_fill_gradient(计数是单向递增的数值,不需要中点设置),同时修改图例名称为“观测数量”
方式二:使用stat_bin_hex(更简洁)
stat_bin_hex本身就是用来统计每个六边形内的观测频数的,代码更直接:
library(ggplot2) p <- ggplot(diamonds, aes(x = depth, y = carat)) + stat_bin_hex(bins = 8) + scale_fill_gradient(low = "blue", high = "red", name = "观测数量") p
内容的提问来源于stack exchange,提问作者user19422662
相关产品推荐
相关产品推荐

