R Programming

How to create a heapmap using ggplot2 in R

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 !

wilsonzhang746

Recent Posts

Download R Course source files

Click here to download R Course source files !

2 months ago

Download Python Course source files

Click here to download Python Course Source Files !

2 months ago

How to create a data frame from nested dictionary with Pandas in Python

For online Python training registration, click here ! Pandas provides flexible ways of generating data…

5 months ago

How to delete columns of a data frame in Python

For online Python training registration, click here ! Data frame is the tabular data object…

5 months ago

Using isin() to check membership of a data frame in Python

Click her for course registration ! When a data frame in Python is created via…

5 months ago

How to assign values to Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago