I want to build custom heatmap with color ranges based on multiple conditions.
I found a similar post that focuses on Heatmap with conditions. However, it does not address my question of having dedicated color scales for different conditions.
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')
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)
perf_cols <- c(colorRampPalette(c("red", "green"))( 9 ))
perf_text_cols <- c(rep("white", 9))
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 = '')
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
The heatmap from the above code looks like this:
However, I want the heatmap to have multiple color gradients based on the given conditions.
For ex, the conditions are below:
If the values are < 0.4 -> Green
If the values are > 0.5 -> Red
Values that lie between 0.4 and 0.5 then -> Grey
These colors would be having their own gradient scale. Higher the value in a condition darker the shade of that color.