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

R ggplot2实现多条件自定义区间分段独立渐变色热图

多条件分段独立色阶自定义热图实现

原有代码使用全区间统一的红-绿渐变,无法满足分段独立配色的需求,核心调整点是按三个数值区间分别生成对应色系的渐变色板,再拼接为完整的填充色映射,完全匹配提出的配色规则:

  • 数值小于0.4:使用绿色系,区间内数值越高绿色越深
  • 数值在0.4~0.5区间:使用灰色系,区间内数值越高灰色越深
  • 数值大于0.5:使用红色系,区间内数值越高红色越深

完整实现代码

library(ggplot2)
library(reshape2) 

# 构造示例数据
tt <- data.frame(C1=c(0.4,.5,.5, 0, .8,.8),
                 C2=c(.5,.6,.7, 0.6, .7,.8), 
                 C3=c(.8,.7,.9, 0, .8,.7), 
                 C4=c(.8,.1,.6, 0.9, .5,.9),
                 C5=c(0.4,.6,.6, 0.5, .8,.8),
                 C6=c(0.8,.7,.5, 0.1, .8,.8), 
                 C7=c(0.8,.6,.4, 0, .8,.8))

row.names(tt) <- paste("F", 1:6, sep='')
tt <- as.matrix(tt)

tt_melt <- melt(tt) 
colnames(tt_melt) <- c('rows', 'columns', 'performance')

# 按0.1步长切分数值区间
tt_melt$cut <- cut(tt_melt$performance, 
                   breaks=c(0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0),
                   labels=as.character(c(0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)),
                   include.lowest=TRUE)

# 分三段生成独立渐变色板
# 0-0.4区间:4个档位,浅绿到深绿
green_pal <- colorRampPalette(c("#e5f5e0", "#31a354"))(4)
# 0.4-0.5区间:2个档位,浅灰到深灰
grey_pal <- colorRampPalette(c("#f0f0f0", "#bdbdbd"))(2)
# 0.5-1.0区间:4个档位,浅红到深红
red_pal <- colorRampPalette(c("#fee0d2", "#de2d26"))(4)
# 拼接为完整填充色向量
perf_cols <- c(green_pal, grey_pal, red_pal)

# 适配底色的文字颜色:浅底用黑字,深底用白字
perf_text_cols <- c(rep("black", 3), "white", rep("black", 2), rep("white", 4))

# 绘图
gg <- ggplot(data=tt_melt, aes(x=columns, y=rows, fill=cut))
gg <- gg + geom_tile()
gg <- gg + geom_text(aes(label=performance, color=cut)) 
gg <- gg + labs(title = '', x = '列名', y = '行名')
gg <- gg + coord_equal()
gg <- gg + scale_colour_manual(values = perf_text_cols)
gg <- gg + scale_fill_manual(values=perf_cols)
gg <- gg + theme_minimal(base_size = 12, base_family = "")
gg <- gg + theme(legend.position="none")
gg

自定义调整说明

如果需要调整各区间的颜色深浅,直接修改对应色板函数里的起止十六进制色值即可:

  • 要让浅色更浅、深色更深,拉大起止颜色的明度差即可
  • 如果需要更细的渐变粒度,调整cut函数的breaks步长,同步修改三个色板生成的档位数量,保证总色数和区间标签数一致即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 14:19:18