% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/ggcorrplot.R
\name{ggcorrplot}
\alias{ggcorrplot}
\alias{cor_pmat}
\title{Visualization of a correlation matrix using ggplot2}
\usage{
ggcorrplot(
  corr,
  method = c("square", "circle"),
  type = c("full", "lower", "upper"),
  ggtheme = ggplot2::theme_minimal,
  title = "",
  show.legend = TRUE,
  legend.title = "Corr",
  show.diag = NULL,
  colors = c("blue", "white", "red"),
  outline.color = "gray",
  hc.order = FALSE,
  hc.method = "complete",
  lab = FALSE,
  lab_col = "black",
  lab_size = 4,
  lab_fontface = "plain",
  sig.stars = FALSE,
  p.mat = NULL,
  sig.level = 0.05,
  insig = c("pch", "blank", "stars"),
  pch = 4,
  pch.col = "black",
  pch.cex = 5,
  tl.cex = 12,
  tl.col = NULL,
  tl.srt = 45,
  tl.vjust = 1,
  tl.hjust = 1,
  digits = 2,
  as.is = FALSE,
  nsmall = 0L,
  leading.zero = TRUE,
  legend.limit = c(-1, 1),
  circle.scale = 1,
  coord.fixed = TRUE,
  lower.method = NULL,
  upper.method = NULL,
  hc.rect = NULL,
  palette = NULL,
  preset = NULL,
  hc.rect.col = "gray30",
  scale.square = FALSE,
  cell.grid = FALSE,
  cell.grid.col = "grey90"
)

cor_pmat(x, ..., use = c("pairwise.complete.obs", "everything"))
}
\arguments{
\item{corr}{the correlation matrix to visualize}

\item{method}{character, the visualization method of correlation matrix to be
used. Allowed values are "square" (default), "circle".}

\item{type}{character, "full" (default), "lower" or "upper" display. A mixed
layout (see \code{lower.method}/\code{upper.method}) always uses the full
matrix.}

\item{ggtheme}{ggplot2 function or theme object. Default value is
`theme_minimal`. Allowed values are the official ggplot2 themes including
theme_gray, theme_bw, theme_minimal, theme_classic, theme_void, .... Theme
objects are also allowed (e.g., `theme_classic()`). A mixed "number" region
reads the background from this argument, resolved against the default theme
in force when \code{ggcorrplot()} is called, to decide how dark to draw the
coefficient text (see \code{lower.method}/\code{upper.method}). So a dark
theme belongs here rather than added to the returned plot with \code{+}, and
a \code{\link[ggplot2]{theme_set}} issued after the call is not seen.}

\item{title}{character, title of the graph.}

\item{show.legend}{logical, if TRUE the legend is displayed.}

\item{legend.title}{a character string for the legend title. lower
triangular, upper triangular or full matrix.}

\item{show.diag}{NULL or logical, whether display the correlation
coefficients on the principal diagonal. If \code{NULL}, the default is to
show diagonal correlation for \code{type = "full"} and to remove it when
\code{type} is one of "upper" or "lower".}

\item{colors}{a vector of colors for the fill gradient. The default is a
length-3 vector for the low, mid and high correlation values (mapped with
\code{\link[ggplot2]{scale_fill_gradient2}}). A vector of any other length
(\code{>= 2}) is spread evenly across the scale with
\code{\link[ggplot2]{scale_fill_gradientn}}, so an n-color palette (e.g.
\code{RColorBrewer::brewer.pal(11, "RdBu")}) can be passed directly.}

\item{outline.color}{the outline color of square or circle. Default value is
"gray".}

\item{hc.order}{logical value. If TRUE, correlation matrix will be hc.ordered
using hclust function.}

\item{hc.method}{the agglomeration method to be used in hclust (see ?hclust).}

\item{lab}{logical value. If TRUE, add correlation coefficient on the plot.}

\item{lab_col, lab_size}{size and color to be used for the correlation
coefficient labels. used when lab = TRUE.}

\item{lab_fontface}{the font face (\code{"plain"}, \code{"bold"},
\code{"italic"}, \code{"bold.italic"}) for the correlation coefficient
labels. Default is \code{"plain"}. Used when \code{lab = TRUE}.}

\item{sig.stars}{logical value. If \code{TRUE} and a \code{p.mat} is
supplied, significance stars are appended to the coefficient labels
(\code{***} for p <= 0.001, \code{**} for p <= 0.01, \code{*} for
p <= 0.05), e.g. \code{"-0.85**"}. Only used when \code{lab = TRUE}. Default
is \code{FALSE}. When \code{TRUE}, significance is shown by the stars and
the \code{insig = "pch"} markers are not drawn. These three thresholds are
fixed and are not affected by \code{sig.level}.}

\item{p.mat}{matrix of p-value. If NULL, arguments sig.level, insig, pch,
pch.col, pch.cex is invalid.}

\item{sig.level}{significant level, if the p-value in p-mat is bigger than
sig.level, then the corresponding correlation coefficient is regarded as
insignificant. This governs which cells \code{insig = "pch"} marks and
\code{insig = "blank"} wipes; the star thresholds used by
\code{insig = "stars"} and \code{sig.stars} are fixed (see those arguments)
and do not follow \code{sig.level}.}

\item{insig}{character, how to convey significance from \code{p.mat}: "pch"
(default), "blank" or "stars". "pch" adds a character (see \code{pch}) on the
glyphs of the insignificant cells; "blank" wipes those glyphs away; "stars"
instead marks the SIGNIFICANT cells with significance stars
(\code{***}/\code{**}/\code{*} for p <= 0.001/0.01/0.05 -- fixed thresholds,
not \code{sig.level}). With the default
\code{lab = FALSE} the stars are drawn on their own (in \code{pch.col}, sized
by \code{lab_size}) as a standalone significance map; with \code{lab = TRUE}
they are appended to the coefficient labels (e.g. \code{"-0.85***"}, as with
\code{sig.stars}) so the two do not overprint.}

\item{pch}{add character on the glyphs of insignificant correlation
coefficients (only valid when insig is "pch"). Default value is 4.}

\item{pch.col, pch.cex}{the color and the cex (size) of pch (only valid when
insig is "pch").}

\item{tl.cex, tl.col, tl.srt}{the size, the color and the string rotation of
text label (variable names). \code{tl.col} defaults to \code{NULL}, which
inherits the color from the theme.}

\item{tl.vjust, tl.hjust}{the vertical and horizontal justification of the
x-axis text labels, passed to \code{\link[ggplot2]{element_text}}. Both
default to \code{1}; adjust them to reposition the variable-name labels.}

\item{digits}{Decides the number of decimal digits to be displayed (Default:
`2`).}

\item{as.is}{retained for backward compatibility; no longer affects the plot.
The axis is now always drawn in the matrix (row/column) order, so the
variable-name handling this argument used to control is done internally.}

\item{nsmall}{the minimum number of digits to the right of the decimal point
in the coefficient labels, passed to \code{\link[base]{format}}. Default is
\code{0} (no minimum, current behavior). Set e.g. \code{nsmall = 2} to keep
trailing zeros (such as 0.70). Only used when \code{lab = TRUE}.}

\item{leading.zero}{logical. If \code{TRUE} (default), coefficient labels keep
the leading zero (e.g. \code{0.23}, \code{-0.67}). Set to \code{FALSE} to
drop it (\code{.23}, \code{-.67}), which is common for correlation tables.
Only used when \code{lab = TRUE}.}

\item{legend.limit}{a length-2 numeric vector giving the limits of the fill
color scale. Default \code{c(-1, 1)} (suitable for a correlation matrix); set
to \code{NULL} to use the data range instead, e.g. for a covariance matrix.}

\item{circle.scale}{a scaling factor for the circle sizes when
\code{method = "circle"}. Default is \code{1}; increase it (e.g.
\code{circle.scale = 2}) for larger circles or decrease it for smaller ones,
which is useful when the output device size makes the default circles too
small or too large. Has no effect when \code{method = "square"}.}

\item{coord.fixed}{logical value. If \code{TRUE} (default), the plot uses
\code{\link[ggplot2]{coord_fixed}} so the cells are square. Set to
\code{FALSE} to let the cells fill the plotting area (a non 1:1 aspect
ratio), which can look better with many long variable names.}

\item{lower.method, upper.method}{character, an optional per-triangle glyph for
  a mixed layout: one of "square", "circle" or "number" (the coefficient drawn
  as text, colored by its value on the fill ramp). When either is set, the plot
  switches to a mixed layout where the lower and upper triangles are drawn
  separately and the variable names are drawn on the diagonal; a triangle left
  \code{NULL} uses \code{method}. Both default to \code{NULL} (single-method
  plot, unchanged). In a mixed layout the single-method significance and label
  overlays (\code{lab}, \code{sig.stars}, \code{p.mat}, \code{insig},
  \code{pch*}) do not apply; show coefficients with a "number" triangle instead.

  Over a light background the "number" text is drawn on a darkened copy of the
  ramp -- same hues, so warm still reads as positive and cool as negative, but
  dark enough that a coefficient near zero stays readable instead of washing
  out. Over a dark background the ramp is used as given, its pale middle being
  what reads there. The background is taken from \code{ggtheme}; a theme added
  to the returned plot with \code{+} arrives too late to be seen.}

\item{hc.rect}{integer or \code{NULL} (default). If an integer \code{k}, draws
\code{k} rectangles (no fill) around the clusters obtained by cutting the
hierarchical tree, marking the cluster blocks on the diagonal. Requires
\code{hc.order = TRUE} and \code{type = "full"} (the boxes span whole
diagonal blocks). \code{NULL} (default) draws no rectangles. For a fully
custom box style, add your own \code{annotate("rect", ...)} to the returned
plot.}

\item{palette}{optional name of a built-in colorblind-safe diverging palette
for the fill gradient: \code{"RdBu"} or \code{"PuOr"}. A convenience
shortcut for \code{colors}: when set it supplies the gradient (an 11-stop
ramp, white at zero, cool = negative / warm = positive) and takes precedence
over \code{colors}. Defaults to \code{NULL} (use \code{colors}), so existing
calls are unchanged.}

\item{preset}{optional name of a bundle of publication-grade defaults. The only
value, \code{"publication"}, sets white cell outlines and the colorblind-safe
\code{"RdBu"} palette in one token. It fills only the arguments you did not
supply, so any argument you pass explicitly (e.g. \code{outline.color},
\code{colors}, \code{palette}) overrides the preset. Defaults to \code{NULL}
(no preset), leaving existing calls unchanged.}

\item{hc.rect.col}{the outline color of the \code{hc.rect} cluster rectangles.
Defaults to \code{"gray30"}; set it to any color that suits your palette
(e.g. \code{"black"} for a bolder box, or \code{"white"}). Only used when
\code{hc.rect} is set.}

\item{scale.square}{logical. If \code{TRUE} and \code{method = "square"}, the
squares are sized by the absolute correlation (larger square = stronger
correlation), in addition to the fill color -- the classic corrplot
size-scaled square look. Defaults to \code{FALSE} (constant full-cell
squares, the current behavior). Has no effect for \code{method = "circle"}
(circles are always sized). Uses \code{circle.scale} to tune the size range.
As with \code{method = "circle"}, coefficient labels (\code{lab = TRUE}) are
drawn at full size and may overflow the smallest squares.}

\item{cell.grid}{logical. If \code{TRUE}, draw a light rectangle around every
cell (behind the glyphs) and remove the through-center gridlines, so the
sized glyphs (\code{method = "circle"} or \code{scale.square = TRUE}) sit
inside boxed cells -- the corrplot boxed-cell look. Defaults to \code{FALSE}
(the current behavior). Has no effect on a full-tile square heatmap
(\code{method = "square"} without \code{scale.square}), whose tiles already
carry a cell border (\code{outline.color}).}

\item{cell.grid.col}{the color of the \code{cell.grid} cell borders. Defaults
to \code{"grey90"}. Only used when \code{cell.grid = TRUE}.}

\item{x}{numeric matrix or data frame}

\item{...}{other arguments to be passed to the function cor.test.}

\item{use}{character, how to treat pairs involving missing values when
deciding which cells are \code{NA}. Either \code{"pairwise.complete.obs"}
(default; test every pair that has enough overlapping observations) or
\code{"everything"} (set a pair to \code{NA} as soon as either variable has
a missing value, matching \code{\link[stats]{cor}}'s default). Mirrors the
corresponding values of \code{\link[stats]{cor}}'s \code{use} argument.}
}
\value{
\itemize{ \item ggcorrplot(): Returns a ggplot2 \item cor_pmat():
Returns a matrix containing the p-values of correlations }
}
\description{
\itemize{ \item ggcorrplot(): A graphical display of a
  correlation matrix using ggplot2. The main plot options are walked through in
  \href{https://www.datanovia.com/learn/biostatistics/correlation/ggcorrplot-in-r}{ggcorrplot:
  Correlation Matrix Heatmap in R with ggplot2}. \item cor_pmat(): Compute a
  correlation matrix p-values, to mark the significant cells. A worked
  example is in
  \href{https://www.datanovia.com/learn/biostatistics/correlation/ggcorrplot-in-r}{ggcorrplot:
  Correlation Matrix Heatmap in R with ggplot2}. }
}
\details{
\code{cor_pmat()} tests each pair of columns with
  \code{\link[stats]{cor.test}}. A pair with fewer than three overlapping
  non-missing observations (which \code{\link[stats]{cor.test}} cannot test,
  e.g. two variables that never co-occur) yields \code{NA} for that cell
  rather than aborting the whole computation. Pairs that can be tested are
  computed as before, and errors they raise are passed through.

  The \code{use} argument controls which pairs are returned as \code{NA} so
  the p-value matrix can be aligned with a correlation matrix built the same
  way. With the default \code{"pairwise.complete.obs"} every pair that has
  enough overlapping observations is tested (the previous behavior). With
  \code{"everything"} a pair is set to \code{NA} whenever either variable has
  any missing value, so the \code{NA} pattern matches
  \code{\link[stats]{cor}(x)} with its default \code{use = "everything"}.
}
\examples{
# Compute a correlation matrix
data(mtcars)
corr <- round(cor(mtcars), 1)
corr

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

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

# Mixed layout: a different glyph per triangle
# --------------------------------
# numbers in the lower triangle, circles in the upper, names on the diagonal
ggcorrplot(corr,
  lower.method = "number", upper.method = "circle",
  show.legend = FALSE
)

# Reordering the correlation matrix
# --------------------------------
# using hierarchical clustering
ggcorrplot(corr, hc.order = TRUE, outline.color = "white")
# draw rectangles around the clusters
ggcorrplot(corr, hc.order = TRUE, hc.rect = 3, outline.color = "white")

# Types of correlogram layout
# --------------------------------
# Get the lower triangle
ggcorrplot(corr,
  hc.order = TRUE, type = "lower",
  outline.color = "white"
)
# Get the upeper 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,
  ggtheme = ggplot2::theme_dark(),
)

# 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"
)

# Changing number of digits for correlation coeffcient
# --------------------------------
ggcorrplot(cor(mtcars),
  type = "lower",
  insig = "blank",
  lab = TRUE,
  digits = 3
)
}
\seealso{
\href{https://www.datanovia.com/learn/biostatistics/correlation/ggcorrplot-in-r}{ggcorrplot:
  Correlation Matrix Heatmap in R with ggplot2} for worked examples of the
  plot, and
  \href{https://www.datanovia.com/learn/biostatistics/correlation/correlation-matrix-in-r}{Correlation
  Matrix in R: Compute, Visualize & P-values} for computing the matrix and
  its p-values beforehand.

\href{https://www.datanovia.com/learn/biostatistics/correlation/correlation-test-in-r}{Correlation
  Test in R: Pearson, Spearman & Kendall} for the test behind the p-values.
}
