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

Main framework for PyTorch music generation model

If your goal is purely symbolic melody generation (e.g., generating MIDI files or notes rather…

24 hours ago

affine_grid() in pytorch

According to PyTorch document, In PyTorch, torch.nn.functional.affine_grid generates a 2D or 3D flow field (sampling…

2 months ago

How to create an Android mobile app with a deep learning AI model ?

Creating an Android mobile app with a deep learning AI model involves several key steps:…

11 months ago

Download source files for R Machine learning

Click here to go to source files for R Machine Learning

1 year ago

Python Machine Learning Source Files

Click here to download Python Machine Learning Source Files !

1 year ago

Install PyTorch on Windows

PyTorch is a deep learning package for machine learning, or deep learning in particular for…

1 year ago