如何为热力图按行设色:每行极值对应深浅填充色
按行(类别)独立设置热力图填充颜色的解决方案
当前你的ggplot2热力图采用全局数值范围映射填充色,要改为每个branques类别(每行)独立使用自身的最小值和最大值作为颜色渐变的端点,可以通过先对数据分组标准化,再映射填充色来实现,具体步骤如下:
步骤1:分组标准化数据
使用dplyr包对数据按branques分组,将每组的values标准化到[0,1]区间,确保每个类别的极值对应颜色渐变的两端:
library(dplyr) # 对数据分组标准化 varIPI_branques_CAT_long <- varIPI_branques_CAT_long %>% group_by(branques) %>% mutate( val_min = min(values, na.rm = TRUE), val_max = max(values, na.rm = TRUE), scaled_row = (values - val_min) / (val_max - val_min) # 标准化到0-1区间 ) %>% ungroup()
步骤2:修改ggplot2代码
将fill映射到新生成的scaled_row变量,同时保留原始values作为文本标签,配色可沿用你原有的设置:
library(ggplot2) library(scales) heatmap_branquesCAT <- ggplot(varIPI_branques_CAT_long, aes(x = time, y = branques, fill = scaled_row)) + geom_tile(aes(width = 31)) + geom_text(aes(label = round(values, 1)), family = "serif", color = "black", size = 4) + scale_x_date(expand = c(0, 0), breaks = "1 months", labels = date_format("%b %y")) + scale_y_discrete(expand = c(0, 0), labels = c("Subministrament d'aigua", "Indústries d'alimentació i begudes", "Altres indústries manufactureres", "Materials i equips elèctrics, electrònics i òptics", "Energia elèctrica", "Fabricació de productes farmacèutics", "Índex general (IPI)", "Indústries extractives", "Indústries manufactureres", "Fabricació de maquinària i equips mecànics", "Metal·lúrgia i fabricació de productes metàl·lics", "Fabricació d'altres productes minerals no metàl·lics", "Indústries del paper", "Fabricació productes cautxú i matèries plàstiques", "Indústries químiques", "Indústries tèxtils", "Fabricació de material de transport")) + labs(title = "Índex de Producció Industrial", subtitle = "% de variació interanual", x = "", y = " ", caption = "Font: Idescat.") + scale_fill_gradient( low = "#CC3300", high = "#66CC00", limits = c(0, 1) # 标准化后的值范围固定为0-1 ) + theme_minimal() + tema + # 保留你自定义的tema主题 theme(axis.text = element_text(size = 12, colour = "black"), legend.position = "none") heatmap_branquesCAT
补充说明
- 若需要保留以0为中点的双色渐变逻辑,可调整标准化规则,或针对每组单独计算中点,但这种场景下
scale_fill_gradient更合适——因为不同组的极值范围差异大,全局中点没有实际参考意义。 - 标准化时加入
na.rm = TRUE是为了避免缺失值导致计算出错。
内容的提问来源于stack exchange,提问作者Maria
相关产品推荐
相关产品推荐

