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

如何为六边形填充色显示正确图例?ggplot2六边形箱图问题

问题解决:移除count图例,仅保留Prediction热力图例

你的问题核心在于第二个stat_summary_hex调用——即使指定了geom="text",该统计层仍会默认生成fill美学映射(对应计数结果),覆盖了第一个统计层基于Prediction均值的fill映射,导致图例显示count而非目标的热力值。

解决方案

通过以下两种方式均可实现需求,推荐第一种更简洁的写法:

方法一:取消第二个统计层的fill映射

FF1xBARHH <- ggplot(FFxBARHH, aes(x = plate_x, y = plate_z, z = Prediction)) +
  stat_summary_hex(fun = mean, bins = 9) +
  # 取消fill映射+禁用图例生成,避免干扰主热力层
  stat_summary_hex(geom = "text", aes(label = after_stat(value), fill = NA), 
                   fun = length, bins = 9, show.legend = FALSE) +
  scale_fill_gradient2(low = "blue", mid = "white", high = "red", midpoint = 0.240,
                       name = "Prediction") + # 可选:给图例设置明确标题
  xlim(c(2,-2)) +
  ylim(c(0,5)) +
  coord_fixed(0.8)+
  labs(title = "Gerrit Cole Fastball April 2022 ExAVG Map RHH")+
  annotate('rect', xmin = -0.85, xmax = 0.85, ymin = 1.6, ymax = 3.5, 
           fill = 'black', color = 'black', alpha = 0.0001, size = 1)

方法二:取消全局aes继承

通过隔离两个统计层的美学映射,避免互相干扰:

FF1xBARHH <- ggplot(FFxBARHH, aes(x = plate_x, y = plate_z)) +
  # 明确指定主热力层的fill映射
  stat_summary_hex(aes(z = Prediction, fill = after_stat(value)), 
                   fun = mean, bins = 9) +
  # 取消继承全局aes,仅保留需要的文本映射+禁用图例
  stat_summary_hex(geom = "text", aes(label = after_stat(value)), 
                   fun = length, bins = 9, inherit.aes = FALSE, show.legend = FALSE) +
  scale_fill_gradient2(low = "blue", mid = "white", high = "red", midpoint = 0.240,
                       name = "Prediction") +
  xlim(c(2,-2)) +
  ylim(c(0,5)) +
  coord_fixed(0.8)+
  labs(title = "Gerrit Cole Fastball April 2022 ExAVG Map RHH")+
  annotate('rect', xmin = -0.85, xmax = 0.85, ymin = 1.6, ymax = 3.5, 
           fill = 'black', color = 'black', alpha = 0.0001, size = 1)

内容的提问来源于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:18:06