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.


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:


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

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: Logo

You are commenting using your 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