ggplot2中stat_summary_hex热力图未按均值正确缩放问题
问题描述
尝试用ggplot2的stat_summary_hex绘制热力图,怀疑未按Prediction列的均值填充六边形,且热力图无法正确缩放。示例代码如下:
FFxBARHH1 <- data.frame("plate_x" = c("-0.20", "0.21", "-0.19", "0.66", "0.10", "0.52"), "plate_z" = c("3.18", "2.01", "2.56", "2.81", "1.93", "1.85"), "Prediction" = c("0.916", "0.908", "0.872", "0.000", "0.000", "0.000")) FFxBARHH1$Prediction<- as.numeric(FFxBARHH1$Prediction) FFxBARHH1$plate_x<- as.numeric(FFxBARHH1$plate_x) FFxBARHH1$plate_z<- as.numeric(FFxBARHH1$plate_z) ggplot(FFxBARHH1, aes(x = plate_x, y = plate_z, z = Prediction))+ stat_summary_hex(fun = mean, bins = 9) + stat_summary_hex(geom = "text", aes(label = after_stat(value)), fun = length, bins = 9) + scale_fill_gradient2(low = "blue", mid = "white", high = "red", midpoint = 0.240, limits = c(0.0, 1.0)) + 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)
解决方案
你的代码核心逻辑正确,主要是两个细节问题导致可视化异常:
1. 修正x轴范围的顺序
xlim(c(2,-2))会反转x轴方向,打乱六边形的布局逻辑,导致缩放和位置异常。需将x轴范围改为下限在前、上限在后:
xlim(c(-2, 2))
2. 优化六边形数量适配小样本
当前stat_summary_hex(fun = mean)已经在计算每个六边形内Prediction的均值,但你的样本量仅6个数据点,bins=9会生成大量空六边形,导致热力图效果不明显。可以减少六边形数量,让现有数据点集中到少数六边形中,更直观看到均值填充效果:
stat_summary_hex(fun = mean, bins = 3)
修正后的完整代码
FFxBARHH1 <- data.frame("plate_x" = c("-0.20", "0.21", "-0.19", "0.66", "0.10", "0.52"), "plate_z" = c("3.18", "2.01", "2.56", "2.81", "1.93", "1.85"), "Prediction" = c("0.916", "0.908", "0.872", "0.000", "0.000", "0.000")) FFxBARHH1$Prediction<- as.numeric(FFxBARHH1$Prediction) FFxBARHH1$plate_x<- as.numeric(FFxBARHH1$plate_x) FFxBARHH1$plate_z<- as.numeric(FFxBARHH1$plate_z) ggplot(FFxBARHH1, aes(x = plate_x, y = plate_z, z = Prediction))+ stat_summary_hex(fun = mean, bins = 3) + stat_summary_hex(geom = "text", aes(label = after_stat(value)), fun = length, bins = 3) + scale_fill_gradient2(low = "blue", mid = "white", high = "red", midpoint = 0.240, limits = c(0.0, 1.0)) + 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)
额外说明
- 若想让文本标签显示均值而非数据点数量,只需将
fun = length改为fun = mean,并可格式化标签(例如label = round(after_stat(value), 3)); coord_fixed(0.8)是固定x、y轴比例,可根据可视化需求调整,不影响均值计算逻辑。
内容的提问来源于stack exchange,提问作者user19422662
相关产品推荐
相关产品推荐

