We provide effective and economically affordable training courses for R and Python, click here for more details and course registration !

A heatmap is just a grip type data visualization of the correlation matrix between each variable pair of a data frame. In R, if you want to create a heatmap, you will have to first create a correlation matrix using cor() function for the data frame. Then using melt() function from reshape2 package in R to transform this correlation matrix object into a long-form data object. Next we can use function geom_tile() from ggplot2 package to plot a heatmap for this correlation matrix in R. The following example shows generating a heatmap for the four main variables of dataset mtcars in R.

#load package ggplot2 and reshape2
library(ggplot2)
library(reshape2)

#using dataset mtcars
data(mtcars)
#to create a new data frame using four main variables from mtcars
data <- mtcars[,c('mpg','hp','drat','qsec')]

#create a correlation matrix for the dataset
data <- cor(data)

#to transform correlation matrix into long form data object
data1 <- melt(data)

#plot heatmap using geom_tile() function from ggplot2 package.
ggplot(data1, aes(x = Var1, y = Var2, fill = value)) +
  geom_tile() +
  labs(title = "Correlation Heatmap",
       x = "Variable 1",
       y = "Variable 2")
A Simple Heatmap

For getting more knowledge of R, you can watch R tutorial videos on our YouTube channel !


0 Comments

Leave a Reply

Avatar placeholder