akshat khetan
akshat khetan

Reputation: 77

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

Desired OutputI 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

Upvotes: 1

Views: 725

Answers (2)

emilliman5
emilliman5

Reputation: 5956

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.

enter image description here

Centered and Scaled (the default)

enter image description here

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))

enter image description here

Upvotes: 2

Ryan
Ryan

Reputation: 934

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, e.g.

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

Upvotes: 1

Related Questions