knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  # out.width = "100%",
  # dpi = 300,
  fig.path = "tools/README-",
  fig.cap = "ggcorrplot: visualize correlation matrix using ggplot2"
)

R build status CRAN_Status_Badge CRAN Checks Downloads Total Downloads

ggcorrplot: Visualization of a correlation matrix using ggplot2

The ggcorrplot package can be used to visualize easily a correlation matrix using ggplot2. It provides a solution for reordering the correlation matrix and displays the significance level on the correlogram. It includes also a function for computing a matrix of correlation p-values.

Find out more at http://www.sthda.com/english/wiki/ggcorrplot-visualization-of-a-correlation-matrix-using-ggplot2.

Installation and loading

ggcorrplot can be installed from CRAN as follow:

install.packages("ggcorrplot")

Or, install the latest version from GitHub:

# Install
if(!require(devtools)) install.packages("devtools")
devtools::install_github("kassambara/ggcorrplot")
# Loading
library(ggcorrplot)

Getting started

Compute a correlation matrix

The mtcars data set will be used in the following R code. The function cor_pmat() [in ggcorrplot] computes a matrix of correlation p-values.

# Compute a correlation matrix
data(mtcars)
corr <- round(cor(mtcars), 1)
head(corr[, 1:6])

# Compute a matrix of correlation p-values
p.mat <- cor_pmat(mtcars)
head(p.mat[, 1:4])

Correlation matrix visualization

# Visualize the correlation matrix
# --------------------------------
# method = "square" (default)
ggcorrplot(corr)
# method = "circle"
ggcorrplot(corr, method = "circle")

# Reordering the correlation matrix
# --------------------------------
# using hierarchical clustering
ggcorrplot(corr, hc.order = TRUE, outline.color = "white")

# Types of correlogram layout
# --------------------------------
# Get the lower triangle
ggcorrplot(corr,
           hc.order = TRUE,
           type = "lower",
           outline.color = "white")

# Get the upper triangle
ggcorrplot(corr,
           hc.order = TRUE,
           type = "upper",
           outline.color = "white")

# Change colors and theme
# --------------------------------
# Argument colors
ggcorrplot(
  corr,
  hc.order = TRUE,
  type = "lower",
  outline.color = "white",
  ggtheme = ggplot2::theme_gray,
  colors = c("#6D9EC1", "white", "#E46726")
)

# Add correlation coefficients
# --------------------------------
# argument lab = TRUE
ggcorrplot(corr,
           hc.order = TRUE,
           type = "lower",
           lab = TRUE)

# Add correlation significance level
# --------------------------------
# Argument p.mat
# Barring the no significant coefficient
ggcorrplot(corr,
           hc.order = TRUE,
           type = "lower",
           p.mat = p.mat)

# Leave blank on no significant coefficient
ggcorrplot(
  corr,
  p.mat = p.mat,
  hc.order = TRUE,
  type = "lower",
  insig = "blank"
)


kassambara/ggcorrplot documentation built on Nov. 16, 2022, 2:07 p.m.