Creating an Interactive Correlation Heatmap

 

An interactive plot shows detailed information of each data point when the user hovers on the plot. Let’s check out how to plot an interactive correlation heatmap using the correlation matrix and p-value matrix. ggplotly( ) function takes in a correlation matrix of the data and gives an interactive heatmap plot and the details can be viewed on hovering on the map.

 

Function: ggplotly( p = ggplot2::last_plot(),   width = NULL,  height = NULL … )

Arguments:

  • p – a ggplot object
  • width – Width of the plot in pixels (optional, defaults to automatic sizing)
  • height – Height of the plot in pixels (optional, defaults to automatic sizing)

 

R




# install and load the plotly package
install.packages("plotly")
library(plotly)
library(ggcorrplot)
 
# create corr matrix and
# corresponding p-value matrix
corr_mat <- round(cor(data),2)
p_mat <- cor_pmat(data)
 
# plotting the interactive corr heatmap
corr_mat <- ggcorrplot(
  corr_mat, hc.order = TRUE, type = "lower",
  outline.col = "white",
  p.mat = p_mat
)
 
ggplotly(corr_mat)


 
 

Output:

 

 



How to Create Correlation Heatmap in R

In this article let’s check out how to plot a Correlation Heatmap in R Programming Language.

Analyzing data usually involves a detailed analysis of each feature and how it’s correlated with each other. It’s essential to find the strength of the relationship between each feature or in other words how two variables move in association to each other. If the variables grow together in the same direction it’s a positive correlation otherwise a negative correlation. This correlation can be visualized via various graphs such as scatter plots etc.

Similar Reads

Loading data

Let’s load the environmental dataset and view the first 6 rows of the data using the head( ) function....

Create Correlation Matrix

...

Correlation Heatmap using ggplot2

Let’s create a correlation matrix for our data using cor( ) function and round each value to 2 decimal places. This matrix can be used to easily create the heatmap....

Reorder the Correlation matrix and Plot Heatmap

...

Adding Correlation coefficients to Heatmap

Using ggplot2 let’s visualize correlation matrix on a heatmap....

Correlation Heatmap using heatmaply

...

Correlation Heatmap using ggcorplot

Reordering or sorting the correlation matrix with respect to coefficient helps us to easily identify patterns between the features/variables. Let’s check out how to reorder the correlation matrix using hclust( ) function by clustering the features hierarchically(hierarchical clustering)....

Plotting the lower triangle of the correlation heatmap

...

Plotting the upper triangle of the correlation heatmap

Correlation coefficients are a measure that represents how strong the relationship is between two variables. The higher the absolute value of the coefficient, the higher is the correlation....

Creating an Interactive Correlation Heatmap

...