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

R ggplot2热图如何实现双颜色填充并修复坐标轴显示问题

R ggplot热图分段填色与坐标轴刻度异常解决方案

需求与异常说明

需要实现的热图填充规则:

  • 填充值处于[-0.1, 0.1]区间时使用第一种颜色
  • 填充值在上述区间外时使用第二种颜色
    原有代码运行后存在两处异常:双颜色填充效果无法实现、坐标轴仅显示10%和90%两个刻度,原代码如下:
ggplot(base, aes(x,y, fill= base$`Equal Opportunity Difference`)) + 
        geom_tile() +
        #axis formatting
        scale_x_discrete(breaks = c(10, 20, 30, 40 , 50, 60, 70, 80, 90),
                       labels = c("10%", "20%","30%", "40%","50%", "60%", "70%","80%", "90%"),
                       limits = c(10,90)) +
        scale_y_discrete(breaks = c(10, 20, 30, 40 , 50, 60, 70, 80, 90),
                       labels = c("10%", "20%","30%", "40%","50%", "60%", "70%","80%", "90%"),
                       limits = c(10,90)) +
    
        geom_text(aes(label = signif(base$`Equal Opportunity Difference`,2)), color = "white", 
        size = 4) +
        scale_fill_gradient2(midpoint=c(-.1, s.1), low="#B2182B", high="#2166AC")

异常原因

  • 坐标轴刻度异常:scale_x_discrete/scale_y_discrete仅适用于离散型(字符/因子)坐标轴变量,若x、y列为数值类型,使用离散刻度函数会导致大部分预设刻度无法识别,仅显示首尾边界值。
  • 填充效果异常:scale_fill_gradient2是三色渐变比例尺,仅支持单个中点值参数,原代码传入长度为2的中点向量还存在拼写错误(s.1应为0.1),完全无法实现分段双颜色填充的需求。另外aes()映射中直接使用base$列名的写法会破坏数据映射关系,容易引发其他显示异常。

修正后可运行代码

ggplot(base, aes(x, y, fill = `Equal Opportunity Difference`)) + 
  geom_tile() +
  # 数值型坐标轴使用continuous比例尺,修复刻度显示问题
  scale_x_continuous(breaks = c(10, 20, 30, 40 , 50, 60, 70, 80, 90),
                     labels = c("10%", "20%","30%", "40%","50%", "60%", "70%","80%", "90%"),
                     limits = c(10, 90)) +
  scale_y_continuous(breaks = c(10, 20, 30, 40 , 50, 60, 70, 80, 90),
                     labels = c("10%", "20%","30%", "40%","50%", "60%", "70%","80%", "90%"),
                     limits = c(10, 90)) +
  geom_text(aes(label = signif(`Equal Opportunity Difference`, 2)), color = "white", size = 4) +
  # 自定义分段填充色:区间外统一为蓝色#2166AC,区间内为浅灰色#F7F7F7,可按需替换颜色值
  scale_fill_gradientn(
    colours = c("#2166AC", "#2166AC", "#F7F7F7"),
    values = scales::rescale(c(-Inf, -0.1, 0.1, Inf)),
    name = "Equal Opportunity Difference"
  )

可选效果调整

如果需要区间外小于-0.1显示红色、大于0.1显示蓝色、中间区间统一显示浅色,只需要将scale_fill_gradientn的colours参数替换为c("#B2182B", "#F7F7F7", "#F7F7F7", "#2166AC")即可。

内容的提问来源于stack exchange,提问作者Matthew Francis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 13:48:18