Plotting Heatmaps using R

A heatmap is the most sweet way of visualizing the values of a matrix. The numbers are converted in a colored and intuitive graphic.

Let’s take the following matrix in CSV format, with hypothetical correlation values varying from 0 to 1.

Name,A,B,C,D,E
var1,0.1,0.0,0.7,0.2,0.1
var2,0.2,0.3,0.4,1.0,0.0
var3,0.7,0.4,0.5,0.0,0.0
var4,0.3,0.1,0.5,0.3,0.6
vae5,0.0,0.8,0.9,1.0,0.5

Based only on the above matrix, it is hard to say what variables are more or less correlated. But in a heatmap the same matrix looks like this:

teste…the color scale from brown to yellow varies in accordance to the matrix correlation values.

Here is the R code:

library("ggplot2")
library("reshape2")
library("plyr")
library("scales")

dataset <- read.csv("table.csv")
dataset$Name <- with(dataset, reorder(Name, A))
dataset.m <- melt(dataset)
dataset.m <- ddply(dataset.m, .(variable), transform, rescale = rescale(value))

(p <- ggplot(dataset.m, aes(variable, Name)) + geom_tile(aes(fill = rescale), colour = "white") + scale_fill_gradient(low = "saddlebrown", high = "gold"))

base_size <- 10

p + theme_grey(base_size = base_size) + labs(x = "Title X axis", y = "Title Y axis") + scale_x_discrete(expand = c(0, 0)) + scale_y_discrete(expand = c(0, 0)) + theme(axis.ticks = element_blank(), axis.text.x = element_text(size = base_size * 0.8, angle = 330, hjust = 0, colour = "grey50"))

ggsave("heatmap.png")
This entry was posted in Local Tools. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s