You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 12:17:18