简体   繁体   中英

Create heatmap in R on the entire matrix rather than by row

Desired Output I want to create a heatmap in R which should consider formatting of colors by all the values in matrix and not just by rows. Ex: I've a following matix

row1 : 1,2,3,4
row2 : 50,50,50,50

When I use heatmap() to plot this matrix, I see row 1 with shades of color, however my row2 is marked as white. I would rather want 50 to be rated in extreme color (eg: Red) and 1,2, 3 & 4 in lighter shades

Hope my question makes sense. Please let me know if anything is unclear. Thanks in advance!

Regards, Akshat

If you read ?heatmap carefully, you will see that by default the rows are scaled and centered .

row1 = c(1,2,3,4)
row2 = c(50,50,50,50)
m = t(as.matrix(cbind(row1, row2)))
par(mfrow=c(2,1))
heatmap(m, col=rev(heat.colors(15)))
heatmap(m, scale = "none", col=rev(heat.colors(15)))

Should do the trick.

在此输入图像描述

Centered and Scaled (the default)

在此输入图像描述

Edit: I reversed the color scale so that red maps to larger values.

2nd: Your desired output is going to be difficult to obtain because 50 is so much larger than the rest of your data. To regain the color detail in row1 you would need to set the breaks in the heatmap function until you get the desired result

heatmap(m, scale = "none", col=rev(heat.colors(5)), breaks=c(0,1,2,3,4,50))

在此输入图像描述

This function should work

library(plotly)
hmap <- function(mat, ... ) {
s <- 1:nrow(mat)
plot_ly(x = s, y = s, z = mat[rev(s), ], type = "heatmap", ...)
}

m <- matrix(1:8, 2, byrow = T)
hmap(m)

You can adjust colors with the colors argument, eg

hmap(m, colors = c('Red','Yellow','Green'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM