Torvon
Torvon

Reputation: 1163

Heatmap in R (using the heatmap() function)

I have a correlation matrix and want to obtain a heat map from cold (negative correlations) to red (positive correlations), with white being 0 correlations.

Now, the heatmap command seems to somehow average, even if I say 'scale=none', meaning that the average correlation is portrayed as white (which, in my case, is 0.2, meaning that all 0 correlations are slightly blue).

Can you help me fix this? Thank you

library(stats)
library(gplots)
library(RColorBrewer)
heatmap(graph.g,Colv = NA, Rowv=NA, revC=T, scale='none', 
    xlab= "IDS-C30 symptoms", main = "Heatmap of glasso associations",
    col = rev(brewer.pal(11,"RdBu")))

enter image description here

Upvotes: 0

Views: 2678

Answers (2)

Tim
Tim

Reputation: 7474

For correlation matrix you can also use corrplot or corrgram libraries that are designed especially for this purpose. They work out of the box and also have additional plotting features. In R Graphics Cookbook you can find examples of how to draw this kind of plot with ggplot2 using geom_tile() or geom_raster() functions.

library(corrplot)
library(corrgram)
library(ggplot2)
library(reshape2)

corrplot(cor(mtcars))
corrplot(cor(mtcars), method="color")
corrgram(cor(mtcars))
corrgram(cor(mtcars), lower.panel=panel.shade,
         upper.panel=panel.pie)

p <- ggplot(melt(cor(mtcars)), aes(x=Var1, y=Var2, fill=value))
p + geom_tile() + scale_fill_gradient2(midpoint=0, limits=c(-1, 1))

enter image description here enter image description here enter image description here enter image description here enter image description here

Upvotes: 2

Cory Brunson
Cory Brunson

Reputation: 718

This is not an elegant solution, but it seems to get the job done. The gist is to restrict the spectrum to the values taken by the correlation matrix, and to make this smoother the palette is stretched from the 11-value maximum provided by brewer.pal (using an odd number of repeats so that the median remains an integer).

vec <- rep(rev(brewer.pal(11,"RdBu")), each = 101)  # stretched palette
med <- (length(vec) + 1) / 2  # middle of palette
rad <- length(vec) - med  # radius of palette
min.g <- med + min(graph.g) * rad  # lowest value taken
max.g <- med + max(graph.g) * rad  # highest value taken
heatmap(graph.g,Colv = NA, Rowv=NA, revC=T, scale='none',
    xlab= "IDS-C30 symptoms", main = "Heatmap of glasso associations",
    col = vec[min.g:max.g])  # palette restricted to realized values

Upvotes: 2

Related Questions