% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/heatmap.R
\name{Heatmap}
\alias{Heatmap}
\title{Heatmap}
\usage{
Heatmap(
  data,
  values_by = NULL,
  values_fill = NA,
  name = NULL,
  in_form = c("auto", "matrix", "wide-columns", "wide-rows", "long"),
  split_by = NULL,
  split_by_sep = "_",
  rows_by = NULL,
  rows_by_sep = "_",
  rows_split_by = NULL,
  rows_split_by_sep = "_",
  columns_by = NULL,
  columns_by_sep = "_",
  columns_split_by = NULL,
  columns_split_by_sep = "_",
  rows_data = NULL,
  columns_data = NULL,
  keep_na = FALSE,
  keep_empty = FALSE,
  rows_orderby = NULL,
  columns_orderby = NULL,
  columns_name = NULL,
  columns_split_name = NULL,
  rows_name = NULL,
  rows_split_name = NULL,
  palette = "RdBu",
  palcolor = NULL,
  palreverse = FALSE,
  pie_size_name = "size",
  pie_size = NULL,
  pie_values = "length",
  pie_name = NULL,
  pie_group_by = NULL,
  pie_group_by_sep = "_",
  pie_palette = "Spectral",
  pie_palcolor = NULL,
  bars_sample = 1,
  label = identity,
  label_size = 10,
  label_color = "black",
  label_name = "label",
  mark = identity,
  mark_color = "black",
  mark_size = 1,
  mark_name = "mark",
  violin_fill = NULL,
  boxplot_fill = NULL,
  dot_size = 8,
  dot_size_name = "size",
  legend_items = NULL,
  legend_discrete = FALSE,
  legend.position = "right",
  legend.direction = "vertical",
  lower_quantile = 0,
  upper_quantile = 0.99,
  lower_cutoff = NULL,
  upper_cutoff = NULL,
  add_bg = FALSE,
  bg_alpha = 0.5,
  add_reticle = FALSE,
  reticle_color = "grey",
  cluster_columns = NULL,
  cluster_rows = NULL,
  show_row_names = NULL,
  show_column_names = NULL,
  border = TRUE,
  title = NULL,
  column_title = NULL,
  row_title = NULL,
  na_col = "grey85",
  row_names_side = "right",
  column_names_side = "bottom",
  row_annotation = NULL,
  row_annotation_side = NULL,
  row_annotation_palette = NULL,
  row_annotation_palcolor = NULL,
  row_annotation_type = NULL,
  row_annotation_params = NULL,
  row_annotation_agg = NULL,
  column_annotation = NULL,
  column_annotation_side = NULL,
  column_annotation_palette = NULL,
  column_annotation_palcolor = NULL,
  column_annotation_type = NULL,
  column_annotation_params = NULL,
  column_annotation_agg = NULL,
  flip = FALSE,
  alpha = 1,
  seed = 8525,
  padding = 15,
  base_size = 1,
  aspect.ratio = NULL,
  draw_opts = list(),
  layer_fun_callback = NULL,
  cell_type = c("tile", "bars", "label", "mark", "label+mark", "mark+label", "dot",
    "violin", "boxplot", "pie"),
  cell_agg = NULL,
  combine = TRUE,
  nrow = NULL,
  ncol = NULL,
  byrow = TRUE,
  axes = NULL,
  axis_titles = axes,
  guides = NULL,
  design = NULL,
  ...
)
}
\arguments{
\item{data}{A data frame or matrix.  When a matrix, it is melted to
long format internally (requires row and column names).}

\item{values_by}{A character of column name in \code{data} that contains the values to be plotted.
This is required when \code{in_form} is \code{"long"}. For other formats, the values are pivoted into a column named by \code{values_by}.}

\item{values_fill}{A value used to fill missing cells in the matrix.
Default \code{NA}.  Missing values prevent clustering when not filled.}

\item{name}{A character string to name the heatmap (will be used to rename \code{values_by}).}

\item{in_form}{The format of the data. Can be one of \code{"matrix"}, \code{"long"}, \code{"wide-rows"}, \code{"wide-columns"}, or \code{"auto"}.
Defaults to \code{"auto"}.}

\item{split_by}{A character of column name in \code{data} that contains the split information to split into multiple heatmaps.
This is used to create a list of heatmaps, one for each level of the split.
Defaults to \code{NULL}, meaning no split.}

\item{split_by_sep}{A character string to concat multiple columns in \code{split_by}.}

\item{rows_by}{A vector of column names in \code{data} that contains the row information.
This is used to create the rows of the heatmap.
When \code{in_form} is \code{"long"} or \code{"wide-columns"}, this is requied, and multiple columns can be specified,
which will be concatenated by \code{rows_by_sep} into a single column.}

\item{rows_by_sep}{A character string to concat multiple columns in \code{rows_by}.}

\item{rows_split_by}{A character of column name in \code{data} that contains the split information for rows.}

\item{rows_split_by_sep}{A character string to concat multiple columns in \code{rows_split_by}.}

\item{columns_by}{A vector of column names in \code{data} that contains the column information.
This is used to create the columns of the heatmap.
When \code{in_form} is \code{"long"} or \code{"wide-rows"}, this is required, and multiple columns can be specified,
which will be concatenated by \code{columns_by_sep} into a single column.}

\item{columns_by_sep}{A character string to concat multiple columns in \code{columns_by}.}

\item{columns_split_by}{A character of column name in \code{data} that contains the split information for columns.}

\item{columns_split_by_sep}{A character string to concat multiple columns in \code{columns_split_by}.}

\item{rows_data}{A data frame containing additional data for rows, which can be used to add annotations to the heatmap.
It will be joined to the main data by \code{rows_by} and \code{split_by} if \code{split_by} exists in \code{rows_data}.
This is useful for adding additional information to the rows of the heatmap.}

\item{columns_data}{A data frame containing additional data for columns, which can be used to add annotations to the heatmap.
It will be joined to the main data by \code{columns_by} and \code{split_by} if \code{split_by} exists in \code{columns_data}.
This is useful for adding additional information to the columns of the heatmap.}

\item{keep_na}{A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the \code{x}, \code{group_by}, \code{fill_by}, etc.}

\item{keep_empty}{One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the \code{x}, \code{group_by}, \code{fill_by}, etc.
\itemize{
\item{\code{FALSE} (default): Drop empty factor levels from the data before plotting.}
\item{\code{TRUE}: Keep empty factor levels and show them as a separate category in the plot.}
\item{\code{"level"}: Keep empty factor levels, but do not show them in the plot.
But they will be assigned colors from the palette to maintain consistency across multiple plots.
Alias: \code{levels}}
}}

\item{rows_orderby}{A expression (in character) to specify how to order rows. It will be evaluated in the context of the data frame used for rows (after grouping by rows_split_by and rows_by). The expression should return a vector of the same length as the number of rows in the data frame. The default is NULL, which means no specific ordering.
Can't be used with cluster_rows = TRUE.
This is applied before renaming rows_by to rows_name.}

\item{columns_orderby}{A expression (in character) to specify how to order columns. It will be evaluated in the context of the data frame used for columns (after grouping by columns
split_by and columns_by). The expression should return a vector of the same length as the number of rows in the data frame. The default is NULL, which means no specific ordering.
Can't be used with cluster_columns = TRUE.
This is applied before renaming columns_by to columns_name.}

\item{columns_name}{A character string to rename the column created by \code{columns_by}, which will be reflected in the name of the annotation or legend.}

\item{columns_split_name}{A character string to rename the column created by \code{columns_split_by}, which will be reflected in the name of the annotation or legend.}

\item{rows_name}{A character string to rename the column created by \code{rows_by}, which will be reflected in the name of the annotation or legend.}

\item{rows_split_name}{A character string to rename the column created by \code{rows_split_by}, which will be reflected in the name of the annotation or legend.}

\item{palette}{A character string naming a palette (see
\code{\link{show_palettes}}) or a character vector of colours for the
main heatmap colour scale.  Default \code{"RdBu"}.}

\item{palcolor}{A custom colour vector overriding \code{palette}.}

\item{palreverse}{A logical value indicating whether to reverse the palette. Default is FALSE.}

\item{pie_size_name}{Legend title for the pie size.}

\item{pie_size}{A numeric value or function returning the pie radius.
When a function, it receives the count of groups in the pie.}

\item{pie_values}{A function or string (convertible via
\code{\link[base]{match.arg}}) to compute the value represented by
each pie slice.  Default \code{"length"} counts observations per
group.}

\item{pie_name}{A character string to rename the column created by \code{pie_group_by}, which will be reflected in the name of the annotation or legend.}

\item{pie_group_by}{A character of column name in \code{data} that contains the group information for pie charts.
This is used to create pie charts in the heatmap when \code{cell_type} is \code{"pie"}.}

\item{pie_group_by_sep}{A character string to concat multiple columns in \code{pie_group_by}.}

\item{pie_palette, pie_palcolor}{Palette and custom colours for pie slice
fill colours.}

\item{bars_sample}{Fraction of each cell's observations (0 < x <= 1;
\code{1} uses all data) or a whole count > 1 sampled per cell when
\code{cell_type = "bars"}.  Column widths are proportional to the
number of bars drawn per column, so a numeric count gives equal
column widths and a fraction gives widths proportional to the
column data sizes.  Proportional widths are skipped when
\code{columns_split_by} is given, and column clustering is
disabled in proportional mode.  Default 1 (all data).}

\item{label}{A function to compute text labels when
\code{cell_type = "label"} (or \code{"label+mark"}).  Receives the
aggregated value for a cell and optionally row/column indices and
names.  See below for the full dispatch contract.}

\item{label_size}{Default point size for label text (used as fallback
when the \code{label} function does not return a \code{size} field).}

\item{label_color}{Default colour for label text (fallback).}

\item{label_name}{Legend title for the label colour scale.  The legend
is shown automatically when the \code{label} function returns a
\code{legend} field for at least one cell.}

\item{mark}{A function to compute mark symbols when
\code{cell_type = "mark"} (or \code{"label+mark"}).  Same dispatch
contract as \code{label}.}

\item{mark_color}{Default mark colour (fallback).}

\item{mark_size}{Default mark stroke width (\code{lwd}) in pt (fallback).}

\item{mark_name}{Legend title for the mark colour scale.}

\item{violin_fill}{A character vector of colours to use as fill for
violin plots when \code{cell_type = "violin"}.  If \code{NULL}, the
annotation colour is used.}

\item{boxplot_fill}{A character vector of colours to use as fill for
boxplots when \code{cell_type = "boxplot"}.  If \code{NULL}, the
annotation colour is used.}

\item{dot_size}{Dot size when \code{cell_type = "dot"}.  Can be a
numeric value or a function.}

\item{dot_size_name}{Legend title for the dot size.}

\item{legend_items}{A named numeric vector specifying custom legend
entries for the main colour scale.  Names become the displayed labels.}

\item{legend_discrete}{Logical; if \code{TRUE}, treat the main colour
scale as discrete.}

\item{legend.position}{A character string specifying the position of the legend.
if \code{waiver()}, for single groups, the legend will be "none", otherwise "right".}

\item{legend.direction}{A character string specifying the direction of the legend.}

\item{lower_quantile, upper_quantile, lower_cutoff, upper_cutoff}{Quantile or explicit cutoffs for clipping the colour scale.  Applied
to aggregated values for \code{tile} / \code{label} cell types; applied
to raw values for \code{bars} / \code{violin} / \code{boxplot} types.}

\item{add_bg}{Logical; if \code{TRUE}, add a background fill behind
non-tile cell types.  Not used for \code{cell_type = "tile"} or
\code{"bars"}.}

\item{bg_alpha}{Numeric in \eqn{[0, 1]} for background transparency.}

\item{add_reticle}{Logical; if \code{TRUE}, draw a reticle (crosshair
pattern) over the heatmap.}

\item{reticle_color}{Colour for the reticle lines.}

\item{cluster_columns}{Logical; cluster the columns.  If \code{TRUE} and
\code{columns_split_by} is provided, clustering is applied within each
split group.}

\item{cluster_rows}{Logical; cluster the rows.  If \code{TRUE} and
\code{rows_split_by} is provided, clustering is applied within each
split group.}

\item{show_row_names}{Logical or character vector; show row names.  If
\code{TRUE}, the legend of the row group annotation is hidden.
\code{FALSE} only hides the in-place names.  Alternatively, a character
vector combining the display modes \code{"inplace"} (in-place names,
same as \code{TRUE}), \code{"legend"} (row group annotation with
legend), \code{"simple"} (row group annotation without legend),
\code{"anno"} (alias \code{"annotation"}; label annotation showing the
row names as text) and \code{"none"} (no names, annotation, or legend).
Modes are lower-priority defaults: explicit \code{row_annotation}
entries (e.g. \code{.row}) still win.}

\item{show_column_names}{Logical or character vector; show column names.
See \code{show_row_names} for the display modes.}

\item{border}{A logical value indicating whether to draw borders around
the heatmap.  If \code{TRUE}, slice borders are also drawn.  Default
\code{TRUE}.}

\item{title}{The global (column) title of the heatmap.}

\item{column_title}{Character string/vector used as the column group
annotation title.  A character vector consisting entirely of the display
modes \code{"inplace"} (per-slice split titles), \code{"legend"} (split
annotation with legend, no title), \code{"simple"} (split annotation,
no legend/title), \code{"anno"} (alias \code{"annotation"}; label block
annotation) and \code{"none"} (no title, annotation, or legend)
controls how the split titles are displayed.  A literal title identical
to a mode keyword is interpreted as a mode.}

\item{row_title}{Character string/vector used as the row group
annotation title.  See \code{column_title} for the display modes.}

\item{na_col}{Colour for \code{NA} cells.  Default \code{"grey85"}.}

\item{row_names_side}{Side for row names.  Default \code{"right"}.}

\item{column_names_side}{Side for column names.  Default \code{"bottom"}.}

\item{row_annotation}{A structured list specifying row annotations.
Same format as \code{column_annotation}.  Sides default to
\code{"left"}.  Aliases: \code{.row}/\code{.rows} for
\code{rows_by}, \code{.row.split}/\code{.rows.split} for
\code{rows_split_by}.}

\item{row_annotation_side}{\strong{Deprecated}: use
\code{row_annotation} with the \code{side} sub-key instead.}

\item{row_annotation_palette}{\strong{Deprecated}: use
\code{row_annotation} with the \code{palette} sub-key instead.}

\item{row_annotation_palcolor}{\strong{Deprecated}: use
\code{row_annotation} with the \code{palcolor} sub-key instead.}

\item{row_annotation_type}{\strong{Deprecated}: use
\code{row_annotation} with the \code{type} sub-key instead.}

\item{row_annotation_params}{\strong{Deprecated}: use
\code{row_annotation} with the \code{params} sub-key instead.}

\item{row_annotation_agg}{\strong{Deprecated}: use
\code{row_annotation} with the \code{agg} sub-key instead.}

\item{column_annotation}{A structured list specifying column annotations.
Each entry is a named list with sub-keys:
\describe{
\item{\code{col}}{Column name in \code{data} supplying the annotation
values.  If omitted, the entry name is used as the column name.}
\item{\code{side}}{\code{"top"} or \code{"bottom"}.}
\item{\code{palette}}{Palette name (see \code{\link{show_palettes}}).}
\item{\code{palcolor}}{Custom colour vector overriding \code{palette}.}
\item{\code{type}}{Annotation type: \code{"auto"}, \code{"simple"},
\code{"pie"}, \code{"ring"}, \code{"bar"}, \code{"violin"},
\code{"boxplot"}, \code{"density"}, \code{"label"},
\code{"rownames"}, \code{"points"}, \code{"lines"}.
For split annotations, \code{"rownames"} (row splits) /
\code{"colnames"} (column splits) is like \code{"label"} but labels
each split block with the concatenated row/column names;
\code{"names"} and \code{"dimnames"} are aliases.
\code{params$sep} (default \code{" "}) controls the separator and
\code{params$wrap_by} the number of names per line.
For name annotations (the built-in \code{rows_by}/\code{columns_by}
annotation), \code{"rownames"}/\code{"colnames"} renders the
row/column names as text labels (this is what
\code{show_row_names = "anno"} uses).}
\item{\code{params}}{A list of additional parameters passed to the
annotation constructor.  \code{FALSE} disables the annotation.
\code{$show_legend} controls legend visibility.  See
\code{\link[ComplexHeatmap]{HeatmapAnnotation}}.}
\item{\code{agg}}{A function to aggregate values for the annotation.}
\item{\code{name}}{Display name for the annotation, shown next to the
annotation bar and used as the legend title.  \code{FALSE} hides the
displayed name.  Defaults to the annotation key (column name).}
}
\strong{Shortcuts:}
\itemize{
\item \code{column_annotation = list(Score = "score")} is short for
\code{list(Score = list(col = "score"))}.
\item \code{column_annotation = TRUE} enables annotations with
defaults.  \code{FALSE} disables all column annotations.
}
\strong{Special keys:}
\itemize{
\item \code{.default} — default values inherited by all entries.
\code{params} is merged recursively; other keys are inherited
only when the entry does not already specify them.
\item \code{.col} / \code{.cols} / \code{.column} / \code{.columns} —
alias for \code{columns_by} (the built-in name annotation).
\item \code{.col.split} / \code{.cols.split} / \code{.column.split} /
\code{.columns.split} — alias for \code{columns_split_by}
(the built-in split annotation).
\item \code{.row} / \code{.rows} — alias for \code{rows_by}.
\item \code{.row.split} / \code{.rows.split} — alias for
\code{rows_split_by}.
}}

\item{column_annotation_side}{\strong{Deprecated}: use
\code{column_annotation} with the \code{side} sub-key instead.}

\item{column_annotation_palette}{\strong{Deprecated}: use
\code{column_annotation} with the \code{palette} sub-key instead.}

\item{column_annotation_palcolor}{\strong{Deprecated}: use
\code{column_annotation} with the \code{palcolor} sub-key instead.}

\item{column_annotation_type}{\strong{Deprecated}: use
\code{column_annotation} with the \code{type} sub-key instead.}

\item{column_annotation_params}{\strong{Deprecated}: use
\code{column_annotation} with the \code{params} sub-key instead.}

\item{column_annotation_agg}{\strong{Deprecated}: use
\code{column_annotation} with the \code{agg} sub-key instead.}

\item{flip}{Logical; if \code{TRUE}, swap rows and columns
transparently.  The caller does not need to swap row- and
column-related arguments manually.}

\item{alpha}{Alpha transparency for heatmap cells in \eqn{[0, 1]}.}

\item{seed}{The random seed to use. Default is 8525.}

\item{padding}{Padding around the heatmap in CSS order (top, right,
bottom, left).  Supports 1–4 values.  Default 15 (mm).  Note that
this is different from \code{ComplexHeatmap::draw()}'s \code{padding}
argument which uses bottom-left-top-right order.}

\item{base_size}{A positive numeric scalar used as a scaling factor for
the overall heatmap size.  Default 1 (no scaling).  Values > 1 enlarge
all cell dimensions proportionally.}

\item{aspect.ratio}{Height-to-width ratio of a single heatmap cell.
When \code{NULL} (default), sensible per-\code{cell_type} defaults are
used: 1 for \code{tile}/\code{label}/\code{dot}, 0.5 for \code{bars},
and 2 for \code{violin}/\code{boxplot}/\code{pie}.  The ratio is
constrained by the overall plot dimensions.}

\item{draw_opts}{A named list of additional arguments passed to
\code{\link[ComplexHeatmap]{draw,HeatmapList-method}}.  Internally
managed arguments take precedence.}

\item{layer_fun_callback}{A function to add custom graphical layers on
top of each heatmap cell.  Receives \code{j}, \code{i}, \code{x},
\code{y}, \code{w}, \code{h}, \code{fill}, \code{sr}, \code{sc}.
See \code{\link[ComplexHeatmap]{Heatmap}} for details.}

\item{cell_type}{The type of cell to render.  One of \code{"tile"}
(default), \code{"bars"}, \code{"label"}, \code{"mark"},
\code{"label+mark"} (or \code{"mark+label"}), \code{"dot"},
\code{"violin"}, \code{"boxplot"}, \code{"pie"}.  See the
\strong{Cell types} section for details.}

\item{cell_agg}{A function to aggregate values within each cell when
\code{cell_type = "tile"} or \code{"label"}.  Default is
\code{\link[base]{mean}}.}

\item{combine}{Whether to combine the plots into one when facet is FALSE. Default is TRUE.}

\item{nrow}{A numeric value specifying the number of rows in the facet.}

\item{ncol}{A numeric value specifying the number of columns in the facet.}

\item{byrow}{A logical value indicating whether to fill the plots by row.}

\item{axes}{A string specifying how axes should be treated. Passed to \code{\link[patchwork:wrap_plots]{patchwork::wrap_plots()}}.
Only relevant when \code{split_by} is used and \code{combine} is TRUE.
Options are:
\itemize{
\item 'keep' will retain all axes in individual plots.
\item 'collect' will remove duplicated axes when placed in the same run of rows or columns of the layout.
\item 'collect_x' and 'collect_y' will remove duplicated x-axes in the columns or duplicated y-axes in the rows respectively.
}}

\item{axis_titles}{A string specifying how axis titltes should be treated. Passed to \code{\link[patchwork:wrap_plots]{patchwork::wrap_plots()}}.
Only relevant when \code{split_by} is used and \code{combine} is TRUE.
Options are:
\itemize{
\item 'keep' will retain all axis titles in individual plots.
\item 'collect' will remove duplicated titles in one direction and merge titles in the opposite direction.
\item 'collect_x' and 'collect_y' control this for x-axis titles and y-axis titles respectively.
}}

\item{guides}{A string specifying how guides should be treated in the layout. Passed to \code{\link[patchwork:wrap_plots]{patchwork::wrap_plots()}}.
Only relevant when \code{split_by} is used and \code{combine} is TRUE.
Options are:
\itemize{
\item 'collect' will collect guides below to the given nesting level, removing duplicates.
\item 'keep' will stop collection at this level and let guides be placed alongside their plot.
\item 'auto' will allow guides to be collected if a upper level tries, but place them alongside the plot if not.
}}

\item{design}{Specification of the location of areas in the layout, passed to \code{\link[patchwork:wrap_plots]{patchwork::wrap_plots()}}.
Only relevant when \code{split_by} is used and \code{combine} is TRUE. When specified, \code{nrow}, \code{ncol}, and \code{byrow} are ignored.
See \code{\link[patchwork:wrap_plots]{patchwork::wrap_plots()}} for more details.}

\item{...}{Additional arguments passed to
\code{\link{HeatmapAtomic}}, which in turn forwards them to
\code{\link[ComplexHeatmap]{Heatmap}}.}
}
\value{
A \code{patchwork} object (class \code{wrap_plots}) with
\code{height} and \code{width} attributes (in inches).  When
\code{combine = FALSE}, a named list of such objects, one per
\code{split_by} level.
}
\description{
Draw a heatmap to visualise data in matrix form.  This is the public,
exported interface — it accepts data in multiple input formats (matrix,
wide, or long), preprocesses it via \code{\link{process_heatmap_data}},
and delegates to \code{\link{HeatmapAtomic}} for rendering.  Commonly
used in biology to visualise gene expression, but applicable to any
matrix-structured data.
}
\section{Input formats}{

The \code{in_form} parameter controls how the input \code{data} is
interpreted:
\itemize{
\item \code{"auto"} (default) — detects the format automatically.
\item \code{"matrix"} — \code{data} is a matrix with row and column
names.  It is melted to long form internally.
\item \code{"wide-rows"} — each row is a feature, columns are samples.
\item \code{"wide-columns"} — each column is a feature, rows are
samples.
\item \code{"long"} — tidy/long format with one observation per row.
}
}

\section{Split-by support}{

When \code{split_by} is provided, the data is partitioned into subsets
and an independent heatmap is produced for each level.  Results are
combined via \code{\link[patchwork]{wrap_plots}} according to
\code{nrow}, \code{ncol}, \code{byrow}, and \code{design}.  Per-split
\code{palette}, \code{palcolor}, \code{legend.position}, and
\code{legend.direction} can be specified as named lists keyed by split
level.
}

\examples{
\donttest{
set.seed(8525)

matrix_data <- matrix(rnorm(60), nrow = 6, ncol = 10)
rownames(matrix_data) <- paste0("R", 1:6)
colnames(matrix_data) <- paste0("C", 1:10)
if (requireNamespace("cluster", quietly = TRUE)) {
    Heatmap(matrix_data)
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # use a different color palette
    # change the main legend title
    # show row names (legend will be hidden)
    # show column names
    # change the row name annotation name and side
    # change the column name annotation name
    Heatmap(matrix_data, palette = "viridis", values_by = "z-score",
       show_row_names = TRUE, show_column_names = TRUE,
       rows_name = "Features", row_names_side = "left",
       columns_name = "Samples")
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # flip the heatmap
    Heatmap(matrix_data, palette = "viridis", values_by = "z-score",
       show_row_names = TRUE, show_column_names = TRUE,
       rows_name = "Features", row_names_side = "left",
       columns_name = "Samples", flip = TRUE)
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # add annotations to the heatmap
    rows_data <- data.frame(
       rows = paste0("R", 1:6),
       group = sample(c("X", "Y", "Z"), 6, replace = TRUE)
    )
    Heatmap(matrix_data, rows_data = rows_data,
        row_annotation = list(Group = list(col = "group", palette = "Spectral"))
    )
}
if (requireNamespace("cluster", quietly = TRUE)) {
    Heatmap(matrix_data, rows_data = rows_data,
        rows_split_by = "group"
    )
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # use label annotation for split groups (shows group labels inside colored blocks)
    Heatmap(matrix_data, rows_data = rows_data,
        rows_split_by = "group",
        row_annotation = list(.row.split = list(
            type = "label",
            params = list(
                border = FALSE,
                labels_gp = grid::gpar(col = "white", fontsize = 12),
                labels_rot = 0
            )
        ))
    )
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # label annotation for column splits
    columns_data <- data.frame(
        columns = paste0("C", 1:10),
        batch = rep(c("A", "B"), each = 5)
    )
    Heatmap(matrix_data, columns_data = columns_data,
        columns_split_by = "batch",
        column_annotation = list(.col.split = list(type = "label"))
    )
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # "rownames" annotation for row splits: show the concatenated row names
    # of each split group, wrapped every 3 names (row names and the split
    # title are hidden/shown by default accordingly)
    Heatmap(matrix_data, rows_data = rows_data,
        rows_split_by = "group",
        row_annotation = list(.row.split = list(
            type = "rownames",
            params = list(sep = ", ", wrap_by = 3)
        ))
    )
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # same for column splits with type = "colnames"
    Heatmap(matrix_data, columns_data = columns_data,
        columns_split_by = "batch",
        column_annotation = list(.col.split = list(
            type = "colnames",
            params = list(wrap_by = 3)
        ))
    )
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # split title modes: per-slice titles plus the split annotation
    # legend; and "anno" mode using label blocks instead of titles
    Heatmap(matrix_data, rows_data = rows_data,
        rows_split_by = "group",
        row_title = c("inplace", "legend")
    )
}
if (requireNamespace("cluster", quietly = TRUE)) {
    Heatmap(matrix_data, rows_data = rows_data,
        rows_split_by = "group",
        row_title = "anno"
    )
}
rownames(matrix_data)[1] <- "R12345"
if (requireNamespace("cluster", quietly = TRUE)) {
    # label annotation for name annotations: show row/column names as colored labels
    Heatmap(matrix_data, rows_data = rows_data,
        row_annotation = list(.row = list(
            type = "label", palette = "Set2", side = "right",
            params = list(labels_rot = 150)
        )),
        column_annotation = list(.col = list(
            type = "label", params = list(labels_rot = 90)
        ))
    )
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # add labels to the heatmap
    Heatmap(matrix_data, rows_data = rows_data,
        rows_split_by = "group", cell_type = "label",
        base_size = 0.8,
        label = function(x) ifelse(
            x > 0, scales::number(x, accuracy = 0.01), NA
        )
    )
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # add labels based on an external data
    pvalues <- matrix(runif(60, 0, 0.5), nrow = 6, ncol = 10)
    Heatmap(matrix_data, rows_data = rows_data,
        rows_split_by = "group", cell_type = "label",
        base_size = 0.8,
        label = function(x, i, j) {
            pv <- ComplexHeatmap::pindex(pvalues, i, j)
            ifelse(pv < 0.01, "***",
            ifelse(pv < 0.05, "**",
            ifelse(pv < 0.1, "*", NA)))
        }
    )
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # Set label color, size, legend and order
    pvalues <- matrix(runif(60, 0, 0.5), nrow = 6, ncol = 10)
    Heatmap(matrix_data, rows_data = rows_data,
        rows_split_by = "group", cell_type = "label",
        base_size = 0.6,
        label_name = "Significance",
        label = function(x, i, j) {
            pv <- ComplexHeatmap::pindex(pvalues, i, j)
            if (pv < 0.01)
               list("***", color = "red", size = 12, legend = "p < 0.01", order = 1)
            else if (pv < 0.05)
               list("**", color = "orange", size = 10, legend = "p < 0.05", order = 3)
            else if (pv < 0.1)
               list("*", color = "yellow", size = 8, legend = "p < 0.1", order = 2)
            else NA
        }
    )
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # add marks
    Heatmap(matrix_data, rows_data = rows_data,
        rows_split_by = "group", cell_type = "mark",
        mark = function(x, i, j) {
            pv <- ComplexHeatmap::pindex(pvalues, i, j)
            if(pv < 0.01) list("[x]", legend = "p < 0.01")
            else if (pv < 0.02) list("[o]", legend = "p < 0.02")
            else if (pv < 0.03) list("[-]", legend = "p < 0.03")
            else if (pv < 0.05) list("[()]", legend = "p < 0.05")
            else if (pv < 0.06) list("+", legend = "p < 0.06")
            else if (pv < 0.07) list("x", legend = "p < 0.07")
            else if (pv < 0.08) list("[/]", legend = "p < 0.08")
            else if (pv < 0.09) list("[\\\\]", legend = "p < 0.09")
            else NA
        }
    )
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # add labels and marks
    Heatmap(matrix_data, rows_data = rows_data,
        rows_split_by = "group", cell_type = "mark+label",
        label = scales::label_number(accuracy = 0.01),
        mark = function(x, i, j) {
            pv <- ComplexHeatmap::pindex(pvalues, i, j)
            if(pv < 0.01) list("{}", legend = "p < 0.01")
            else if(pv < 0.05) list("[]", legend = "p < 0.05")
            else NA
        },
        mark_size = 1.5, mark_color = "red"
    )
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # quickly simulate a GO board
    go <- matrix(sample(c(0, 1, NA), 81, replace = TRUE), ncol = 9)

    Heatmap(
        go,
        # Do not cluster rows and columns and hide the name annotations
        # Use .row/.col aliases to disable the built-in name annotations
        cluster_rows = FALSE, cluster_columns = FALSE,
        row_annotation = list(.row = list(params = FALSE)),
        column_annotation = list(.col = list(params = FALSE)),
        show_row_names = FALSE, show_column_names = FALSE,
        # Set the legend items
        values_by = "Players", legend_discrete = TRUE,
        legend_items = c("Player 1" = 0, "Player 2" = 1),
        # Set the pawns
        cell_type = "dot", dot_size = function(x) ifelse(is.na(x), 0, 10),
        dot_size_name = NULL,  # hide the dot size legend
        palcolor = c("white", "black"),
        # Set the board
        add_reticle = TRUE,
        # Set the size of the board
        width = ggplot2::unit(105, "mm"), height = ggplot2::unit(105, "mm"))
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # Make the row/column name annotation thicker using the .row/.col aliases
    Heatmap(matrix_data,
        column_annotation = list(.col = list(params = list(height = 5))),
        row_annotation = list(.row = list(params = list(width = 5))))
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # Per-annotation side control: row name annotation on the right,
    # all other row annotations on the left (.default)
    rows_data2 <- data.frame(
        rows = sample(paste0("R", 1:6), 60, replace = TRUE),
        group = sample(c("X", "Y"), 60, replace = TRUE),
        score = runif(60)
    )
    Heatmap(matrix_data, rows_data = rows_data2,
        rows_split_by = "group",
        row_annotation = list(
            .default = list(side = "left"),
            .row = list(side = "right"),
            Score = "score"
        ),
        show_row_names = TRUE
    )
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # Move all row annotations to the right side
    Heatmap(matrix_data, rows_data = rows_data2,
        rows_split_by = "group",
        row_annotation = list(
            .default = list(side = "right"),
            Score = "score"
        ),
        show_row_names = TRUE
    )
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # Split and name annotations on opposite sides:
    # split annotation on the default left, name annotation on the right
    Heatmap(matrix_data, rows_data = rows_data2,
        rows_split_by = "group",
        row_annotation = list(
            .default = list(side = "left"),
            .row = list(side = "right")
        ),
        show_row_names = TRUE
    )
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # Row name label annotation on the right side (text rotated 90° clockwise)
    Heatmap(matrix_data, rows_data = rows_data2,
        row_annotation = list(.row = list(
            type = "label", palette = "Set2", side = "right"
        )),
        show_row_names = TRUE
    )
}

# Use long form data
N <- 500
data <- data.frame(
    value = rnorm(N),
    c = sample(letters[1:8], N, replace = TRUE),
    r = sample(LETTERS[1:5], N, replace = TRUE),
    p = sample(c("x", "y"), N, replace = TRUE),
    q = sample(c("X", "Y", "Z"), N, replace = TRUE),
    a = as.character(sample(1:5, N, replace = TRUE)),
    p1 = runif(N),
    p2 = runif(N)
)

if (requireNamespace("cluster", quietly = TRUE)) {
    Heatmap(data, rows_by = "r", columns_by = "c", values_by = "value",
        rows_split_by = "p", columns_split_by = "q", show_column_names = TRUE)
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # display modes: in-place row names plus the row group annotation
    # legend; and "anno" mode showing the column names as text labels
    Heatmap(data, rows_by = "r", columns_by = "c", values_by = "value",
        show_row_names = c("inplace", "legend"),
        show_column_names = "anno"
    )
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # split into multiple heatmaps
    Heatmap(data,
        values_by = "value", columns_by = "c", rows_by = "r", split_by = "p",
        upper_cutoff = 2, lower_cutoff = -2, legend.position = c("none", "right"),
        design = "AAAAAA#BBBBBBB"
    )
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # cell_type = "bars" (default is "tile")
    Heatmap(data, values_by = "value", rows_by = "r", columns_by = "c",
        cell_type = "bars")
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # column widths are proportional to the number of bars per column
    # (columns c1 and c2 have 10 and 4 data points)
    bars_data <- data.frame(
        value = rnorm(14),
        r = c(rep("r1", 8), rep("r2", 6)),
        c = c(rep("c1", 6), rep("c2", 2), rep("c1", 4), rep("c2", 2))
    )
    Heatmap(bars_data, values_by = "value", rows_by = "r", columns_by = "c",
        cell_type = "bars")
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # a fraction uses that fraction of each cell's data
    Heatmap(bars_data, values_by = "value", rows_by = "r", columns_by = "c",
        cell_type = "bars", bars_sample = 0.5)
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # a whole count samples that many per cell -> equal column widths
    Heatmap(bars_data, values_by = "value", rows_by = "r", columns_by = "c",
        cell_type = "bars", bars_sample = 3)
}
if (requireNamespace("cluster", quietly = TRUE)) {
    p <- Heatmap(data, values_by = "value", rows_by = "r", columns_by = "c",
        cell_type = "dot", dot_size = length, dot_size_name = "data points",
        add_bg = TRUE, add_reticle = TRUE)
    p
}
if (requireNamespace("cluster", quietly = TRUE)) {
    dot_size_data <- as.matrix(p$data)
    # Make it big so we can see if we get the right indexing
    # for dot_size function
    dot_size_data["A", "a"] <- max(dot_size_data) * 2

    Heatmap(data, values_by = "value", rows_by = "r", columns_by = "c",
        cell_type = "dot", dot_size_name = "data points",
        dot_size = function(x, i, j) ComplexHeatmap::pindex(dot_size_data, i, j),
        show_row_names = TRUE, show_column_names = TRUE,
        add_bg = TRUE, add_reticle = TRUE)
}
if (requireNamespace("cluster", quietly = TRUE)) {
    Heatmap(data, values_by = "value", rows_by = "r", columns_by = "c",
        cell_type = "pie", pie_group_by = "q", pie_size = sqrt,
        add_bg = TRUE, add_reticle = TRUE)
}
if (requireNamespace("cluster", quietly = TRUE)) {
    Heatmap(data, values_by = "value", rows_by = "r", columns_by = "c",
        cell_type = "violin", add_bg = TRUE, add_reticle = TRUE)
}
if (requireNamespace("cluster", quietly = TRUE)) {
    Heatmap(data, values_by = "value", rows_by = "r", columns_by = "c",
        cell_type = "boxplot", add_bg = TRUE, add_reticle = TRUE)
}
if (requireNamespace("cluster", quietly = TRUE)) {
    Heatmap(data,
        values_by = "value", rows_by = "r", columns_by = "c",
        column_annotation = list(
            r1 = list(col = "p", type = "ring",
                      params = list(height = grid::unit(10, "mm"), show_legend = FALSE)),
            r2 = list(col = "q", type = "bar"),
            r3 = list(col = "p1", type = "violin",
                      params = list(height = grid::unit(18, "mm")))
        ),
        row_annotation = list(
            .default = list(side = "right"),
            q = list(type = "pie", params = list(width = grid::unit(12, "mm"))),
            p2 = list(type = "density"),
            a = list(type = "simple")
        ),
        show_row_names = TRUE, show_column_names = TRUE
    )
}
if (requireNamespace("cluster", quietly = TRUE)) {
    Heatmap(data,
        values_by = "value", rows_by = "r", columns_by = "c",
        split_by = "p", palette = list(x = "Reds", y = "Blues")
    )
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # implies in_form = "wide-rows"
    Heatmap(data, rows_by = c("p1", "p2"), columns_by = "c")
}
if (requireNamespace("cluster", quietly = TRUE)) {
    # implies wide-columns
    Heatmap(data, rows_by = "r", columns_by = c("p1", "p2"))
}
}
}
\seealso{
\code{\link{HeatmapAtomic}}, \code{\link{LinkedHeatmap}},
\code{\link{anno_simple}}, \code{\link{anno_points}},
\code{\link{anno_lines}}, \code{\link{anno_pie}},
\code{\link{anno_violin}}, \code{\link{anno_boxplot}},
\code{\link{anno_density}}
}
