How to Create an Interactive Correlation Matrix Heatmap in R

Interactive Heatmap in R using heatmaply


How to Create an Interactive Correlation Matrix Heatmap in R

This articles describes how to create an interactive correlation matrix heatmap in R. You will learn two different approaches:

  1. Using the heatmaply R package
  2. Using the combination of the ggcorrplot and the plotly R packages.

Interactive Heatmap in R using heatmaply



Contents:

Prerequisites

Install required R packages:

install.packages("plotly")
install.packages("heatmaply")
install.packages("ggcorrplot")

Data preparation

df <- mtcars

Correlation heatmaps using heatmaply

Load R packages

library(heatmaply)

Basic correlation matrix heatmap

Use the arguments k_col and k_row to specify the desired number of groups by which to color the dendrogram’s branches in the columns and rows, respectively.

heatmaply_cor(
  cor(df),
  xlab = "Features", 
  ylab = "Features",
  k_col = 2, 
  k_row = 2
)

Change the point size according to the correlation test p-values

# Compute correlation coefficients
cor.coef <- cor(df)

# Compute correlation p-values
cor.test.p <- function(x){
    FUN <- function(x, y) cor.test(x, y)[["p.value"]]
    z <- outer(
      colnames(x), 
      colnames(x), 
      Vectorize(function(i,j) FUN(x[,i], x[,j]))
    )
    dimnames(z) <- list(colnames(x), colnames(x))
    z
}
p <- cor.test.p(df)
# Create the heatmap
heatmaply_cor(
  cor.coef,
  node_type = "scatter",
  point_size_mat = -log10(p), 
  point_size_name = "-log10(p-value)",
  label_names = c("x", "y", "Correlation")
)

Correlation heatmaps using ggcorrplot

Load R packages

library(ggcorrplot)

Static heatmap of the correlation matrix

# Compute a correlation matrix
corr <- round(cor(df), 1)

# Compute a matrix of correlation p-values
p.mat <- cor_pmat(df)

# Visualize the lower triangle of the correlation matrix
# Barring the no significant coefficient
corr.plot <- ggcorrplot(
  corr, hc.order = TRUE, type = "lower", outline.col = "white",
  p.mat = p.mat
  )
corr.plot

Make the correlation heatmap interactive

library(plotly)
ggplotly(corr.plot)

`



Version: Français





No Comments

Give a comment

Want to post an issue with R? If yes, please make sure you have read this: How to Include Reproducible R Script Examples in Datanovia Comments