custom color palette with custom breaks on stats::heatmap

50 Views Asked by At

I'd like to create a clustered heatmap of my data, clustering different models and categories based on the MAPE. I'd like to apply the color palette green-white-red, in which the range of green colors (MAPE: 0-10) is smaller than the range of red colors (MAPE 10, up to 100), with a mid-value of 10. However, when i try to do this, it results in a heatmap containing only green colors.

Dummy matrix - Let's say my data looks like this:

matrix_heatmap <- matrix(1:16, nrow=4, ncol=4, 
                         dimnames=list(c("W", "X", "Y", "Z"), 
                                         c("A", "B", "C", "D")))
matrix_heatmap

custom colorpalette and breaks

colors <- colorRampPalette(c("green", "white", "red"))
number_breaks <- 6
breaks_green <- seq(from=min(matrix_heatmap), to=10, 
                    length.out=floor(number_breaks / 2))
breaks_red <- seq(from=10, to=quantile(matrix_heatmap, 0.95), 
                  length.out=ceiling(number_breaks / 2))
breaks <- unique(c(0, breaks_green, breaks_red))

custom_palette <- colors(number_breaks - 1)

custom_palette
breaks

heatmap(matrix_heatmap, 
        col=custom_palette, 
        breaks=breaks,
        cexRow=0.5, cexCol=0.5)
legend("topleft", legend=breaks, fill=custom_palette, title="legenda")
1

There are 1 best solutions below

2
thothal On

heatmap scales the values depending on parameter scale. From ?heatmap:

scale: character indicating if the values should be centered and
       scaled in either the row direction or the column direction,
       or none.  The default is ‘"row"’ if ‘symm’ false, and
       ‘"none"’ otherwise.

So either you provide your breaks in a scaled version, or you ask for no-scaling:

heatmap(matrix_heatmap, 
        col = custom_palette, 
        breaks = breaks,
        cexRow = .5, cexCol = .5, scale = "none")

Heatmap using all teh colors provided