Package 'HeatmapR'

Title: Create Heatmaps Using Base Graphics
Description: Provides a lightweight framework for creating high quality, complex heatmaps using base graphics. Supports hierarchical clustering with dendrograms, column and row scaling, cluster sub-divisions, customisable cell colours, shapes and sizes, legends, and flexible layouts for arranging multiple heatmaps. Designed to return plot objects that can be easily arranged with other plots without sacrificing resolution. Methods for hierarchical clustering and distance computations are described in Murtagh and Contreras (2012) <doi:10.1002/widm.53>; linkage uses the nearest-neighbour chain algorithm, a minimum spanning tree for single linkage and the generic algorithm of Mullner (2011) <doi:10.48550/arXiv.1109.2378> for centroid and median linkage, leaves are ordered optimally as in Bar-Joseph, Gifford and Jaakkola (2001) <doi:10.1093/bioinformatics/17.suppl_1.S22>, Kendall correlations are computed by Knight's (1966) algorithm <doi:10.1080/01621459.1966.10480879>, k-means by Hartigan and Wong (1979) <doi:10.2307/2346830>, also from the k-means++ starts of Arthur and Vassilvitskii (2007), and the dip statistic of unimodality, which flags groups of cells that may be two populations, by Hartigan and Hartigan (1985) <doi:10.1214/aos/1176346577>, all in compiled code.
Authors: Dillon Hammill [aut, cre, cph] (ORCID: <https://orcid.org/0000-0002-1407-7223>)
Maintainer: Dillon Hammill <[email protected]>
License: MIT + file LICENSE
Version: 2.0.0
Built: 2026-11-13 02:58:06 UTC
Source: https://github.com/dillonhammill/heatmapr

Help Index


Create a complex heatmap using base graphics

Description

Create a complex heatmap using base graphics

Usage

heat_map(
  x,
  scale = FALSE,
  scale_method = "range",
  dist_method = "euclidean",
  clust_method = "complete",
  clust_max = 5000,
  round = 2,
  tree = FALSE,
  tree_x = NULL,
  tree_size_x = 1,
  tree_col_x = NULL,
  tree_scale_x = FALSE,
  tree_order_x = "default",
  tree_support_x = NULL,
  tree_cut_x = NULL,
  tree_kmeans_x = NULL,
  tree_split_x = 1,
  tree_label_x = FALSE,
  tree_label_size_x = 0.1,
  tree_label_col_x = "grey85",
  tree_label_col_alpha_x = 1,
  tree_label_text_x = NA,
  tree_label_text_font_x = 1,
  tree_label_text_size_x = 1,
  tree_label_text_col_x = "auto",
  tree_label_text_col_alpha_x = 1,
  tree_y = NULL,
  tree_size_y = 1,
  tree_col_y = NULL,
  tree_scale_y = FALSE,
  tree_order_y = "default",
  tree_support_y = NULL,
  tree_support_labels = TRUE,
  tree_cut_y = NULL,
  tree_kmeans_y = NULL,
  tree_split_y = 1,
  tree_label_y = FALSE,
  tree_label_size_y = 0.1,
  tree_label_col_y = "grey85",
  tree_label_col_alpha_y = 1,
  tree_label_text_y = NA,
  tree_label_text_font_y = 1,
  tree_label_text_size_y = 1,
  tree_label_text_col_y = "auto",
  tree_label_text_col_alpha_y = 1,
  cell_shape = "rect",
  cell_size = FALSE,
  cell_col_palette = c("red", "blue", "green", "orange", "magenta", "purple"),
  cell_col_scale,
  cell_col_scale_limits = NULL,
  cell_col_scale_center = NULL,
  cell_col_scale_breaks = NULL,
  cell_col_blocks_x = NULL,
  cell_col_blocks_y = NULL,
  cell_size_scale_limits = NULL,
  cell_size_scale_method = "linear",
  cell_size_scale_range = c(0, 1),
  cell_col_alpha = 1,
  cell_uncertainty = NULL,
  cell_uncertainty_breaks = NULL,
  cell_uncertainty_title = "Uncertainty",
  cell_split = NULL,
  cell_split_labels = c("x", "cell_split"),
  cell_split_size = NULL,
  cell_col_empty = "white",
  cell_border_line_type = 1,
  cell_border_line_width = 1,
  cell_border_line_col = "black",
  cell_border_line_col_alpha = 1,
  cell_grid_line_col = NA,
  cell_border_mask = NULL,
  cell_text = FALSE,
  cell_text_font = 1,
  cell_text_size = 1,
  cell_text_col = "white",
  cell_text_col_alpha = 1,
  bar_size_x = 1,
  bar_values_x = NULL,
  bar_type_x = NULL,
  bar_axis_label_x = NULL,
  bar_axis_label_adj_x = 0,
  bar_axis_label_font_x = 1,
  bar_axis_label_size_x = 1,
  bar_axis_label_col_x = "black",
  bar_axis_label_col_alpha_x = 1,
  bar_fill_x = "grey40",
  bar_fill_alpha_x = 1,
  bar_line_type_x = 1,
  bar_line_width_x = 1,
  bar_line_col_x = "black",
  bar_line_col_alpha_x = 1,
  bar_size_y = 1,
  bar_values_y = NULL,
  bar_type_y = NULL,
  bar_axis_label_y = NULL,
  bar_axis_label_adj_y = 0,
  bar_axis_label_font_y = 1,
  bar_axis_label_size_y = 1,
  bar_axis_label_col_y = "black",
  bar_axis_label_col_alpha_y = 1,
  bar_fill_y = "grey40",
  bar_fill_alpha_y = 1,
  bar_line_type_y = 1,
  bar_line_width_y = 1,
  bar_line_col_y = "black",
  bar_line_col_alpha_y = 1,
  axis_text_x = NULL,
  axis_text_side_x = "bottom",
  axis_text_font_x = 1,
  axis_text_size_x = 1,
  axis_text_col_x = "black",
  axis_text_col_alpha_x = 1,
  axis_text_angle_x = 3,
  axis_text_adjust_x = 0.45,
  axis_label_x = NULL,
  axis_label_font_x = 2,
  axis_label_size_x = 1.2,
  axis_label_col_x = "black",
  axis_label_col_alpha_x = 1,
  axis_ticks_length_x = 1,
  axis_text_y = NULL,
  axis_text_side_y = "left",
  axis_text_font_y = 1,
  axis_text_size_y = 1,
  axis_text_col_y = "black",
  axis_text_col_alpha_y = 1,
  axis_text_angle_y = 1,
  axis_text_adjust_y = 0.45,
  axis_label_y = NULL,
  axis_label_font_y = 2,
  axis_label_size_y = 1.2,
  axis_label_col_y = "black",
  axis_label_col_alpha_y = 1,
  axis_ticks_length_y = 1,
  margins = c(NA, NA, NA, NA),
  title = NULL,
  title_text_font = 2,
  title_text_size = 1.5,
  title_text_col = "black",
  title_text_col_alpha = 1,
  annotation_x = NULL,
  annotation_y = NULL,
  annotation_colours = NULL,
  annotation_size_x = 0.2,
  annotation_size_y = 0.2,
  annotation_text_size = 0.9,
  annotation_text_font = 1,
  annotation_text_col = "black",
  annotation_legend = TRUE,
  legend = TRUE,
  legend_side = "auto",
  legend_size = 1,
  legend_col_scale_size = 1,
  legend_col_breaks = NULL,
  legend_col_density = FALSE,
  legend_size_format = NULL,
  legend_title = NULL,
  legend_title_text_font = 2,
  legend_title_text_size = 1,
  legend_title_text_col = "black",
  legend_title_text_col_alpha = 1,
  legend_text_font = 1,
  legend_text_size = 1,
  legend_text_col = "black",
  legend_text_col_alpha = 1,
  mark_x = NULL,
  mark_y = NULL,
  mark_labels_x = NULL,
  mark_labels_y = NULL,
  mark_line_col = "grey40",
  zoom_x = NULL,
  zoom_y = NULL,
  zoom_size_x = NULL,
  zoom_size_y = NULL,
  zoom_side_x = NULL,
  zoom_side_y = NULL,
  cell_raster = "auto",
  cell_values = NULL,
  cell_glyph = "density",
  cell_glyph_range = "column",
  cell_glyph_col = "grey10",
  cell_glyph_fill = "#FFFFFF8C",
  fit_text = TRUE,
  popup = TRUE,
  popup_size = c(7, 7),
  features = NULL,
  assay = NULL,
  group_by = NULL,
  group_max = NULL,
  annotation_by = NULL,
  swap_axes = FALSE,
  transform = NULL,
  cofactor = 5,
  scale_q = 0.01,
  bimodal = FALSE,
  style = NULL,
  ...
)

Arguments

x

matrix or data.frame containing the data to display in the heatmap, or single-cell data: a SingleCellExperiment or SummarizedExperiment, a Seurat object, a flowFrame or flowSet, or a sparse matrix (e.g. a dgCMatrix, one cell per row), or an AnnData file read by heat_map_read_h5ad (or the name of an .h5ad file). Assays can be held on disk: DelayedArray objects (e.g. the HDF5Matrix and TENxMatrix of HDF5Array) and BPCells matrices (e.g. in Seurat layers) are read a block of features at a time. Single-cell data are drawn with one row per cell and one column per feature (see features, assay, group_by, group_max, annotation_by and swap_axes).

scale

logical indicating whether the data should be scaled prior to constructing the heatmap (TRUE scales each column). Additional options include "column" or "row" to indicate whether scaling should be performed within each column or each row. For convenience, the name of a scaling method ("range", "mean", "zscore" or "quantile") can also be supplied to apply that method to each column.

scale_method

indicates the type of scaling to perform on rows or columns as indicated by scale, options include "range", "mean", "zscore" or "quantile" (0 to 1 between the scale_q and 1 - scale_q quantiles, with the values beyond them clipped); see heat_map_scale. Set to "range" by default.

dist_method

indicates the type of distance metric to use when constructing dendrograms, set to "euclidean" distance by default. See ?dist for alternatives. Also supports "cosine" for cosine distance (1 - cosine similarity), "pearson", "spearman" or "kendall" for one minus the correlation (common for gene expression), or a function that takes the matrix being clustered (one row per row or column of the heatmap) and returns a dist object or a square matrix of distances.

clust_method

indicates the type of agglomeration method to use when performing hierarchical clustering, set to "complete" by default. See ?hclust for alternatives.

clust_max

the largest number of rows (or columns) clustered exactly, set to 5000 by default. Exact clustering needs the distances between every pair of rows, so its memory and time grow with the square of their number (about 400 MB and 1.5 seconds on two cores for 10,000 rows). Larger margins are clustered in two stages: a sample of clust_max rows is clustered exactly, its dendrogram is split into groups, every row joins the group of its nearest group medoid and each group is clustered exactly beneath the sample's dendrogram (see heat_map_clust). 100,000 rows take about half a second. Branch support (tree_support_x, tree_support_y) is only computed for up to clust_max rows or columns. Set to Inf to always cluster exactly. Rows or columns grouped by tree_cut_x or tree_cut_y (or tree_kmeans_x, tree_kmeans_y) are clustered within each group, and the groups share the limit in proportion to their size (at least 50 rows each), so grouped clustering takes no longer than clustering all the rows at once.

round

indicates the number of decimal places to round values when cell_text = TRUE and values are displayed in the heatmap, set to 2 decimal places by default

tree

options include "row", "y", "column", "x" or "both" (or TRUE) to indicate the axes for which dendrograms should be constructed, set to FALSE by default. This argument overrides the tree_x and tree_y arguments.

tree_x

logical indicating whether dendrograms should be constructed for the x axis (columns), set to NULL by default. Alternatively, a pre-computed hclust or dist object describing the columns of x, such as heat_map_info(hm)$tree_x from a previous heatmap. Clusters stored in the hclust object are kept unless tree_cut_x is supplied.

tree_size_x

numeric to control the height of the dendrogram for the x axis, set to 1 by default (0.6 inches).

tree_col_x

colours for the branches of the x axis dendrogram: one colour for the whole tree or, with clusters (tree_cut_x or tree_kmeans_x), one colour for each cluster from left to right, which colours the branches within the cluster (the branches joining clusters stay black), or TRUE for distinct colours. Set to NULL by default for black branches. The cluster labels take the same colours unless tree_label_col_x is given.

tree_scale_x

logical indicating whether the branch heights of the x axis dendrogram should be scaled for better visualisation, set to FALSE by default.

tree_order_x

how the branches of the x axis dendrogram are ordered, either "default" (the order from hclust), "olo" (optimal leaf ordering, Bar-Joseph et al. 2001, which flips branches so that neighbouring columns are as similar as possible), "mean" (branches ordered by their mean values - heatmap orders them by the sum of their columns' means instead, which favours small branches) or "spectral". Optimal leaf ordering is exact for up to 4000 columns, which takes well under a second; larger dendrograms are ordered in blocks (see heat_map_clust). A spectral order needs no dendrogram: the columns are ordered by recursive spectral bisection (Shi and Malik 2000; Atkins et al. 1998) of the graph joining each column to its 6 nearest neighbours (by dist_method, weighted as in UMAP, McInnes et al. 2018), which lays gradients and trajectories out along their length, cycles around their loop and clusters one after another, and runs of up to 12 columns are then reversed where that brings similar columns together (windowed 2-opt, Croes 1958). With a dendrogram, its branches are ordered by the mean spectral position of their columns. Up to clust_max columns are ordered exactly; more are ordered from a sample of clust_max landmarks, each other column placed beside its nearest landmark (200,000 take about 4 seconds). "peak" orders the columns by where they are highest along the rows, in the order of the rows in the data (ties by where they are lowest), so that features peaking early along a trajectory come first and cascades run diagonally (see heat_map_smooth); it needs no dendrogram either, and with one orders its branches by the mean peak position of their columns. The rows of a trajectory from heat_map_smooth() are placed by their position along it (e.g. pseudotime), so the peaks of its lineages are compared by when they occur; other rows split into groups by a factor or character tree_cut_y (or group_by) are placed by their position within their group.

tree_support_x

TRUE or a number of resamples (at least 10) to draw each branch of the x axis dendrogram by its bootstrap support (Felsenstein 1985): the rows are resampled with replacement and the columns clustered again (with dist_method and clust_method, within each group for a dendrogram split by groups), and each branch scores the proportion of resamples in which its exact set of columns is a branch again. Branches with 90% support or more are thick black lines, 70-89% grey lines and lower support dashed lines, with a key in the legend. TRUE uses 100 resamples. The resamples use a fixed seed (leaving the random number generator as it was), so the support is the same each time the heatmap is drawn. heat_map_info() returns the support of each branch.

tree_cut_x

either a numeric ranging from 0 to 1 indicating the branch cut height for x axis dendrogram (proportional for non-cosine distances, or absolute cosine distance threshold when dist_method = "cosine"), an integer indicating the desired number of clusters to obtain by cutting the x axis dendrogram, or "auto" to choose the number of clusters from the data by their mean silhouette width (from 2 to 20 clusters, or none when no cut reaches a width of 0.25; see heat_map_clust). Alternatively, clusters can be manually defined by specifying the number of columns to include in each cluster in the displayed order (e.g., c(3,4,5)), or a vector of cluster indices can be supplied to assign each column to a specific cluster (e.g., c(1,1,1,2,2,2,2,3,3,3) for 10 columns in 3 clusters). Numeric cluster indices are given column by column from the left of the heatmap as it is displayed without them (in the dendrogram order when tree_x is requested), so clusters can be assigned by reading a heatmap. Named indices are matched to the column names of x, and labels (character or factor, e.g. treatments from metadata) are given in the original column order of x. Columns are regrouped so that each cluster is contiguous, ordered from left to right. When a vector of indices is supplied, its length must equal the number of columns in x; if its length also matches a valid set of cluster sizes, it is treated as cluster indices. If a dendrogram is requested (tree_x = TRUE), the columns are clustered within each cluster and the clusters are joined at the top of the dendrogram, so the clusters act as groups (e.g. treatments) with a dendrogram inside each one. A dendrogram supplied as an hclust or dist object (or a heatmap with non-numeric columns) is kept only when the clusters are contiguous in its order. Clusters are always numbered, and labelled by tree_label_text_x, in the displayed order from left to right.

tree_kmeans_x

number of k-means clusters (Hartigan and Wong 1979) to split the columns of x into, an alternative to tree_cut_x (e.g. tree_kmeans_x = 3). See tree_kmeans_y.

tree_split_x

a numeric to control the spacing between x axis tree splits, set to 1 by default. Setting the argument to 0 will remove axis tree splits. Each unit is 0.08 inches.

tree_label_x

logical indicating whether a label should be added for each cluster within the x axis tree when tree_cut_x is specified, set to FALSE by default.

tree_label_size_x

numeric to control the height of the tree cluster labels for the x axis tree, set to 0.1 by default. Strips holding label text are made tall enough for the text; the strip is at least 0.8 inches x tree_label_size_x tall.

tree_label_col_x

vector of colours to use for x axis tree cluster labels from left to right, set to "grey85" (light grey) by default - or, with one colour per cluster in tree_col_x, to the colours of the branches. The settings of the cluster labels take one value, or one for each cluster; other lengths are recycled with a warning.

tree_label_col_alpha_x

numeric to control the transparency of the x axis tree cluster labels, set to 1 by default to use solid colours.

tree_label_text_x

a vector of text to include in the x axis tree cluster labels from left to right, set to NA by default.

tree_label_text_font_x

a vector of font types to use for text in x axis cluster labels, set to 1 by default for plain text. See font in ?par for alternatives.

tree_label_text_size_x

a vector of numerics to control the size of the text in the x axis cluster labels, set to 1 by default.

tree_label_text_col_x

a vector of colours to control the colour of text in x axis cluster labels, set to "auto" by default to use white text on dark labels and black text on light ones, whichever contrasts more with the colour of each label (by the contrast ratio of the Web Content Accessibility Guidelines).

tree_label_text_col_alpha_x

a vector of numerics to control the transparency of text in x axis cluster labels, set to 1 by default to use solid colours.

tree_y

logical indicating whether dendrograms should be constructed for the y axis (rows), set to NULL by default. Rows are drawn from the top in the dendrogram order (as columns are from the left), or in the order of x without a dendrogram. Alternatively, a pre-computed hclust or dist object describing the rows of x, such as heat_map_info(hm)$tree_y from a previous heatmap. Clusters stored in the hclust object are kept unless tree_cut_y is supplied.

tree_size_y

numeric to control the width of the dendrogram for the y axis, set to 1 by default (0.6 inches).

tree_col_y

colours for the branches of the y axis dendrogram, as tree_col_x, with one colour for each cluster from top to bottom.

tree_scale_y

logical indicating whether the branch heights of the y axis dendrogram should be scaled for better visualisation, set to FALSE by default.

tree_order_y

how the branches of the y axis dendrogram are ordered, either "default", "olo", "mean", "spectral" or "peak", as for tree_order_x. A spectral order without a dendrogram orders the rows on their own (e.g. cells along a differentiation trajectory or samples along a time course); rows grouped by tree_cut_y or tree_kmeans_y keep it within each group. "peak" orders the rows by where they are highest along the columns (e.g. genes along pseudotime with swap_axes = TRUE), within the groups of a factor or character tree_cut_x.

tree_support_y

TRUE or a number of resamples to draw each branch of the y axis dendrogram by its bootstrap support, resampling the columns. See tree_support_x.

tree_support_labels

logical indicating whether larger branches (at least 5 leaves and an eighth of all leaves) are labelled with their support as a percentage, set to TRUE by default.

tree_cut_y

either a numeric ranging from 0 to 1 indicating the branch cut height for y axis dendrogram (proportional for non-cosine distances, or absolute cosine distance threshold when dist_method = "cosine"), an integer indicating the desired number of clusters to obtain by cutting the y axis dendrogram, or "auto" to choose the number of clusters by mean silhouette width, as for tree_cut_x. Alternatively, clusters can be manually defined by specifying the number of rows to include in each cluster in the displayed order, starting from the top of the heatmap (e.g., c(3,4,5)), or a vector of cluster indices can be supplied to assign each row to a specific cluster (e.g., c(1,1,1,2,2,2) for 6 rows in 2 clusters). Numeric cluster indices are given row by row from the top of the heatmap as it is displayed without them (in the dendrogram order when tree_y is requested; without a dendrogram in the order of x). Named indices are matched to the row names of x, and labels (character or factor, e.g. cell types from metadata) are given in the original row order of x. Rows are regrouped so that each cluster is contiguous, the first cluster at the top. When a vector of indices is supplied, its length must equal the number of rows in x. If a dendrogram is requested (tree_y = TRUE), the rows are clustered within each cluster and the clusters are joined at the top of the dendrogram (e.g. cells grouped by cell type, each with its own dendrogram); a supplied hclust or dist object is kept only when the clusters are contiguous in its order. Clusters are always numbered, and labelled by tree_label_text_y, in the displayed order from the top of the heatmap to the bottom, which may differ from the supplied indices when the dendrogram order is kept.

tree_kmeans_y

number of k-means clusters to split the rows of x into, an alternative to tree_cut_y that is quick for many rows (e.g. tree_kmeans_y = 4). The rows are clustered on the numeric columns of x after scaling, by the Hartigan-Wong algorithm (in compiled code), from the centres of equal slices of the rows along their first principal component and from nine k-means++ starts (Arthur and Vassilvitskii 2007, greedy as in Grunau et al. 2023), fitted on separate threads, keeping the clusters with the smallest within-cluster sum of squares (for more than 20,000 rows, the starts are compared on a sample of 20,000, the best few fits of the sample are compared on every row, and every row is then fitted from the best). The starts use fixed seeds, so the clusters don't depend on the random seed. The clusters are ordered so that similar clusters are neighbours (optimal leaf order of their centres) and then act like groups supplied to tree_cut_y: with a dendrogram (tree_y = TRUE) the rows are clustered within each k-means cluster, and tree_split_y and tree_label_y separate and label the clusters. Missing values are replaced by the mean of their column for k-means. heat_map_info()$row_clusters returns the clusters.

tree_split_y

a numeric to control the spacing between y axis tree splits, set to 1 by default. Setting the argument to 0 will remove axis tree splits. Each unit is 0.08 inches.

tree_label_y

logical indicating whether a label should be added for each cluster within the y axis tree when tree_cut_y is specified, set to FALSE by default.

tree_label_size_y

numeric to control the width of the tree cluster labels for the y axis tree, set to 0.1 by default. Strips holding label text are made wide enough for the text; the strip is at least 0.8 inches x tree_label_size_y wide.

tree_label_col_y

vector of colours to use for y axis tree cluster labels from top to bottom, set to "grey85" (light grey) by default - or, with one colour per cluster in tree_col_y, to the colours of the branches.

tree_label_col_alpha_y

numeric to control the transparency of the y axis tree cluster labels, set to 1 by default to use solid colours.

tree_label_text_y

a vector of text to include in the y axis tree cluster labels from the top of the heatmap to the bottom, set to NA by default. Other settings with one value per row cluster (colours, fonts and sizes) are also given from the top.

tree_label_text_font_y

a vector of font types to use for text in y axis cluster labels, set to 1 by default for plain text. See font in ?par for alternatives.

tree_label_text_size_y

a vector of numerics to control the size of the text in the y axis cluster labels, set to 1 by default.

tree_label_text_col_y

a vector of colours to control the colour of text in y axis cluster labels, set to "auto" by default to use white text on dark labels and black text on light ones, whichever contrasts more with the colour of each label (by the contrast ratio of the Web Content Accessibility Guidelines).

tree_label_text_col_alpha_y

a vector of numerics to control the transparency of text in y axis cluster labels, set to 1 by default to use solid colours.

cell_shape

indicates the shape to use for the cells in the heatmap, options include "rect", "circle", "diamond", "ellipse", "number" or "none". Circles, diamonds and ellipses stay round on cells that aren't square, sized by the shorter side of the cells. Ellipses show values between -1 and 1, such as correlations, by their shape (Murdoch and Chow 1996) - the outline of a bivariate normal distribution with that correlation, rising to the right for positive values, falling for negative values, and narrower the closer the value is to -1 or 1 (a circle at 0); values beyond -1 and 1 are drawn as -1 or 1 with a warning. "number" writes the value of each cell (or its cell_text) in the colour of the cell instead of filling it, darkened where the colour is too light to read, and "none" leaves the cell empty apart from its cell_text. Alternatively, a matrix of the same dimensions as x containing the shape to use for each cell, e.g. ellipses below the diagonal of a correlation matrix and numbers above it (see heat_map_cor).

cell_size

logical indicating whether each cell in the heatmap should be scaled by the value in x, set to FALSE by default. Alternatively, a matrix of the same dimensions as x containing the values by which the size of each cell should be scaled.

cell_col_palette

a vector of colours from which colours are selected for columns containing non-numeric data, one for each distinct value (interpolated between the colours when there are more values). Alternatively, the name of a palette listed in hcl.pals (e.g. "Dark 3") or a function that returns n colours. With the default colours, values beyond the six take distinct colours of several lightnesses, each the furthest from the colours before it (as Glasbey et al. 2007 choose them), so that dozens of values can be told apart.

cell_col_scale

a vector of colours to use for the colour scale of numeric values. By default the scale runs through the colour-blind friendly viridis colours (as in viridisLite) from dark purple to yellow, then on through orange and red to dark red. Alternatively, the name of a palette listed in hcl.pals (e.g. "viridis" or "Blue-Red 3"), a palette function that takes the number of colours as its first argument n (e.g. one created by colorRampPalette), or a function created by colorRamp.

cell_col_scale_limits

a numeric vector of length 2 specifying custom limits for the colour scale as c(min, max). If NULL (default), limits are computed from the data before rounding. Custom limits allow you to set consistent colour scales across multiple heatmaps or override automatic scaling. Set to "robust" to use the 2nd and 98th percentiles of the data, so that a few outliers don't wash out the colour scale; values beyond the limits take the colours at the ends of the scale.

cell_col_scale_center

optional numeric value at which to centre the colour scale, set to NULL by default. When supplied, the colour scale limits are made symmetric around this value so that it maps to the middle colour of cell_col_scale. Useful with diverging palettes such as "Blue-Red 3" and scale_method = "zscore" (center = 0).

cell_col_scale_breaks

a numeric vector of at least two breaks that bin the values into a stepped colour scale, set to NULL by default for a continuous scale. Each bin between consecutive breaks takes one colour, evenly spaced along cell_col_scale whatever the widths of the bins, and values beyond the outer breaks take the colours of the outer bins. The breaks set the limits of the colour scale and label the colour legend.

cell_col_blocks_x, cell_col_blocks_y

blocks of columns (or rows), each with its own colour scale and colour legend: a vector or factor with one value per column (row) of x in its original order, naming the block of each - e.g. "RNA" for the columns of genes and "ADT" for those of proteins, whose values aren't comparable. Each block's colours span its own values (or its own cell_col_scale_limits) and its legend is titled by its name. cell_col_scale, cell_col_scale_limits and cell_col_scale_center then take one setting for every block or a list with one per block (in the order of the blocks, or named by them). Blocks are separate from clusters: give the same vector to tree_cut_x to split and label the blocks (as heat_map_align does). Can't be combined with cell_col_scale_breaks or cell_uncertainty. Set to NULL by default for one colour scale.

cell_size_scale_limits

a numeric vector of length 2 specifying custom limits for the size scale as c(min, max). If NULL (default), limits are computed from the data before rounding. Only used when cell_size is not FALSE. Custom limits allow consistent size scales across multiple heatmaps.

cell_size_scale_method

indicates how values are mapped to cell sizes, either "linear" (default) to scale the width of each cell with its value, or "area" to scale the area of each cell with its value, which is perceptually more accurate.

cell_size_scale_range

numeric vector of length 2 indicating the smallest and largest relative cell sizes (as a proportion of the cell width), set to c(0, 1) by default. Increasing the lower limit (e.g. c(0.1, 1)) ensures cells with the smallest values remain visible.

cell_col_alpha

a numeric to control the fill transparency of cells within the heatmap, set to 1 by default to use solid colours. A different transparency can be used for each cell by supplying a matrix with the same dimensions as x, or a vector that is recycled down the columns of x (as in matrix()). Legends use solid colours unless all cells share the same transparency.

cell_uncertainty

a numeric matrix with the same dimensions as x holding the uncertainty of each value, such as a standard error, a confidence interval width or a p-value. Cells are coloured with a value-suppressing palette (Correll et al. 2018): the more uncertain a value, the fewer colours its part of the scale has and the closer they are to grey, so an uncertain value can't look like a strong one. The most certain level uses 8 colours across the scale (with the default 4 levels), the next 4, then 2, and the most uncertain level a single, nearly grey colour. Missing uncertainties are treated as the most uncertain. The colour legend becomes a key with one row per uncertainty level.

cell_uncertainty_breaks

1 to 5 increasing thresholds between the uncertainty levels, set to NULL by default for thresholds at a quarter, half and three quarters of the largest uncertainty (4 levels).

cell_uncertainty_title

heading of the uncertainty levels in the colour legend, set to "Uncertainty" by default.

cell_split

a numeric matrix with the same dimensions as x holding a second value for each cell, such as the treated condition when x holds the control. Each cell is split along its diagonal: the value in x fills the upper left half and the value in cell_split the lower right half, on the same colour scale (its limits cover both). Circles (cell_shape = "circle") are split down the middle instead: x fills the left half and cell_split the right half, and each half can have its own size (cell_size and cell_split_size), as in the split dots of heat_map_dot. Other cells must be full-size rectangles (no cell_size or other cell_shape). Can't be combined with cell_uncertainty; cells of non-numeric columns are not split. With scale, each column (or row) of x is scaled together with the same column (or row) of cell_split, so that the halves stay comparable.

cell_split_labels

two labels for the halves of the cells in the legend - the values in x and in cell_split, set to c("x", "cell_split") by default.

cell_split_size

a numeric matrix with the same dimensions as x giving the size of the right half of each split circle, on the same size scale as the matrix given to cell_size (which sizes the left halves; the limits of the scale cover both). Set to NULL by default, for halves of the same size - or, with cell_size = TRUE, right halves sized by cell_split. Halves with a missing size are not drawn.

cell_col_empty

a colour to use for missing values in x, set to "white" by default.

cell_border_line_type

a integer to indicate the type of line to use for cell borders, set to 1 by default for solid lines. See lty in ?par for alternatives.

cell_border_line_width

a numeric to control the width of cell borders, set to 1 by default.

cell_border_line_col

indicates the colour to use for cell borders, set to "black" by default. Borders are left out when cells are smaller than three line widths, as they would hide the cells, unless a cell_border_mask is supplied.

cell_border_line_col_alpha

numeric to control the transparency of cell borders, set to 1 by default to use solid colours.

cell_grid_line_col

colour of grid lines drawn around every cell (apart from empty cells, see cell_shape = "none"), behind the cells, set to NA by default to draw no grid. A light grid (e.g. "grey85") keeps the rows and columns visible when cells are drawn as shapes that don't fill them, such as circles, ellipses or numbers. The grid uses cell_border_line_type and cell_border_line_width and is left out, like cell borders, when the cells are too small.

cell_border_mask

a matrix of the same dimensions as x containing TRUE/FALSE values indicating whether each cell should have a coloured border (TRUE) or a transparent border (FALSE), set to NULL by default to apply border colour to all cells. Missing values are treated as FALSE.

cell_text

logical indicating whether the values in x should be displayed in each cell of the heatmap, set to FALSE by default.

cell_text_font

an integer to control the font face of cell text, set to 1 by default. See font in ?par for alternatives.

cell_text_size

numeric to control the size of cell text, set to 1 by default.

cell_text_col

colour to use for cell text, set to "white" by default.

cell_text_col_alpha

numeric ranging from 0 to 1 to control the transparency of cell text, set to 1 by default to use solid colours for cell text.

bar_size_x

numeric to control the height of x axis bar plot, set to 1 by default (0.6 inches).

bar_values_x

a vector of values to display in x axis bar plot, supplied in the order matching the original columns of x or named with the column names of x. The values supplied to bar_values_x will be internally reordered to match the order of columns as determined by hierarchical clustering. To show the distribution of several values for each column as a box plot or violin (bar_type_x), supply a list with a numeric vector for each column (named or in the original order), a matrix or data.frame with one column for each column of x, or TRUE for the values of each column of the heatmap (after scaling). For stacked bars (bar_type_x = "stack" or "fill"), supply a matrix with one column per column of x and one row per part (e.g. counts per condition). "n" shows the number of cells in each group of a summary from heat_map_summarise(group_by = ...), or with stacked bars their numbers in each part of stack_by.

bar_type_x

the type of plot drawn for bar_values_x: "bar" (one value per column), "box" (box plots of the values of each column, with the median, quartiles, whiskers to the most extreme values within 1.5 times the interquartile range and points beyond them) or "violin" (Hintze and Nelson 1998: densities of the values of each column, with a line at the median), "stack" (stacked bars of the parts of each column, e.g. the number of cells of each condition in each cluster) or "fill" (stacked bars of the proportions of the parts). Set to NULL by default to draw bars for a vector and box plots for distributions. bar_fill_x and the bar_line_*_x arguments style the boxes and violins; for stacked bars bar_fill_x gives one colour per part (named by part or in order), and the parts get a legend.

bar_axis_label_x

axis label to use for the x axis bar plot.

bar_axis_label_adj_x

scalar [-1, 1] to adjust the position of the x axis bar graph label relative to the x axis, set to 0 by default.

bar_axis_label_font_x

font to use for the axis label of the x axis bar plot, set to 1 by default. See font in ?par for alternatives.

bar_axis_label_size_x

numeric to control the size of the axis text in x axis bar plots, set to 1 by default.

bar_axis_label_col_x

colour to use for the axis text in x axis bar plot, set to "black" by default.

bar_axis_label_col_alpha_x

numeric ranging from 0 to 1 to control the transparency of axis text in x axis bar plot, set to 1 by default to use solid colours.

bar_fill_x

a vector of colours to use for the bars in the x axis bar plot, set to "grey40" by default.

bar_fill_alpha_x

a numeric ranging from 0 to 1 to control the fill transparency of bars in x axis bar plot, set to 1 by default to use solid colours.

bar_line_type_x

integer to control the line type of bar borders in the x axis bar plot, set to 1 by default to use solid lines. See lty in ?par for alternatives.

bar_line_width_x

numeric to control the width bar borders in x axis bar plot, set to 1 by default.

bar_line_col_x

colour to use for bar borders in x axis bar plot, set to "black" by default.

bar_line_col_alpha_x

numeric ranging from 0 to 1 to control the transparency of bar borders in x axis bar plot, set to 1 by default.

bar_size_y

numeric to control the width of y axis bar plot, set to 1 by default (0.6 inches).

bar_values_y

a vector of values to display in y axis bar plot, supplied in the order matching the original rownames of x or named with the row names of x. The values supplied to bar_values_y will be internally reordered to match the order of rows as determined by hierarchical clustering. As for bar_values_x, a list (one numeric vector per row), a matrix or data.frame with one row per row of x, or TRUE (the values of each row of the heatmap) shows the distribution of each row as a box plot or violin, and a matrix with one row per row of x and one column per part gives stacked bars (bar_type_y = "stack" or "fill"). "n" shows the number of cells in each group of a summary from heat_map_summarise(group_by = ...), or with stacked bars their numbers in each part of stack_by, and "dip" the largest dip of each row of a summary with dips (see bimodal). The axis of the row bar graph is drawn on the x axis side with the x axis text font, size, colour, adjustment and tick length (and that of the column bar graph on the y axis side with the y axis settings); its numbers are always horizontal.

bar_type_y

the type of plot drawn for bar_values_y, as for bar_type_x.

bar_axis_label_y

axis label to use for the y axis bar plot.

bar_axis_label_adj_y

scalar [-1, 1] to adjust the position of the y axis bar graph label relative to the y axis, set to 0 by default.

bar_axis_label_font_y

font to use for the axis label of the y axis bar plot, set to 1 by default. See font in ?par for alternatives.

bar_axis_label_size_y

numeric to control the size of the axis text in y axis bar plots, set to 1 by default.

bar_axis_label_col_y

colour to use for the axis text in y axis bar plot, set to "black" by default.

bar_axis_label_col_alpha_y

numeric ranging from 0 to 1 to control the transparency of axis text in y axis bar plot, set to 1 by default to use solid colours.

bar_fill_y

a vector of colours to use for the bars in the y axis bar plot, set to "grey40" by default.

bar_fill_alpha_y

a numeric ranging from 0 to 1 to control the fill transparency of bars in y axis bar plot, set to 1 by default to use solid colours.

bar_line_type_y

integer to control the line type of bar borders in the y axis bar plot, set to 1 by default to use solid lines. See lty in ?par for alternatives.

bar_line_width_y

numeric to control the width bar borders in y axis bar plot, set to 1 by default.

bar_line_col_y

colour to use for bar borders in y axis bar plot, set to "black" by default.

bar_line_col_alpha_y

numeric ranging from 0 to 1 to control the transparency of bar borders in y axis bar plot, set to 1 by default.

axis_text_x

vector of text to use for x axis labels supplied in the order matching the constructed heatmap (from left to right), or named by the column names of x to label each column by name wherever it is drawn, set to NULL by default to use the column names of x. Missing values (NA) are drawn as empty labels without a tick mark, so NA removes the x axis text. An expression can be supplied for mathematical annotation (see ?plotmath).

axis_text_side_x

indicates whether the x axis text should be on the 1 - "bottom" or 3 - "top" of the heatmap, set to "bottom" by default. All other heatmap components, including the tree, tree labels and bar plot will be positioned on the opposite side to the axis text.

axis_text_font_x

integer to control the font face of x axis labels, set to 1 by default. See font in ?par for alternatives.

axis_text_size_x

numeric to control the size of x axis text, set to 1 by default.

axis_text_col_x

colour to use for x axis text labels, set to "black" by default.

axis_text_col_alpha_x

numeric ranging from 0 to 1 to control the transparency of x axis text labels, set to 1 by default to use solid text colours.

axis_text_angle_x

controls the angle of x axis text labels relative to the x axis, set to 3 by default. The whole numbers 0 to 3 are las codes (see las in ?par), any other angle between 0 and 90 is in degrees. Labels rotated by an angle (e.g. 45) end at their ticks and slant towards the y axis text, so that the longest labels extend beneath (or above) the y axis text rather than the dendrograms and legends. Rotated labels are spaced along the axis by their height across their baselines, and axis_text_adjust_x is not used. The angle is not used for mark labels (mark_x).

axis_text_adjust_x

numeric to adjust position x axis text relative to x axis ticks, set to 0.45 by default.

axis_label_x

label to use for the x axis.

axis_label_font_x

integer to control the font face of the x axis label, set to 2 by default.

axis_label_size_x

numeric to control the size of the x axis label, set to 1.2 by default.

axis_label_col_x

colour to use for x axis label text, set to "black" by default.

axis_label_col_alpha_x

numeric ranging from 0 to 1 to control the transparency of the x axis label text, set to 1 by default to use solid colours.

axis_ticks_length_x

numeric to control the length of the x axis ticks, set to 1 by default.

axis_text_y

vector of text to use for y axis labels supplied in the order matching the constructed heatmap (from top to bottom), or named by the row names of x to label each row by name, set to NULL by default to use the row names of x, or the row indices when x has no row names. Missing values (NA) are drawn as empty labels without a tick mark, so NA removes the y axis text. An expression can be supplied for mathematical annotation (see ?plotmath). Axis text settings with one value per row (e.g. axis_text_col_y) are also given from the top.

axis_text_side_y

indicates whether the y axis text should be on the 2 - "left" or 4 - "right" of the heatmap, set to "left" by default. All other heatmap components, including the tree, tree labels and bar plot will be positioned on the opposite side to the axis text.

axis_text_font_y

integer to control the font face of y axis labels, set to 1 by default. See font in ?par for alternatives.

axis_text_size_y

numeric to control the size of y axis text, set to 1 by default.

axis_text_col_y

colour to use for y axis text labels, set to "black" by default.

axis_text_col_alpha_y

numeric ranging from 0 to 1 to control the transparency of y axis text labels, set to 1 by default to use solid text colours.

axis_text_angle_y

integer to control the angle of y axis text labels relative to the y axis, set to 1 by default. See las in ?par for alternatives.

axis_text_adjust_y

numeric to adjust position y axis text relative to y axis ticks, set to 0.45 by default.

axis_label_y

label to use for the y axis.

axis_label_font_y

integer to control the font face of the y axis label, set to 2 by default.

axis_label_size_y

numeric to control the size of the y axis label, set to 1.2 by default.

axis_label_col_y

colour to use for y axis label text, set to "black" by default.

axis_label_col_alpha_y

numeric ranging from 0 to 1 to control the transparency of the y axis label text, set to 1 by default to use solid colours.

axis_ticks_length_y

numeric to control the length of the y axis ticks, set to 1 by default.

margins

vector of numerics to control the size of the margins around the bottom, left, top and right of the heatmap, in lines of text (as par("mar")). Setting any of these values to NA (the default) sizes that margin to fit its contents.

title

text to include in the title above the heatmap.

title_text_font

integer to control the font face for the heatmap title, set to 2 by default. See font in ?par for alternatives.

title_text_size

numeric to control the size of the text in the heatmap title, set to 1.5 by default.

title_text_col

colour to use for text in heatmap title, set to "black" by default.

title_text_col_alpha

numeric ranging from 0 to 1 to control the transparency of text in heatmap title, set to 1 by default for solid colours.

annotation_x

a data.frame of metadata describing the columns of x (e.g. the treatment and sex of each sample), drawn as coloured tracks beside the heatmap opposite the x axis text. Rows are matched to the column names of x when the data.frame has row names, otherwise one row per column of x in the original order. Non-numeric columns are coloured by level and numeric columns with a colour ramp. A single vector is treated as one annotation.

annotation_y

a data.frame of metadata describing the rows of x, drawn as tracks opposite the y axis text (see annotation_x).

annotation_colours

a named list of colours for the annotations, e.g. list(Treatment = c(Control = "grey", Drug = "red")). Discrete annotations accept a named vector (one colour per level), an unnamed vector, a palette function or an hcl.pals() name; numeric annotations accept colours for a ramp, a colorRamp() function or an hcl.pals() name. Annotations without an entry get default palettes.

annotation_size_x, annotation_size_y

height (width) of each annotation track in inches, set to 0.2 by default.

annotation_text_size, annotation_text_font, annotation_text_col

size, font and colour of the annotation names, which are written beside the tracks on the side of the axis text.

annotation_legend

logical indicating whether legends should be drawn for the annotations, set to TRUE by default.

legend

logical indicating whether to include a legend in the heatmap, set to TRUE by default to include the colour, size and levels legends that apply. Alternatively, a character vector containing any of "colour", "size", "both" (colour and size) or "levels" to indicate the type(s) of legends to include in the heatmap. The "levels" legend shows the colours assigned to values in non-numeric columns, e.g. legend = "both" leaves it out. Set to FALSE, NA or "none" to remove the legend.

legend_side

where to draw the legend, either "auto" (the default) beside the heatmap, opposite the y axis text, or "bottom" below the heatmap with horizontal colour bars and the legends side by side (wrapping into rows when they don't fit across the figure).

legend_size

numeric to control the amount of space allocated to the legend, set to 1 by default. The legend is sized from its contents and legend_size scales the legend keys (colour bars, swatches and size legend shapes).

legend_col_scale_size

numeric to control the width of the legend colour scale relative to the allocated space for the legend, set to 1 by default.

legend_col_breaks

values at which to label the colour legend, set to NULL by default to choose them automatically (or use cell_col_scale_breaks). Names, when supplied, are used as the labels, e.g. c(low = -2, 0, high = 2).

legend_col_density

logical indicating whether the distribution of the numeric values (a kernel density) is drawn as a trace over the colour legend, so that you can see which colours most cells take and how many values sit near the limits of the scale (e.g. with cell_col_scale_limits = "robust"), set to FALSE by default.

legend_size_format

the text of the size legend: NULL (the default) for its values, "percent" for values between 0 and 1 (e.g. the proportion of cells detected) shown as percentages, or a function taking the values and returning their labels.

legend_title

a vector of up to three elements containing text to be displayed above the cell colour, size and levels legends respectively.

legend_title_text_font

integer to control the font face for the heatmap legends, set to 2 by default for bold font. See font in ?par for alternatives.

legend_title_text_size

numeric to control the size of the text in the heatmap legend titles, set to 1 by default.

legend_title_text_col

colour to use for text in heatmap legend titles, set to "black" by default.

legend_title_text_col_alpha

numeric ranging from 0 to 1 to control the transparency of text in heatmap legend titles, set to 1 by default for solid colours.

legend_text_font

integer to control the font face for legend text, set to 1 by default. See font in ?par for alternatives.

legend_text_size

numeric to control the size of text in the legend, set to 1 by default.

legend_text_col

colour to use for text in the legend, set to "black".

legend_text_col_alpha

numeric to control the transparency of text in the legend, set to 1 by default to use solid colours.

mark_x, mark_y

columns or rows to label, as names, positions in the heatmap as it is displayed (columns from the left, rows from the top), or a logical vector with one value per column or row in the original order of x. The labels replace the axis text on that axis: they are spread out beside the heatmap so that they don't overlap, and leader lines connect each label to its column or row. This names a few rows of a large heatmap (e.g. marker genes) when there is no room to label every row. The labels use the axis text font, size and colour; row labels are horizontal and column labels vertical.

mark_labels_x, mark_labels_y

labels for the columns or rows in mark_x and mark_y, one per marked column or row (one per element of names or positions, or one per TRUE value of a logical vector), set to NULL by default to use the column or row names.

mark_line_col

colour of the leader lines connecting mark labels to their rows or columns, set to "grey40" by default.

zoom_x, zoom_y

columns or rows to enlarge, as names, positions in the heatmap as it is displayed (columns from the left, rows from the top), or a logical vector with one value per column or row in the original order of x. Every row from the first to the last of these in the displayed order is enlarged, so giving the first and last rows of a band is enough (e.g. a cluster from tree_cut_y). The band is outlined on the heatmap and drawn again in a larger panel beside it, joined to the band by a wedge, with the enlarged rows named on the outer side of the panel. This shows the detail of a few rows of a large heatmap together with the whole. A list enlarges several bands, each in its own panel (e.g. zoom_y = list(c("gene1", "gene9"), 40:55)); bands can't share rows. Panels on the same side keep the order of their bands, are spread out so that they don't overlap and enlarge their rows by the same amount.

zoom_size_x, zoom_size_y

size of the zoom panel relative to the heatmap - its height for zoom_x and its width for zoom_y - between 0.2 and 5. Along the band the panel is as long as the heatmap, or shorter when that would make the enlarged cells larger than 0.3 inches. Set to NULL by default for panels as large as the heatmap when they are as long as it, and smaller for shorter panels (down to 0.3 for a band of a few rows), so that enlarging a few rows or columns (e.g. one cell of single-cell data) doesn't halve the heatmap.

zoom_side_x, zoom_side_y

the side of the heatmap each zoom panel is drawn on: "bottom" or "top" for zoom_x, "left" or "right" for zoom_y. One side for every panel, or sides for the bands of a list in turn (recycled, so c("left", "right") alternates). Set to NULL by default to use the axis text side, where the panels replace the axis text. Panels on the other side are drawn beyond the dendrogram and other tracks, which a lane carries the band across, and the heatmap keeps its axis text unless a panel is on the axis text side. mark_x or mark_y can't be combined with panels on the axis text side of the same axis.

cell_raster

whether to draw the cells as raster images, which is much faster and gives smaller files for large heatmaps. Set to "auto" by default to use raster images for heatmaps with more than 50,000 cells. TRUE always uses raster images and FALSE never does. Raster images are only used when every cell is a full-size rectangle (no cell_size scaling or other cell_shape) and the graphics device supports them; cell borders are then drawn as grid lines.

cell_values

a matrix of lists with the same dimensions as x, holding a numeric vector of values for each cell, such as the result of heat_map_summarise(fun = "values"). The distribution of each cell's values is drawn inside the cell (cell_glyph), so that a heatmap of summaries (e.g. the median of each marker in each cluster) also shows the spread and shape behind each summary - two populations behind a middling median, for example. Values are drawn as supplied, without scale.

cell_glyph

how the values in cell_values are drawn: "density" (a kernel density with a tick at the median, the default), "histogram" (16 bins with a tick at the median) or "box" (a box plot as boxplot(), with the median, quartiles, whiskers to 1.5 times the interquartile range and the values beyond them). A single distinct value is drawn as a vertical line.

cell_glyph_range

the range of values spanned by each glyph, shared by the cells of each "column" (the default), each "row" or "all" cells, or a numeric vector c(min, max). Values beyond the range are drawn at its ends.

cell_glyph_col

colour of the lines of the glyphs, set to "grey10" by default.

cell_glyph_fill

fill colour of densities, histogram bars and boxes, set to translucent white by default so that the cell colour shows through.

fit_text

logical indicating whether axis text, cell text and cluster label text should be shrunk to fit the available space when it would otherwise overlap, set to TRUE by default. Axis labels that still don't fit at half their size are thinned to every second, third, ... label.

popup

logical indicating whether the heatmap should be drawn in a new popup window, set to TRUE by default. Popups are only opened in interactive sessions: in scripts, R Markdown and other non-interactive sessions the heatmap is drawn on the current device.

popup_size

vector to control the height and width of the popup window in inches, set to c(7,7).

features

the features (genes, proteins or markers) of single-cell data to show, as names (or indices), in the order to show them. Only these features are read from sparse data, so a few markers of a large dataset need little memory. Features are matched to the row names of SingleCellExperiment and Seurat objects (or to gene symbols in the rowData() column Symbol, gene_name or similar), to the marker names (desc) or channel names of a flowFrame or flowSet and to the column names of matrices and data.frames. Missing features are an error that names them. Set to NULL by default to show every feature; a message is shown when the dense values would take more than 1 GB.

assay

the values of single-cell data to show: an assay of a SingleCellExperiment or SummarizedExperiment (by name or number; by default "logcounts", else "exprs", else the first), or for a Seurat object an assay (its "data" layer), a layer of the default assay (e.g. "counts" or "scale.data") or both as c(assay, layer).

group_by

the group of each cell (e.g. its cluster or cell type): the name of a column of the cells' metadata (colData() of a SingleCellExperiment, meta.data of a Seurat object, "sample" or a pData() column of a flowSet), of a column of a matrix, data.frame or flowFrame (left out of the features), or a vector with the group of each cell. The cells are grouped as by tree_cut_y, in the order of the groups' factor levels (sorted for other vectors), and the groups are labelled (tree_label_y). Several column names (or a data.frame or list of several variables, with one value per cell) group the cells by their combinations, e.g. c("cell_type", "condition") for each cell type in each condition: ordered by the first variable, then the next within it, labelled "CD4 T / control", and without empty combinations. Cells without a group (NA, or a missing value of any of the variables) are left out with a message.

group_max

the largest number of cells to show from each group of group_by (or in all when there are no groups), drawn with a fixed seed by heat_map_downsample, so that small groups stay visible next to large ones. Arguments with one value per cell (bar_values_y, a logical mark_y, and matrices given to cell_size, cell_text, cell_split, cell_split_size, cell_uncertainty, cell_values and cell_border_mask) are kept for the cells shown. Set to NULL by default to show every cell.

annotation_by

annotations of the cells drawn as tracks beside the heatmap (as annotation_y): names of columns of the cells' metadata (see group_by), or a data.frame with one row per cell.

swap_axes

logical indicating whether single-cell data should be drawn with one row per feature and one column per cell (as Seurat's DoHeatmap() draws them) instead of one row per cell, set to FALSE by default. The groups and annotations of the cells are then drawn along the x axis (tree_cut_x, annotation_x); other arguments refer to the heatmap as drawn.

transform

"asinh" to transform the values with the inverse hyperbolic sine of each value divided by cofactor before any scaling (the usual transform of cytometry intensities, Bendall et al. 2011), or NULL (default) to draw the values as they are.

cofactor

the cofactor of transform = "asinh": one number (5 by default, as for mass cytometry; about 150 is common for flow cytometry) or one per column, named by column.

scale_q

the quantile of scale_method = "quantile", set to 0.01 by default.

bimodal

TRUE to outline, with a thick border, the cells of a summary of groups of cells in which a feature looks like two populations (e.g. a cluster that combines two smaller ones differing in one or two markers), so that they can be looked into; or the smallest dip (Hartigan and Hartigan 1985) to outline. Set to FALSE by default. Needs the dips of a summary from heat_map_summarise(bimodal = TRUE) (see there for how they are found) or of heat_map_dot(bimodal = TRUE). A cell is outlined when its dip is at least bimodal (0.01 for TRUE) and above the dip that one population of the same number of cells exceeds 1% of the time (0.059 for 100 cells, 0.019 for 1,000, 0.009 for 5,000), so that small groups aren't outlined by chance. Groups whose cells split across several of the features at once - most often whether the features are detected at all, as in a cluster combining CD4 and CD8 T cells, which no single feature shows as two peaks - are outlined in the features that drive the split, from the dip across features (see heat_map_summarise). The legend gains a key, and bar_values_y = "dip" (or bar_values_x) draws the largest dip of each row (column) as bars. heat_map_info()$bimodal returns the dips, the numbers of values they were found from and the cells outlined, and heat_map_describe() names them. The distributions behind each cell (cell_values) show what the dip has found.

style

a style from heat_map_style: settings used for the arguments that aren't given, e.g. text sizes, colours and legend options set once for every heatmap of a report. By default the style set with options(HeatmapR.style = ), if any; FALSE for none.

...

additional arguments passed to heat_map_clust (and on to dist or hclust). Any other arguments are ignored with a warning, which catches misspelled argument names. Note that p (for Minkowski distances) is partially matched to popup_size, so cluster with heat_map_clust() and supply the result to tree_x or tree_y instead.

Value

an object of class heat_map returned invisibly. The object is the recordedplot of the heatmap (so it can still be used with replayPlot), and can be redrawn with print() or plot() or saved with heat_map_save. The data used to construct the heatmap, including row and column orders, cluster assignments, dendrograms and cell colours, can be extracted with heat_map_info.

Author(s)

Dillon Hammill ([email protected])

References

Arthur, D. and Vassilvitskii, S. (2007). k-means++: the advantages of careful seeding. Proceedings of the 18th Annual ACM-SIAM Symposium on Discrete Algorithms (SODA '07), 1027-1035.

Atkins, J. E., Boman, E. G. and Hendrickson, B. (1998). A spectral algorithm for seriation and the consecutive ones problem. SIAM Journal on Computing, 28(1), 297-310. doi:10.1137/S0097539795285771

Bar-Joseph, Z., Gifford, D. K. and Jaakkola, T. S. (2001). Fast optimal leaf ordering for hierarchical clustering. Bioinformatics, 17(suppl 1), S22-S29. doi:10.1093/bioinformatics/17.suppl_1.S22

Bendall, S. C. et al. (2011). Single-cell mass cytometry of differential immune and drug responses across a human hematopoietic continuum. Science, 332(6030), 687-696. doi:10.1126/science.1198704

Correll, M., Moritz, D. and Heer, J. (2018). Value-suppressing uncertainty palettes. Proceedings of the 2018 CHI Conference on Human Factors in Computing Systems. doi:10.1145/3173574.3174216

Croes, G. A. (1958). A method for solving traveling-salesman problems. Operations Research, 6(6), 791-812. doi:10.1287/opre.6.6.791

Felsenstein, J. (1985). Confidence limits on phylogenies: an approach using the bootstrap. Evolution, 39(4), 783-791. doi:10.1111/j.1558-5646.1985.tb00420.x

Garnier, S. et al. viridisLite: colorblind-friendly color maps (lite version). https://CRAN.R-project.org/package=viridisLite

Glasbey, C., van der Heijden, G., Toh, V. F. K. and Gray, A. (2007). Colour displays for categorical images. Color Research and Application, 32(4), 304-309. doi:10.1002/col.20327

Grunau, C., Ozudogru, A. A., Rozhon, V. and Tetek, J. (2023). A nearly tight analysis of greedy k-means++. Proceedings of the 2023 ACM-SIAM Symposium on Discrete Algorithms (SODA 2023), 1012-1070. doi:10.48550/arXiv.2207.07949

Hartigan, J. A. and Hartigan, P. M. (1985). The dip test of unimodality. The Annals of Statistics, 13(1), 70-84. doi:10.1214/aos/1176346577

Hartigan, J. A. and Wong, M. A. (1979). Algorithm AS 136: a k-means clustering algorithm. Applied Statistics, 28(1), 100-108. doi:10.2307/2346830

Hintze, J. L. and Nelson, R. D. (1998). Violin plots: a box plot-density trace synergism. The American Statistician, 52(2), 181-184. doi:10.1080/00031305.1998.10480559

Hyndman, R. J. and Fan, Y. (1996). Sample quantiles in statistical packages. The American Statistician, 50(4), 361-365. doi:10.1080/00031305.1996.10473566

Kaufman, L. and Rousseeuw, P. J. (1990). Finding Groups in Data: An Introduction to Cluster Analysis. Wiley. doi:10.1002/9780470316801

McInnes, L., Healy, J. and Melville, J. (2018). UMAP: uniform manifold approximation and projection for dimension reduction. arXiv:1802.03426. doi:10.48550/arXiv.1802.03426

Murdoch, D. J. and Chow, E. D. (1996). A graphical display of large correlation matrices. The American Statistician, 50(2), 178-180.

Rousseeuw, P. J. (1987). Silhouettes: a graphical aid to the interpretation and validation of cluster analysis. Journal of Computational and Applied Mathematics, 20, 53-65. doi:10.1016/0377-0427(87)90125-7

Shi, J. and Malik, J. (2000). Normalized cuts and image segmentation. IEEE Transactions on Pattern Analysis and Machine Intelligence, 22(8), 888-905. doi:10.1109/34.868688

W3C (2018). Web Content Accessibility Guidelines (WCAG) 2.1. https://www.w3.org/TR/WCAG21/

See Also

heat_map_info, heat_map_save

Examples

heat_map(
  mtcars,
  scale = "column",
  cell_shape = "circle",
  cell_size = TRUE,
  tree_x = TRUE,
  tree_cut_x = 3,
  tree_y = TRUE,
  tree_cut_y = 3,
  bar_values_x = 1:11,
  bar_fill_x = rainbow(11),
  bar_values_y = 1:32,
  bar_fill_y = rainbow(32)
 )

# Diverging colour scale centred at zero for z-scores
hm <- heat_map(
  mtcars,
  scale = "column",
  scale_method = "zscore",
  cell_col_scale = "Blue-Red 3",
  cell_col_scale_center = 0,
  tree = "both",
  tree_cut_y = 4,
  popup = FALSE
)

# Extract cluster assignments and display order
heat_map_info(hm)$row_clusters

# Single cells grouped by cluster, at most 20 cells of each, with their
# sample as an annotation (a data.frame here; a SingleCellExperiment, Seurat
# object or flowSet is read in the same way)
set.seed(1)
cells <- data.frame(
  CD3 = c(rnorm(200, 4), rnorm(30, 1)),
  CD19 = c(rnorm(200, 1), rnorm(30, 4)),
  CD56 = rnorm(230, 2),
  cluster = rep(c("T cells", "B cells"), c(200, 30)),
  sample = sample(c("A", "B"), 230, replace = TRUE)
)
heat_map(
  cells,
  features = c("CD3", "CD19", "CD56"),
  group_by = "cluster",
  group_max = 20,
  annotation_by = "sample",
  popup = FALSE
)

# Number of row clusters chosen by mean silhouette width, rows in spectral
# order (no dendrogram needed for a spectral order)
heat_map(
  mtcars,
  scale = "column",
  tree_cut_y = "auto",
  tree_order_y = "spectral",
  tree_order_x = "spectral",
  popup = FALSE
)

Heatmaps of the same rows side by side, each with its own colour scale

Description

heat_map_align() joins several data sets measured on the same rows

  • e.g. the genes (RNA) and surface proteins (ADT) of the same cells or groups of cells, or the expression and methylation of the same samples - into one heatmap: the rows are lined up, in one order, and each data set is a block of columns with its own colour scale and legend, separated and labelled by name, as ComplexHeatmap's heatmap lists draw them. The rows are clustered (tree = TRUE) or split into k-means clusters (tree_kmeans) on the main data set alone, so its order holds for the others too.

Usage

heat_map_align(
  x,
  main = 1,
  axis = c("x", "y"),
  scale = NULL,
  scale_method = "zscore",
  cell_col_scale = NULL,
  cell_col_scale_limits = NULL,
  cell_col_scale_center = NULL,
  tree = FALSE,
  tree_kmeans = NULL,
  tree_blocks = FALSE,
  dist_method = "euclidean",
  clust_method = "complete",
  tree_order = "default",
  ...
)

Arguments

x

a named list of two or more numeric matrices or data.frames (e.g. from heat_map_summarise or heat_map_score), whose rows are the same and named - matched by name, in the order of the first. With axis = "y" they share their columns instead, and are stacked as blocks of rows.

main

the data set (name or position) whose rows are clustered, set to the first by default.

axis

"x" (default) to place the data sets side by side as blocks of columns, or "y" to stack them as blocks of rows that share their columns (e.g. features as rows and cells as columns).

scale, scale_method

how to scale each data set before it is drawn: scale "column", "row" or NULL (default, no scaling), or a list with one per data set, and scale_method as in heat_map (z-scores by default).

cell_col_scale, cell_col_scale_limits, cell_col_scale_center

the colour scale, limits and centre of each data set: one for all of them, or a list with one per data set (named or in order). By default every data set uses the default colour scale over its own values.

tree

logical, whether to draw a dendrogram of the shared rows (columns with axis = "y") clustered on the main data set, set to FALSE by default (in the order of the first data set).

tree_kmeans

the number of k-means clusters of the shared rows (columns with axis = "y"), found on the main data set, or NULL.

tree_blocks

logical, whether to cluster the columns (rows with axis = "y") within each data set, set to FALSE by default.

dist_method, clust_method, tree_order

how the shared rows are clustered: as dist_method, clust_method and tree_order_y of heat_map.

...

other arguments of heat_map.

Details

Each data set is scaled on its own (scale), so scale = "row" z-scores each row within each block. Columns can be clustered within each block with tree_blocks = TRUE. With axis = "y" the data sets are stacked as blocks of rows instead, sharing their columns, which tree and tree_kmeans then cluster. Every other argument of heat_map can be passed in ..., and replaces the settings of heat_map_align().

Value

an object of class heat_map, as returned by heat_map.

See Also

heat_map (cell_col_blocks_x), heat_map_summarise

Examples

set.seed(1)
groups <- paste0("Group", 1:8)
rna <- matrix(rnorm(8 * 10, 8, 2), 8, dimnames = list(groups, paste0("G", 1:10)))
adt <- matrix(rexp(8 * 5, 1 / 300), 8, dimnames = list(groups, paste0("P", 1:5)))
# Genes and proteins of the same groups, the rows clustered on the genes
heat_map_align(
  list(RNA = rna, ADT = adt),
  scale = "column",
  cell_col_scale = list("viridis", "Blue-Red 3"),
  tree = TRUE,
  popup = FALSE
)

Build a heatmap in the browser

Description

heat_map_app() opens an app in a web browser (or the RStudio or Positron viewer) to build a heatmap without writing code: drop a table or a single-cell file on its start page (or start from data in R or an example), choose what each column does - cells of the heatmap, groups or annotations of the rows - and set any of the arguments of heat_map while the heatmap is drawn again: scaling, clustering and dendrograms, colours, cells and their text, labels, legends, tracks and bars, marks and zooms. Hovering over the heatmap shows the values of its cells, and rows and columns selected on it (by clicking or dragging) can be shown alone, labelled or copied. Each change can be undone, the R code that draws the heatmap again is written beside it, and the heatmap downloads as a PNG, PDF, SVG, TIFF or JPEG image of a chosen size.

Usage

heat_map_app(
  x = NULL,
  ...,
  allow_code = TRUE,
  max_upload = 1024,
  launch.browser = interactive()
)

Arguments

x

data to start with: a matrix, data frame or single-cell object (anything heat_map() draws), or the name of a file to read (as above). Set to NULL by default to start on a page to drop a file or choose an example (tables and single-cell data).

...

settings to start with, named by the arguments of heat_map, e.g. scale = "column".

allow_code

logical indicating whether settings may be R code run in this R session (such as rainbow(5) or x$mpg), set to TRUE by default. Set it to FALSE before hosting the app for other people: settings are then limited to numbers, text, TRUE, FALSE, NA, NULL and c() or list() of them.

max_upload

the size of the largest file that can be uploaded, in megabytes, set to 1024 by default.

launch.browser

whether the app opens in a browser when it runs, as in runApp: TRUE in interactive sessions by default.

Details

Files can be CSV, TSV or other delimited text (.csv, .tsv, .tab or .txt), Excel files (.xlsx or .xls, read with the readxl package), R data (.rds: a matrix, data frame or single-cell object) or AnnData files (.h5ad, read with heat_map_read_h5ad). The first column of a table is used as its row names when it holds unique text. Tables show their columns (one row per row of the table), and their columns can also group the rows (group_by) or annotate them (annotation_by); single-cell data show the chosen features, grouped and annotated by the cells' metadata. Heatmaps can also be dot plots of groups (heat_map_dot) or correlations between the columns (heat_map_cor).

Every argument of heat_map() has a setting, in sections down the side of the page (the most used with plain labels and inputs made for them, the rest under "More settings"), with the argument's name and its documentation, and a search box finds them. Settings left at their defaults are left out of the code. Settings that take R values that belong to the data (e.g. bar_values_y) are R code, run in the R session with the data as x, so that x$mpg gives each row a bar of its mpg.

Value

a Shiny app (from shinyApp), which runs when it is printed (as at the console) or given to shiny::runApp(). The app needs the shiny and bslib packages.

Author(s)

Dillon Hammill ([email protected])

See Also

heat_map, heat_map_html, heat_map_save

Examples

if(interactive() && requireNamespace("shiny", quietly = TRUE) &&
   requireNamespace("bslib", quietly = TRUE)) {
  # Start with mtcars, or upload a file in the app
  heat_map_app()
  # Start from data in R, with some settings
  heat_map_app(mtcars, scale = "column", tree = "both")
}

Arrange heatmaps side by side on shared colour and size scales

Description

heat_map_arrange() redraws several heatmaps - returned by heat_map, heat_map_dot, heat_map_cor or heat_map_align - in one layout, with one set of colour limits (and cell size limits) across them all, so that the same colour means the same value in every panel and panels can be compared by eye: e.g. a heatmap of each condition, or of each sample, drawn separately. Each heatmap keeps its other settings, and its dendrograms and clusters are reused rather than computed again.

Usage

heat_map_arrange(
  ...,
  layout = NULL,
  share = c("colour", "size"),
  popup = TRUE,
  popup_size = NULL
)

Arguments

...

heatmaps (objects of class heat_map), or a list of them.

layout

the layout of the panels, as in heat_map_custom: c(nrow, ncol) or a matrix. By default the heatmaps are drawn side by side (up to three) or in a grid.

share

what the heatmaps share: "colour" (the colour limits) and "size" (the limits of cell sizes, e.g. of dot plots), both by default, or "none".

popup, popup_size

whether to open a new graphics device (in interactive sessions) and its size in inches, by default 6 inches wide and 5 tall for each panel (see heat_map_custom).

Details

The shared colour limits run from the lowest to the highest limit of the heatmaps, centred on the value they were centred on (cell_col_scale_center) when they all share one. Heatmaps with blocks of columns on their own colour scales (heat_map_align()) share the limits of the blocks of the same name. Heatmaps with stepped colour scales (cell_col_scale_breaks) keep their breaks.

Value

a list of the redrawn heatmaps (objects of class heat_map), invisibly.

Author(s)

Dillon Hammill ([email protected])

See Also

heat_map_custom, heat_map_save

Examples

# Two groups of cars on one colour scale
grDevices::pdf(NULL)
merc <- heat_map(mtcars[grepl("Merc", rownames(mtcars)), ], popup = FALSE,
                 title = "Mercedes")
other <- heat_map(mtcars[!grepl("Merc", rownames(mtcars)), ], popup = FALSE,
                  title = "Others")
grDevices::dev.off()
heat_map_arrange(merc, other, popup = FALSE)

Check that the colours of a heatmap can be told apart with colour-vision deficiencies

Description

heat_map_check_colours() simulates how the colours of a heatmap look with the three common colour-vision deficiencies - deuteranopia and protanopia (red-green, about 1 in 12 men of northern European descent) and tritanopia (blue-yellow) - and reports the colours that become hard to tell apart: two levels of an annotation, of the values of non-numeric cells, of stacked bars or of branch colours, and values far apart on a colour scale that end up looking alike. The deficiencies are simulated as Machado, Oliveira and Fernandes (2009) model them (at full severity, in linear RGB, as colorspace::simulate_cvd() does), and colours count as hard to tell apart when their difference in CIELAB (Delta E) falls below min_difference.

Usage

heat_map_check_colours(
  x,
  deficiency = c("deuteranopia", "protanopia", "tritanopia"),
  min_difference = 10
)

Arguments

x

a heatmap (an object of class heat_map), or colours (a vector, named by what they stand for).

deficiency

the colour-vision deficiencies to simulate, all three by default.

min_difference

the smallest difference (CIELAB Delta E) of two colours that count as easy to tell apart, 10 by default. Colours that differ by less than this in normal vision too are reported as such.

Details

Qualitative palettes of more than four or five colours rarely stay apart for every deficiency: colour-blind readers see colours along fewer dimensions. Name the levels in the legend and beside the tracks, or choose colours that differ in lightness as well as hue, e.g. the first eight colours of palette.colors(palette = "Okabe-Ito") (Okabe and Ito 2008; R 4.0.0 or later), given to annotation_colours or cell_col_palette. Colour scales such as "viridis" or "Blue-Red 3" change in lightness from end to end, so they stay readable.

With options(HeatmapR.check_colours = TRUE), heat_map() checks every heatmap it draws and gives a message when colours are hard to tell apart.

Value

a data.frame of class heat_map_colour_check with one row per pair of colours that are hard to tell apart: element (e.g. "annotation cell_type" or "colour scale"), vision ("normal" or the deficiency), the two levels (first and second; positions along the scale for colour scales), their colours and their difference. It prints as a summary.

Author(s)

Dillon Hammill ([email protected])

References

Machado GM, Oliveira MM and Fernandes LAF (2009). A physiologically-based model for simulation of color vision deficiency. IEEE Transactions on Visualization and Computer Graphics 15(6), 1291-1298. doi:10.1109/TVCG.2009.113

Okabe M and Ito K (2008). Color universal design (CUD): how to make figures and presentations that are friendly to colorblind people. https://jfly.uni-koeln.de/color/

See Also

heat_map_describe for alternative text

Examples

# The red and green of matplotlib's palette: apart for most readers, close
# for red-green colour-blind ones
heat_map_check_colours(c(case = "#D62728", control = "#2CA02C", other = "#1F77B4"))

hm <- heat_map(
  mtcars,
  scale = "column",
  annotation_y = data.frame(
    cylinders = factor(mtcars$cyl),
    row.names = rownames(mtcars)
  ),
  annotation_colours = list(cylinders = c("#D62728", "#2CA02C", "#1F77B4")),
  popup = FALSE
)
heat_map_check_colours(hm)

Perform hierarchical clustering for heatmap

Description

Perform hierarchical clustering for heatmap

Usage

heat_map_clust(
  x,
  tree = "row",
  dist = "euclidean",
  method = "complete",
  scale = FALSE,
  cut = NULL,
  order = "default",
  max = 5000,
  ...
)

Arguments

x

matrix-like object to cluster - its numeric columns. Distances, linkage and cuts are computed in compiled code (only a distance function supplied to dist runs in R). With a supplied hclust object and order, the rows of x (or its columns when they don't match) are the leaves of the tree.

tree

indicates whether hierarchical clustering should be performed by "row" or "column". Optionally a custom object of class "dist" (clustered using method) or "hclust" which will be updated with cluster labels as specified by cut. Any clusters already stored in a supplied hclust object are replaced when cut is supplied.

dist

method passed to dist to compute distance matrix, set to "euclidean" by default. Also supports "cosine" for cosine distance (1 - cosine similarity), "pearson", "spearman" or "kendall" for one minus the correlation (rows without variation are treated as uncorrelated), or a function that takes the matrix being clustered (one row per leaf) and returns a dist object or a square matrix of distances. Names ignore case and can be abbreviated (e.g. "pear").

method

agglomeration method, one of the methods of hclust ("ward.D", "ward.D2", "single", "complete", "average", "mcquitty", "median" or "centroid", which can be abbreviated), set to "complete" by default.

scale

logical indicating whether branch heights should be scaled for better visualisation, set to FALSE by default.

cut

value from 0 to less than 1 specifying the tree cutpoint as a proportion of the tree height (for non-cosine distances) or as an absolute cosine distance threshold (when dist = "cosine"), a value greater than or equal to 1 indicating the number of desired clusters, or "auto" to choose the number of clusters from the data. An automatic cut tries 2 to 20 clusters and keeps the one with the largest mean silhouette width (Rousseeuw 1987: each leaf compares its mean distance to the rest of its cluster with that to the nearest other cluster, from -1 to 1), unless no cut reaches 0.25 - the width below which Kaufman and Rousseeuw (1990) find no substantial structure - when the tree isn't cut. Trees with more than max leaves are scored on a sample of max leaves (fixed seed); 5000 leaves take well under a second.

order

how the branches of the dendrogram are ordered: "default" keeps the order from hclust, "olo" flips branches to minimise the distances between neighbouring leaves (optimal leaf ordering, Bar-Joseph et al. 2001) and "mean" orders branches by their mean values (heatmap orders them by the sum of their leaves' means instead, which favours small branches). "spectral" orders branches by the mean position of their leaves in a spectral order (recursive spectral bisection of the graph joining each leaf to its 6 nearest neighbours; Shi and Malik 2000, Atkins et al. 1998), so that gradients and trajectories run in one direction across the dendrogram. "peak" orders branches by the mean position of their leaves' maxima along the columns (ties by the position of their minima), so that features peaking early come first, e.g. along pseudotime (see heat_map_smooth). A numeric vector with one value per row orders branches by the mean value of their leaves. Optimal leaf ordering is exact for up to 4000 leaves, which takes well under a second; its time grows with the cube of the number of leaves (and its memory with the square), so larger trees are ordered in blocks (of 4000 leaves, down to 100 for the largest trees), each ordered exactly, with the blocks then ordered and turned to meet their neighbours. 200,000 leaves take about a second.

max

the largest number of rows (or columns) clustered exactly, set to 5000 by default. Exact clustering needs the distances between every pair of rows, so its memory and time grow with the square of their number. Larger data is clustered in two stages: a sample of max rows (drawn with a fixed seed, so the result is the same each time) is clustered exactly and its dendrogram split into groups of about 200 rows of the data, every row joins the group of its nearest group medoid, and each group is clustered exactly beneath the sample's dendrogram. The dendrogram then shows the structure of the whole data down to the groups, and within each group: 100,000 rows take about half a second. Set to Inf to always cluster exactly.

...

additional arguments passed to dist (e.g. p) or hclust (members); others are ignored with a warning.

Details

Distances are computed as dist and cor compute them. Missing and infinite values are left out of each pair of rows: sums over the remaining values are scaled up to all the columns (as dist scales them) and correlations use the values both rows have (as cor(use = "pairwise.complete.obs"); Spearman's ranks the values of each pair); rows that share no values can't be clustered. Kendall's tau is computed by Knight's (1966) algorithm. Single linkage is computed from a minimum spanning tree (Prim's algorithm, Prim 1957, which needs no matrix of distances; Gower and Ross 1969) and centroid and median linkage by the generic algorithm of Mullner (2011), which merges the closest pair of clusters at every step, both giving the tree hclust gives when the distances are distinct. Complete, average, McQuitty and Ward linkage are computed by the nearest-neighbour chain algorithm (Murtagh 1983; Mullner 2011), which builds the same tree as hclust when the distances are distinct. When distances are tied (common for integer, binary or rounded data), more than one tree is correct and the two can choose differently between tied merges, so the tree - and the branches above the tied merges - can differ from the one hclust returns while being equally valid. Distances to merged clusters are updated by the formula of Lance and Williams (1967); Murtagh and Contreras (2012) give an overview of these algorithms.

Value

object of class hclust which describes the tree produced by the clustering process. Branch heights are rescaled to the range [0, 1] for display. When cut is supplied, the returned object also contains a cut element holding the cluster assigned to each leaf in dendrogram order (an automatic cut also adds an auto_cut element: the number of clusters k, 1 when the tree isn't cut, the mean silhouette width of each cut tried and the number of leaves scored). A tree clustered in two stages (more than max rows) has a two_stage element giving the size of the sample and the number of groups.

Author(s)

Dillon Hammill ([email protected])

References

Atkins, J. E., Boman, E. G. and Hendrickson, B. (1998). A spectral algorithm for seriation and the consecutive ones problem. SIAM Journal on Computing, 28(1), 297-310. doi:10.1137/S0097539795285771

Bar-Joseph, Z., Gifford, D. K. and Jaakkola, T. S. (2001). Fast optimal leaf ordering for hierarchical clustering. Bioinformatics, 17(suppl 1), S22-S29. doi:10.1093/bioinformatics/17.suppl_1.S22

Croes, G. A. (1958). A method for solving traveling-salesman problems. Operations Research, 6(6), 791-812. doi:10.1287/opre.6.6.791

Gower, J. C. and Ross, G. J. S. (1969). Minimum spanning trees and single linkage cluster analysis. Applied Statistics, 18(1), 54-64. doi:10.2307/2346439

Kaufman, L. and Rousseeuw, P. J. (1990). Finding Groups in Data: An Introduction to Cluster Analysis. Wiley. doi:10.1002/9780470316801

Knight, W. R. (1966). A computer method for calculating Kendall's tau with ungrouped data. Journal of the American Statistical Association, 61(314), 436-439. doi:10.1080/01621459.1966.10480879

Lance, G. N. and Williams, W. T. (1967). A general theory of classificatory sorting strategies: 1. Hierarchical systems. The Computer Journal, 9(4), 373-380. doi:10.1093/comjnl/9.4.373

McInnes, L., Healy, J. and Melville, J. (2018). UMAP: uniform manifold approximation and projection for dimension reduction. arXiv:1802.03426. doi:10.48550/arXiv.1802.03426

Mullner, D. (2011). Modern hierarchical, agglomerative clustering algorithms. arXiv:1109.2378. doi:10.48550/arXiv.1109.2378

Murtagh, F. (1983). A survey of recent advances in hierarchical clustering algorithms. The Computer Journal, 26(4), 354-359. doi:10.1093/comjnl/26.4.354

Murtagh, F. and Contreras, P. (2012). Algorithms for hierarchical clustering: an overview. WIREs Data Mining and Knowledge Discovery, 2(1), 86-97. doi:10.1002/widm.53

Prim, R. C. (1957). Shortest connection networks and some generalizations. Bell System Technical Journal, 36(6), 1389-1401. doi:10.1002/j.1538-7305.1957.tb01515.x

Rousseeuw, P. J. (1987). Silhouettes: a graphical aid to the interpretation and validation of cluster analysis. Journal of Computational and Applied Mathematics, 20, 53-65. doi:10.1016/0377-0427(87)90125-7

Shi, J. and Malik, J. (2000). Normalized cuts and image segmentation. IEEE Transactions on Pattern Analysis and Machine Intelligence, 22(8), 888-905. doi:10.1109/34.868688

Examples

# Hierarchical clustering
heat_map_hclust <- heat_map_clust(mtcars, cut = 5)

# Number of clusters chosen by mean silhouette width
heat_map_hclust <- heat_map_clust(scale(mtcars), cut = "auto")
heat_map_hclust$auto_cut$k

Indicate when a heatmap is complete and ready for saving

Description

Indicate when a heatmap is complete and ready for saving

Usage

heat_map_complete()

Value

No return value, called for side effects.

Author(s)

Dillon Hammill ([email protected])

Examples

# Save heatmap
heat_map_save(file.path(tempdir(), "Heatmap.png"),
height = 7, 
width = 15)

# Custom layout
heat_map_layout(layout = c(1,2))

# Construct raw heatmap
heat_map(iris[1:10,],
scale = FALSE,
title = "Iris Raw Heatmap",
axis_label_x = "Plant Parameter",
axis_label_y = "Row ID")

# Construct scaled heatmap
heat_map(iris[1:10,],
scale = "column",
title = "Iris Scaled Heatmap",
axis_label_x = "Plant Parameter",
axis_label_y = "Row ID")

# Signal completion
heat_map_complete()

Heatmaps of the make-up of samples: the share of each group of cells

Description

heat_map_composition() counts the cells of each group (e.g. cell type or cluster) in each sample and draws the share of each sample's cells in each group, one row per sample, with the samples clustered by their make-up and annotated by their metadata (e.g. condition or donor) - the composition heatmap of cohort studies. Only the metadata of the cells is read, so any single-cell data, or a data.frame of the cells' metadata, can be given.

Usage

heat_map_composition(
  x,
  group_by,
  sample_by,
  annotation_by = NULL,
  values = c("proportion", "percent", "count", "clr"),
  bars = TRUE,
  tree_y = TRUE,
  ...
)

Arguments

x

single-cell data (see heat_map) or a data.frame of the metadata of the cells, one row per cell.

group_by

the group of each cell, drawn as columns: a column of the metadata (or several, combined), or one value per cell.

sample_by

the sample of each cell, drawn as rows, as for group_by.

annotation_by

columns of the metadata that describe the samples (e.g. "condition"), drawn as annotation tracks beside the rows; a column with more than one value in a sample is an error.

values

what each cell of the heatmap shows: "proportion" (default, the share of the sample's cells), "percent", "count" (the number of cells) or "clr" (the centred log-ratio, on a diverging colour scale centred at 0).

bars

logical, whether to draw the number of cells of each sample as bars beside the rows, set to TRUE by default.

tree_y

logical, whether to cluster the samples, set to TRUE by default.

...

other arguments of heat_map, which replace those set here (e.g. tree_x = TRUE to cluster the groups, or cell_text = TRUE to write the values in the cells).

Details

Shares are compositions - they add up to 1 in each sample, so one group growing shrinks the others. values = "clr" draws the centred log-ratio of the counts instead (the log of each group's share less the mean log share of the sample, with half a cell added to every count so that empty groups have a finite log), the usual transform for comparing compositions (Aitchison 1982): a group's value no longer depends on the others, and samples are clustered on distances suited to compositions.

Value

an object of class heat_map, as returned by heat_map; heat_map_info()$data holds the values, one row per sample.

Author(s)

Dillon Hammill ([email protected])

References

Aitchison J (1982). The statistical analysis of compositional data. Journal of the Royal Statistical Society: Series B 44(2), 139-160. doi:10.1111/j.2517-6161.1982.tb01195.x

See Also

heat_map_summarise (stack_by) for the make-up of groups as stacked bars

Examples

cells <- heat_map_example("rna")
heat_map_composition(
  cells,
  group_by = "cell_type",
  sample_by = "sample",
  annotation_by = "condition",
  popup = FALSE
)

Heatmaps of the differences between two conditions in each group of cells

Description

heat_map_contrast() compares two conditions (e.g. treated and control) in each group of cells (e.g. cell type or cluster) and draws the difference of each feature - its log fold change - in each group, on a diverging colour scale, with stars where it is significant. The test is a pseudobulk test across samples: the cells of each group in each sample are summarised into one value, and the samples (e.g. donors) are the replicates, so that the thousands of cells of a sample don't count as independent observations - tests of single cells find nearly every gene significant with enough cells, while only differences that hold from one sample to the next are real (Squair et al. 2021).

Usage

heat_map_contrast(
  x,
  group_by,
  condition_by,
  sample_by,
  features = NULL,
  assay = NULL,
  contrast = NULL,
  values = c("mean", "logcpm"),
  transform = NULL,
  cofactor = 5,
  min_cells = 10,
  min_counts = 10,
  n = 5,
  stars = c(0.05, 0.01, 0.001),
  draw = TRUE,
  ...
)

Arguments

x

single-cell data (see heat_map).

group_by

the group of each cell (e.g. its cell type): a column of the metadata, several, or one value per cell. Each group is a row of the heatmap.

condition_by

the condition of each cell, as for group_by; each sample must be in one condition.

sample_by

the sample of each cell (e.g. the donor), as for group_by: the replicates of the test.

features

the features to test and draw (names, indices or a named list of groups of features), or NULL (default) to test every feature and draw the n with the smallest adjusted p-values in each group.

assay

the assay of single-cell objects (see heat_map).

contrast

the two conditions compared, as c(test, reference); by default the second level of the conditions against the first. The differences are test minus reference.

values

"mean" or "logcpm" (see Details).

transform, cofactor

the transform of the values of the cells before they are summarised, e.g. "asinh" for cytometry (see heat_map_dot).

min_cells

the smallest number of cells of a group in a sample for the sample to be compared, 10 by default.

min_counts

with values = "logcpm", the counts a feature needs in enough samples to be tested, 10 by default (see Details).

n

the number of features drawn for each group when features is NULL, 5 by default.

stars

the adjusted p-values below which cells get one, two and three stars, c(0.05, 0.01, 0.001) by default; NULL for no stars.

draw

logical, whether to draw the heatmap (default) or only return the results.

...

other arguments of heat_map, which replace those set here.

Details

For each group, the samples of the two conditions with at least min_cells cells in the group are compared feature by feature with a moderated t-test (Smyth 2004): the variance of each feature among the samples of its condition is shrunk towards a prior estimated from all the features of the group, which steadies tests of the few samples that experiments have. The prior's degrees of freedom and scale are found by the method of moments on the log variances, as Smyth (2004) describes. The results are those of limma's lmFit() and eBayes() on the same pseudobulk values (compared as a black box), except that features whose variance is zero are left out of the estimation of the prior (limma moves them just above zero), and features with the same value in every sample compared (e.g. not detected in the group) aren't tested. The p-values are adjusted within each group for the features tested (Benjamini and Hochberg 1995).

values = "mean" (default) compares the mean of each sample's cells

  • of log-normalised values (e.g. the logcounts of a SingleCellExperiment), or of transformed cytometry intensities (transform = "asinh") - so the difference is a log fold change in the units of the data. values = "logcpm" sums the counts of each sample's cells (assay = "counts") and compares their log2 counts per million, as limma-voom and edgeR-based pseudobulk analyses do; the features with fewer than min_counts counts in as many samples as the smaller condition has aren't tested, as edgeR's filterByExpr() leaves them out, since the logs of a few counts vary too little from one sample to the next for their variances to be trusted.

Value

With draw = TRUE, the heatmap (an object of class heat_map) with the results in its "contrast" attribute, invisibly; with draw = FALSE, the results: a data.frame of class heat_map_contrast with one row per group and feature tested - group, feature, logfc (test minus reference), t (the moderated t statistic), p_value, p_adj, mean_test, mean_reference, the numbers of samples of each condition compared (samples_test, samples_reference) and cells.

Author(s)

Dillon Hammill ([email protected])

References

Smyth GK (2004). Linear models and empirical Bayes methods for assessing differential expression in microarray experiments. Statistical Applications in Genetics and Molecular Biology 3(1), Article 3. doi:10.2202/1544-6115.1027

Squair JW et al. (2021). Confronting false discoveries in single-cell differential expression. Nature Communications 12, 5692. doi:10.1038/s41467-021-25960-2

Benjamini Y and Hochberg Y (1995). Controlling the false discovery rate: a practical and powerful approach to multiple testing. Journal of the Royal Statistical Society: Series B 57(1), 289-300. doi:10.1111/j.2517-6161.1995.tb02031.x

See Also

heat_map_markers for markers of each group against the other cells, heat_map_composition for differences in the make-up of samples

Examples

# HLA-DR rises in clusters C5 and C6 of the stimulated samples
events <- heat_map_example("cytometry")
heat_map_contrast(
  events,
  group_by = "cluster",
  condition_by = "condition",
  sample_by = "sample",
  features = c("CD3", "CD4", "CD8", "CD19", "CD14", "HLA-DR", "CD45RA"),
  transform = "asinh",
  popup = FALSE
)

Correlation heatmaps with ellipses, numbers and dendrograms

Description

heat_map_cor() draws a correlation matrix as a heatmap whose rows and columns share one order, so the diagonal runs from the top left to the bottom right and each triangle can show the correlations in a different way. By default the lower triangle shows ellipses (Murdoch and Chow 1996), whose shape follows the correlation (rising to the right for positive correlations, falling for negative ones and narrower the stronger the correlation), the upper triangle the correlation coefficients written in their colours, and the diagonal the names of the variables, with the variables clustered so that correlated variables sit together.

Usage

heat_map_cor(
  x,
  method = c("pearson", "spearman", "kendall"),
  use = "pairwise.complete.obs",
  lower = "ellipse",
  upper = "number",
  diag = NULL,
  tree = TRUE,
  clust_method = "average",
  ...
)

Arguments

x

a numeric matrix or data.frame whose columns are correlated with cor (non-numeric columns are left out), or a correlation matrix (square and symmetric, with values between -1 and 1 and ones on the diagonal), which is used as it is.

method

the correlation coefficient computed by cor, either "pearson" (default), "spearman" or "kendall".

use

how cor handles missing values, set to "pairwise.complete.obs" by default.

lower

the shape of the cells below the diagonal, set to "ellipse" by default.

upper

the shape of the cells above the diagonal, set to "number" by default.

diag

the cells on the diagonal: "names" writes the names of the variables there instead of beside the axes, or any of the shapes. Set to "names" by default when lower and upper differ, and to their shape otherwise.

tree

logical indicating whether the variables should be clustered and their dendrograms drawn, set to TRUE by default. Otherwise the variables are kept in the order of x, the first at the top left.

clust_method

the agglomeration method passed to hclust, set to "average" by default.

...

additional arguments passed to heat_map, which replace the defaults chosen here, e.g. cell_col_scale, tree_cut_x and tree_cut_y, or round for the number of decimal places of the coefficients. Arguments that reorder the dendrograms (e.g. tree_order_x) would separate the rows from the columns and break the triangles.

Details

The variables are clustered with hclust on one minus their correlations (1 - r), and the same dendrogram orders the rows and columns. Any shape can be used in either triangle (see cell_shape in heat_map): "ellipse", "number", "circle" and "diamond" (sized by the absolute correlation, as in corrplot), "rect" (full cells) or "none" to leave a triangle empty.

Value

a heat_map object (see heat_map) whose data is the correlation matrix.

Author(s)

Dillon Hammill ([email protected])

References

Murdoch, D. J. and Chow, E. D. (1996). A graphical display of large correlation matrices. The American Statistician, 50(2), 178-180.

Wei, T. and Simko, V. corrplot: visualization of a correlation matrix. https://CRAN.R-project.org/package=corrplot

See Also

heat_map

Examples

# Ellipses below the diagonal, coefficients above
heat_map_cor(mtcars, popup = FALSE)

# Ellipses throughout, cut into three groups of variables
heat_map_cor(
  mtcars,
  upper = "ellipse",
  tree_cut_x = 3,
  tree_cut_y = 3,
  popup = FALSE
)

# Rank correlations as circles in the lower triangle only
heat_map_cor(
  mtcars,
  method = "spearman",
  lower = "circle",
  upper = "none",
  popup = FALSE
)

Create a custom heatmap plot layout

Description

heat_map_custom() is similar to heat_map_save() with the exception that it doesn't write the plot to a file. heat_map_custom() opens a new graphics device and sets the desired layout in preparation for the addition of heatmaps and other plot objects. Once the custom plot is full users MUST run heat_map_complete() to close the graphics device and reset any heat_map() related settings (see example).

Usage

heat_map_custom(popup = TRUE, popup_size = c(8, 8), layout = NULL, ...)

Arguments

popup

logical indicating whether a popup graphics device should be opened, set to TRUE by default. Popups are only opened in interactive sessions.

popup_size

indicates the size of the popup graphics device in inches, set to c(8,8) by default.

layout

either a vector of the form c(nrow, ncol) defining the dimensions of the plot or a matrix defining a more sophisticated layout (see layout). Vectors can optionally contain a third element to indicate whether plots should be placed in row (1) or column (2) order, set to row order by default.

...

additional arguments passed to heat_map_new().

Value

No return value, called for side effects.

Author(s)

Dillon Hammill ([email protected])

See Also

heat_map_save

heat_map_new

heat_map_complete

Examples

heat_map_custom(
  popup = FALSE,
  layout = c(1,2)
)
heat_map(
  mtcars
)
plot(
  mtcars[, 1:2],
  pch = 16
)
heat_map_complete()

Extract the contents of a heatmap as tidy data

Description

heat_map_data() returns what a heatmap shows as a data.frame with one row per cell, row, column or dendrogram segment, positioned as they are in the heatmap. Use it to rebuild or extend a heatmap with ggplot2 or other tools, to add to a heatmap with base graphics, or to export the displayed values, colours and clusters.

Usage

heat_map_data(x, what = c("cells", "rows", "columns", "tree_x", "tree_y"))

Arguments

x

object of class heat_map returned by heat_map.

what

the table to return: "cells" (the default), "rows", "columns", or the dendrogram segments "tree_x" (columns) or "tree_y" (rows).

Details

Positions are given in two ways. display_row and display_col count rows from the top and columns from the left of the heatmap. x and y are the centres of the cells in the heatmap's plot co-ordinates - one unit per cell plus any gaps between clusters, with y increasing upwards - so ggplot(cells, aes(x, y)) + geom_tile() lays the cells out as in the heatmap, and base graphics drawn on the heatmap's device after heat_map() land on its cells.

Value

a data.frame:

  • "cells": one row per cell, from the top left of the heatmap along each row, with the row and column names, their row_index and col_index in the original data, display_row, display_col, x and y, the displayed value (after any scaling), level for non-numeric columns, the fill colour, relative size and shape (see cell_shape in heat_map), split_value and split_colour for split cells (cell_split), and the row_cluster and col_cluster when rows or columns are split into clusters.

  • "rows", "columns": one row per row (from the top) or column (from the left), with its name, index in the original data, display position, centre (y or x), axis text (label), cluster when there are clusters, and the values of any annotations (annotation_y or annotation_x).

  • "tree_x", "tree_y": one row per dendrogram segment, from (x, y) to (xend, yend). Along the heatmap the segments are in plot co-ordinates; across it they are the branch heights, from 0 at the leaves. Branch support is added as support (see tree_support_x), and with clusters the cluster below each segment as cluster (NA for the branches joining clusters, as tree_col_x colours them). NULL when the heatmap has no such dendrogram.

Author(s)

Dillon Hammill ([email protected])

See Also

heat_map_info for the same information as matrices and vectors, and heat_map_grob to combine heatmaps with ggplot2 plots.

Examples

hm <- heat_map(
  mtcars,
  scale = "column",
  tree_y = TRUE,
  tree_cut_y = 3,
  popup = FALSE
)
cells <- heat_map_data(hm)
head(cells)

# The displayed values, rows in the order of the heatmap
rows <- heat_map_data(hm, "rows")
head(rows)

# Mark the highest value of each column on the heatmap
top <- cells[ave(cells$value, cells$column, FUN = max) == cells$value, ]
points(top$x, top$y, pch = 8, col = "white")

Describe a heatmap in plain language

Description

heat_map_describe() writes a description of a heatmap in plain language - its size and scaling, what the colours show, the most extreme values, how the rows and columns are clustered and what sets each cluster apart, and any annotations, bars, labels or panels. Use it as alternative text for people who use screen readers (e.g. the fig.alt chunk option of R Markdown and Quarto), as a starting point for a figure legend, or to check what a heatmap shows.

Usage

heat_map_describe(x, digits = 3, max_groups = 8)

Arguments

x

object of class heat_map returned by heat_map.

digits

number of significant digits of the values, set to 3 by default.

max_groups

the largest number of clusters to describe one by one, set to 8 by default. With more clusters only their sizes are given.

Details

Clusters are described by the columns (for row clusters) or rows (for column clusters) in which their mean is highest and lowest. Numbers are the values displayed in the heatmap, after any scaling.

Value

a character string of class heat_map_description, printed as wrapped text. Use as.character() for the plain string.

Author(s)

Dillon Hammill ([email protected])

Examples

hm <- heat_map(
  mtcars,
  scale = "zscore",
  tree = "both",
  tree_cut_y = 3,
  legend_title = "z-score",
  title = "mtcars",
  popup = FALSE
)
heat_map_describe(hm)

Dot plots of the features of groups of cells

Description

heat_map_dot() draws a dot plot of single-cell data, with one row per group of cells (e.g. per cluster) and one column per feature: the colour of each dot is the mean of the feature in the group, scaled within each feature, and its area the proportion of the group's cells in which the feature is detected, as Seurat's DotPlot() (Hao et al. 2024) and scanpy's dotplot() (Wolf et al. 2018) draw them. The means and proportions are found in one pass over the data, from the non-zero values of sparse data (see heat_map_summarise). The plot is a heatmap of circles, so every option of heat_map can be added through ..., e.g. a dendrogram of the groups (tree_y = TRUE) or annotations.

Usage

heat_map_dot(
  x,
  features = NULL,
  group_by = NULL,
  split_by = NULL,
  assay = NULL,
  scale = "zscore",
  scale_limits = NULL,
  threshold = 0,
  dot_min = 0,
  swap_axes = FALSE,
  bimodal = FALSE,
  transform = NULL,
  cofactor = 5,
  marker_colour = "logfc",
  marker_size = "p_adj",
  ...
)

Arguments

x

single-cell data, a matrix or a data.frame (see heat_map), or the markers returned by heat_map_markers for a dot plot of markers.

features

the features to show (see heat_map). A named list of features, or the markers returned by heat_map_markers, groups the columns, labelled by group (as scanpy's var_group_positions brackets do).

group_by

the group of each cell, the name of a column of its metadata or a vector (see heat_map). Each group is one row. Several column names give one row per combination, e.g. c("cell_type", "condition") for each cell type in each condition: the rows are grouped by the first variable (in labelled strips) and each row is labelled by the others.

split_by

a variable with two values (e.g. two conditions, or two samples) by which to split each dot down the middle: the name of a column of the cells' metadata or a vector with one value per cell, as group_by. The left half of each dot shows the cells of the group with the first value (the first factor level, or first in sorted order) and the right half those with the second, each half with its own colour and size, on the same scales: the means are scaled within each feature across the groups and both values. Cells without a value are left out, and the halves of groups without cells are not drawn. Set to NULL by default for whole dots.

assay

the values of single-cell data to show (see heat_map).

scale

how the means are scaled within each feature for their colour: "zscore" (the default) for z-scores across the groups, clipped to scale_limits, as Seurat's DotPlot() scales them, "range" to scale them from 0 to 1, as scanpy's standard_scale = "var" does, or "none" to show the means themselves.

scale_limits

the limits that scaled means are clipped to, set to c(-2.5, 2.5) for z-scores by default (Seurat's col.min and col.max) and not clipped otherwise.

threshold

values above threshold are counted as detected, set to 0 by default - after transform.

dot_min

the smallest proportion of a group's cells detected for a dot to be drawn, set to 0 by default (as Seurat's dot.min).

swap_axes

logical indicating whether the features should be drawn as rows and the groups as columns, set to FALSE by default.

bimodal

TRUE to outline, with a thick border, the dots of groups in which a feature looks like two populations among the cells it is detected in (e.g. a cluster combining two smaller ones), from the dip (Hartigan and Hartigan 1985) of each feature in each group; or the smallest dip to outline. Set to FALSE by default. See heat_map_summarise for how the dips are found and heat_map for when a dot is outlined. Can't be combined with split_by.

transform

"asinh" to transform the values of the cells with the inverse hyperbolic sine of each value divided by cofactor before their means are taken (the usual transform of cytometry intensities), or NULL (default) to use the values as they are, as in heat_map_summarise. The zeros of sparse data stay zeros, so they are transformed without a dense copy.

cofactor

the cofactor of transform = "asinh": one number (5 by default, as for mass cytometry; about 150 is common for flow cytometry) or one per feature, named by feature.

marker_colour, marker_size

for a dot plot of markers (x from heat_map_markers), the columns of the markers that colour and size the dots: "logfc" (the default colour, on a diverging scale centred at 0), "auc" (centred at 0.5, and sized from 0.5), "p_adj" (the default size) or "p_value" (as -log10(p)), "mean_in", "mean_out", "detected_in" or "detected_out". Each column of the plot is a feature, as features chooses them (by default the top markers of each group, grouped by the group they mark), and each row a group; a feature has a dot in each group where it passed the filters of heat_map_markers (all of them with min_detected = 0 and min_logfc = -Inf). The colours are not scaled unless scale is given, and dot_min leaves out the dots of groups in which fewer cells are detected (detected_in).

...

other arguments passed to heat_map, e.g. cell_col_scale, tree_y or popup. They replace the settings of the dot plot of the same name. bar_values_y = "n" (bar_values_x with swap_axes = TRUE) draws the number of cells in each group as bars.

Value

an object of class heat_map, as returned by heat_map, whose data are the scaled means (of the first value of split_by, whose second is in cell_split). The means, the proportions detected and the cells in each group are returned by heat_map_summarise.

Author(s)

Dillon Hammill ([email protected])

References

Hao, Y. et al. (2024). Dictionary learning for integrative, multimodal and scalable single-cell analysis. Nature Biotechnology, 42(2), 293-304. doi:10.1038/s41587-023-01767-y

Hartigan, J. A. and Hartigan, P. M. (1985). The dip test of unimodality. The Annals of Statistics, 13(1), 70-84. doi:10.1214/aos/1176346577

Wolf, F. A., Angerer, P. and Theis, F. J. (2018). SCANPY: large-scale single-cell gene expression data analysis. Genome Biology, 19, 15. doi:10.1186/s13059-017-1382-0

See Also

heat_map_markers, heat_map_summarise

Examples

set.seed(1)
cells <- data.frame(
  CD3 = c(rexp(200, 0.5), rexp(60, 4)) * rbinom(260, 1, 0.7),
  CD19 = c(rexp(200, 4), rexp(60, 0.5)) * rbinom(260, 1, 0.7),
  NKG7 = rexp(260, 1) * rbinom(260, 1, 0.3),
  cluster = rep(c("T cells", "B cells"), c(200, 60))
)
heat_map_dot(cells, group_by = "cluster", popup = FALSE)

# Features in groups, scaled from 0 to 1 within each feature
heat_map_dot(
  cells,
  features = list(T = c("CD3", "NKG7"), B = "CD19"),
  group_by = "cluster",
  scale = "range",
  popup = FALSE
)

# Markers of each cluster, coloured by log fold change and sized by
# -log10 of the adjusted p-value
markers <- heat_map_markers(cells, group_by = "cluster", n = 2,
                            min_detected = 0, min_logfc = -Inf)
heat_map_dot(markers, popup = FALSE)

# Each dot split by condition - control on the left, treated on the right
cells$condition <- rep(c("control", "treated"), 130)
heat_map_dot(cells, group_by = "cluster", split_by = "condition",
             popup = FALSE)

# Blood cells, with the dots of groups whose cells look like two
# populations outlined
blood <- heat_map_example("rna", n = 1500)
heat_map_dot(blood, features = attr(blood, "markers"),
             group_by = "cell_type", bimodal = TRUE, popup = FALSE)

Downsample cells within groups

Description

heat_map_downsample() keeps at most n cells of each group, and every cell of smaller groups, so that small clusters stay visible next to large ones in a heatmap of single cells. The cells are drawn with a fixed seed, so the same cells are kept each time, and the random numbers of the session are left as they were. heat_map(..., group_max = n) downsamples the groups of group_by in this way.

Usage

heat_map_downsample(groups, n = 500, seed = 2357)

Arguments

groups

a vector with the group of each cell (e.g. its cluster). Cells without a group (NA) are left out.

n

the largest number of cells to keep from each group, set to 500 by default.

seed

the random seed for the draw, set to 2357 by default.

Value

the indices of the cells kept, in increasing order.

Author(s)

Dillon Hammill ([email protected])

See Also

heat_map

Examples

groups <- rep(c("T cells", "B cells", "NK cells"), c(2000, 300, 40))
keep <- heat_map_downsample(groups, n = 100)
table(groups[keep])

Simulated single-cell data for examples

Description

heat_map_example() simulates the single-cell data used in the examples and guides: an RNA experiment of blood cells, cytometry events in clusters, or cells along a branching trajectory. The data are simulated with a fixed seed, so they are the same each time, without changing the random numbers of the session.

Usage

heat_map_example(
  type = c("rna", "cytometry", "trajectory"),
  class = c("data.frame", "SingleCellExperiment"),
  n = NULL
)

Arguments

type

the kind of data: "rna" (default), "cytometry" or "trajectory".

class

"data.frame" (default) for a data.frame with one row per cell, holding the values of each feature followed by the cells' metadata, or "SingleCellExperiment" (for "rna" and "trajectory"; needs the SingleCellExperiment package) with genes as rows, sparse counts and logcounts assays and the metadata in colData().

n

the number of cells (or events), set to NULL by default for 3,000 cells of "rna", 200,000 events of "cytometry" or 4,000 cells of "trajectory".

Details

"rna"

3,000 peripheral blood cells of six types (CD4 T, CD8 T, B, NK, CD14 Mono and DC) from four donors in two conditions (donors 1 and 2 "control", 3 and 4 "treated"), with 2,000 genes. Four genes mark each cell type (e.g. CD3E, IL7R, CCR7 and LDHB the CD4 T cells; the list is in the "markers" attribute), with little expression in the other cells, and the others are background. Counts are Poisson, with a size factor for each cell, and log-normalised to 10,000 counts per cell (log1p(counts / total * 10000)).

"cytometry"

200,000 events of 12 markers (CD3, CD4, CD8, CD19, CD20, CD56, CD16, CD14, CD11c, HLA-DR, CD45RA and CCR7) in eight clusters (C1 to C8), from eight samples (S1 to S8) in two conditions (S1 to S4 "control", S5 to S8 "stimulated"). The intensities are raw, as from a mass cytometer: asinh(x / 5) (the usual transform, Bendall et al. 2011) recovers the simulated levels. Cluster C3 is twice as common in the stimulated samples, and HLA-DR rises in clusters C5 and C6 under stimulation.

"trajectory"

4,000 cells of a branching trajectory with 30 genes (log-transformed counts, log1p()), in a random order (the genes are the first 30 columns of the data.frame). Every cell has a pseudotime from 0 to 1, and lineage1 and lineage2 give the pseudotime of each lineage, as slingshot (Street et al. 2018) gives them (missing for cells outside the lineage). The lineages share their start and branch at a pseudotime of 0.4; each gene peaks at its own point, and some genes peaking after the branch are expressed in one lineage only.

Value

the cells as a data.frame or SingleCellExperiment. The metadata columns are cell_type, sample and condition ("rna"); cluster, sample and condition ("cytometry"); and pseudotime, lineage1 and lineage2 ("trajectory"). For "rna" the marker genes of each cell type are a named list in the "markers" attribute of the data.frame, or in metadata()$markers of the SingleCellExperiment.

Author(s)

Dillon Hammill ([email protected])

References

Bendall, S. C. et al. (2011). Single-cell mass cytometry of differential immune and drug responses across a human hematopoietic continuum. Science, 332(6030), 687-696. doi:10.1126/science.1198704

Street, K. et al. (2018). Slingshot: cell lineage and pseudotime inference for single-cell transcriptomics. BMC Genomics, 19, 477. doi:10.1186/s12864-018-4772-0

See Also

heat_map, heat_map_dot, heat_map_markers, heat_map_summarise, heat_map_smooth

Examples

# Blood cells: the marker genes of each cell type in each cell
cells <- heat_map_example("rna")
markers <- attr(cells, "markers")
heat_map(cells, features = markers, group_by = "cell_type",
         group_max = 100, axis_text_y = NA, popup = FALSE)
heat_map_dot(cells, features = markers, group_by = "cell_type",
             popup = FALSE)

# Cytometry: the scaled median of each marker in each cluster, with the
# events of each condition in each cluster
events <- heat_map_example("cytometry", n = 20000)
medians <- heat_map_summarise(events, group_by = "cluster",
                              fun = "median", transform = "asinh",
                              scale = "quantile", stack_by = "condition")
heat_map(medians, tree = "both", bar_values_y = "n",
         bar_type_y = "stack", popup = FALSE)

# A trajectory: genes along pseudotime, ordered by when they peak
traj <- heat_map_example("trajectory")
smooth <- heat_map_smooth(traj, along = "pseudotime", features = 1:30,
                          bins = 50)
heat_map(smooth, swap_axes = TRUE, scale = "row", tree_order_y = "peak",
         annotation_by = "pseudotime", axis_text_x = NA, popup = FALSE)

Convert a heatmap into a grob for grid and ggplot2 layouts

Description

heat_map_grob() turns a heatmap into a grid graphical object (grob), so that it can sit beside ggplot2 plots in patchwork, cowplot or gridExtra layouts, or be drawn with grid::grid.draw(). The grob draws the heatmap again whenever its space changes, so the layout sizes the dendrograms, legends and text for the space the heatmap is given. The dendrograms are kept in the heatmap, so drawing it again doesn't cluster it again.

Usage

heat_map_grob(x, ...)

Arguments

x

object of class heat_map returned by heat_map.

...

arguments passed to heat_map that replace those the heatmap was drawn with, as in plot(hm, ...), e.g. title = NULL.

Details

The heatmap is drawn with base graphics and converted to grid by the gridGraphics package, which must be installed. In patchwork, wrap_elements(full = ~ plot(hm)) does the same without heat_map_grob().

Value

a grob that draws the heatmap.

Author(s)

Dillon Hammill ([email protected])

See Also

heat_map_data to rebuild a heatmap with ggplot2 from its data.

Examples

if(requireNamespace("gridGraphics", quietly = TRUE)) {
  hm <- heat_map(
    mtcars,
    scale = "column",
    tree = "both",
    popup = FALSE
  )
  g <- heat_map_grob(hm, title = "mtcars")
  grid::grid.newpage()
  grid::grid.draw(g)
}

# Beside a ggplot2 plot with patchwork
if(requireNamespace("gridGraphics", quietly = TRUE) &&
   requireNamespace("ggplot2", quietly = TRUE) &&
   requireNamespace("patchwork", quietly = TRUE)) {
  library(ggplot2)
  library(patchwork)
  ggplot(mtcars, aes(wt, mpg)) + geom_point() + heat_map_grob(hm)
}

Interactive heatmaps: a web page to explore and select from

Description

heat_map_html() writes a heatmap to a self-contained web page - one HTML file, with nothing to install and nothing loaded from the internet - in which the heatmap can be explored and its rows and columns picked out:

Usage

heat_map_html(
  x,
  ...,
  file = NULL,
  width = 7,
  height = 7,
  format = c("auto", "svg", "png"),
  res = 150,
  title = NULL,
  max_cells = 1e+06,
  browse = interactive()
)

Arguments

x

a heatmap (an object of class heat_map, e.g. from heat_map, heat_map_dot, heat_map_cor or heat_map_composition), or data to draw with heat_map() and the arguments in ....

...

arguments of heat_map when x is data, or settings that replace those of the heatmap x (e.g. a new title).

file

the HTML file to write, or NULL (default) for a temporary file.

width, height

the size of the heatmap in inches, 7 by 7 by default; on the page it is shown at its width (96 pixels per inch) or narrower to fit, and zooms from there.

format

"svg" or "png", or "auto" (default): SVG when R can write it (with cairo), else PNG.

res

the resolution of PNG images in pixels per inch, 150 by default.

title

the title of the page, by default that of the heatmap.

max_cells

the largest number of cells whose values are written to the page, 1 million by default; larger heatmaps show the names of their rows and columns only, which keeps the page small.

browse

logical, whether to open the page, by default in interactive sessions.

Details

  • hovering over a cell shows its row, column and value (and the value before scaling, its size, clusters and annotations), and hovering over a label shows the row or column;

  • clicking a cell or a row's label selects (or unselects) the row, and clicking a column's label the column; dragging a box across cells, labels or dendrograms selects every row and column in it (Alt unselects them) - e.g. the genes of a cluster, picked off the dendrogram;

  • the selected rows and columns are listed beside the heatmap, to copy (one name per line, e.g. for features) or to download with their values as a CSV file;

  • a search box highlights the rows and columns whose names contain the text (Enter selects them), and the heatmap zooms (the buttons, or Ctrl or Cmd with the mouse wheel) for large heatmaps.

The heatmap is drawn as it is by heat_map - an SVG image by default, so it stays sharp when zoomed, or a PNG image - with its values alongside, and the page works offline and can be shared as one file. In an interactive session the page opens in the viewer of RStudio or Positron, or in a web browser; in R Markdown and Quarto documents rendered as HTML it is embedded where it is printed.

Value

an object of class heat_map_html, invisibly: the path of the page (file), with its size. Printing it opens the page.

Author(s)

Dillon Hammill ([email protected])

See Also

heat_map, heat_map_data

Examples

page <- heat_map_html(
  mtcars,
  scale = "column",
  tree = "both",
  tree_cut_y = 3,
  title = "mtcars",
  file = file.path(tempdir(), "mtcars.html"),
  browse = FALSE
)
page

# A heatmap drawn before, with a new title
grDevices::pdf(NULL)
hm <- heat_map(iris[1:40, 1:4], scale = "column", popup = FALSE)
grDevices::dev.off()
heat_map_html(hm, title = "iris", browse = FALSE)

Extract information about a constructed heatmap

Description

heat_map_info() returns the data and layout used to construct a heatmap, including the order of rows and columns, cluster assignments and dendrograms, so that they can be used in downstream analyses.

Usage

heat_map_info(x)

Arguments

x

object of class heat_map returned by heat_map.

Value

a list containing:

  • data: the data displayed in the heatmap (after scaling).

  • row_order: indices of the rows of x in the order they are displayed from the top to the bottom of the heatmap.

  • col_order: indices of the columns of x in the order they are displayed from left to right.

  • row_clusters, col_clusters: the cluster assigned to each row/column in their original order (or NULL when no clusters were defined). Clusters are numbered in the order they are displayed: from left to right for columns and from top to bottom for rows.

  • tree_x, tree_y: hclust objects for the x and y axis dendrograms (or NULL). Branch heights are rescaled for display.

  • support_x, support_y: bootstrap support of each merge of tree_x and tree_y (tree_support_x, tree_support_y), NA for the root and merges fixed by groups, or NULL.

  • zoom_x, zoom_y: indices of the columns (from left to right) and rows (from top to bottom) enlarged in a zoom panel (zoom_x, zoom_y) - a list with the indices of each band when several were given as a list - or NULL.

  • axis_text_x, axis_text_y: axis labels from left to right and from top to bottom respectively.

  • colours, sizes, shapes: the fill colour, relative size and shape of each cell, in the orientation of the original data.

  • centers: lists x and y with the centre of each column and row in the original order, in the heatmap's plot co-ordinates (one unit per cell, plus any gaps between clusters), for drawing on top of a heatmap.

  • split_colours, split_data: the fill colour and value (after scaling) of the lower right (or right) half of each cell (cell_split) in the orientation of the original data, or NULL.

  • split_sizes: the relative size of the right half of each split circle (cell_split_size), or NULL.

  • annotations: lists x and y with the colour of each row/column for every annotation, in the original order.

  • layout: a data.frame with the bounding box (xmin, xmax, ymin, ymax) of each component of the heatmap in inches from the bottom left corner of the device.

  • raster: whether the cells were drawn as raster images (see cell_raster in heat_map()).

  • col_limits, size_limits: limits of the colour and size scales.

Author(s)

Dillon Hammill ([email protected])

Examples

hm <- heat_map(
  mtcars,
  scale = "column",
  tree_cut_x = 3,
  tree_cut_y = 4,
  popup = FALSE
)
info <- heat_map_info(hm)
info$col_clusters
rownames(mtcars)[info$row_order]

Arrange multiple heatmaps

Description

Arrange multiple heatmaps

Usage

heat_map_layout(layout = NULL)

Arguments

layout

either a vector of the form c(nrow, ncol) defining the dimensions of the plot or a matrix defining a more sophisticated layout (see layout). Vectors can optionally contain a third element to indicate whether plots should be placed in row (1) or column (2) order, set to row order by default.

Value

No return value, called for side effects.

Author(s)

Dillon Hammill ([email protected])

Examples

# Save heatmap
heat_map_save(file.path(tempdir(), "Heatmap.png"),
height = 7, 
width = 15)

# Custom layout
heat_map_layout(layout = c(1,2))

# Construct raw heatmap
heat_map(iris[1:10,],
scale = FALSE,
title = "Iris Raw Heatmap",
axis_label_x = "Plant Parameter",
axis_label_y = "Row ID")

# Construct scaled heatmap
heat_map(iris[1:10,],
scale = "column",
title = "Iris Scaled Heatmap",
axis_label_x = "Plant Parameter",
axis_label_y = "Row ID")

# Signal completion
heat_map_complete()

Find the marker features of groups of cells

Description

heat_map_markers() ranks the features of single-cell data by how well they mark each group of cells (e.g. each cluster), for heatmaps and dot plots of the top markers of each group. Each feature is scored in each group by its AUC against all the other cells: the chance that a cell of the group has a larger value than a cell outside it, ties counting half (the Wilcoxon rank-sum statistic, Wilcoxon 1945 and Mann and Whitney 1947, over the product of the numbers of cells, as presto's wilcoxauc() scores markers; Korsunsky et al. 2019). 0.5 is no better than chance and 1 a perfect marker.

Usage

heat_map_markers(
  x,
  group_by,
  features = NULL,
  assay = NULL,
  n = 5,
  min_detected = 0.1,
  min_logfc = 0.25,
  threshold = 0
)

Arguments

x

single-cell data, a matrix or a data.frame (see heat_map).

group_by

the group of each cell, the name of a column of its metadata or a vector (see heat_map). Cells without a group are left out.

features

the features to score, set to NULL by default for every feature (see heat_map).

assay

the values of single-cell data to score (see heat_map), e.g. log-normalised expression.

n

the number of top markers of each group, set to 5 by default.

min_detected

the smallest proportion of a group's cells in which a marker of the group is detected, set to 0.1 by default.

min_logfc

the smallest difference between the mean of a marker in its group and its mean in the other cells, set to 0.25 by default. On log-transformed values, such as log-normalised counts, the difference is the log fold change (in the base of the logarithm).

threshold

values above threshold are counted as detected, set to 0 by default.

Details

Features are kept for a group when they are detected (above threshold) in at least min_detected of its cells and their mean in the group exceeds their mean in the other cells by at least min_logfc. Each feature marks the group where its AUC is highest, and the n features with the highest AUC in each group are its top markers.

Each AUC has the p-value of the Wilcoxon rank-sum test of the group against the other cells (two-sided, from the normal approximation with corrections for ties and continuity, as wilcox.test(exact = FALSE) finds it), and the p-values of each group are adjusted for the false discovery rate by Benjamini and Hochberg's (1995) method over every feature scored, not only those kept. With thousands of cells nearly every marker has a tiny p-value, so the AUC and the difference of the means are the better guides to how well a feature marks a group.

The AUC is found from one ranking of each feature's values. The zeros of sparse data share one rank, so only the non-zero values are sorted; the features are shared between threads (see heat_map_threads), and only features that pass the filters in some group are ranked.

Value

a data.frame of class heat_map_markers with one row per feature kept for a group, in the order of the groups and, within each group, from the highest AUC: group (a factor), feature, auc, logfc (the difference between the means in and out of the group), p_value and p_adj (the p-value of the rank-sum test and its adjusted value), mean_in, mean_out, detected_in and detected_out (the proportions of cells detected in and out of the group) and top (TRUE for the top markers of each group). Its "features" attribute lists the top markers of each group. Given to features in heat_map or heat_map_dot, the rows with top = TRUE are shown, grouped by the group they mark; edit top to choose other markers. Given to x in heat_map_dot, the markers are drawn as a dot plot coloured by fold change and sized by adjusted p-value.

Author(s)

Dillon Hammill ([email protected])

References

Benjamini, Y. and Hochberg, Y. (1995). Controlling the false discovery rate: a practical and powerful approach to multiple testing. Journal of the Royal Statistical Society: Series B, 57(1), 289-300. doi:10.1111/j.2517-6161.1995.tb02031.x

Korsunsky, I., Nathan, A., Millard, N. and Raychaudhuri, S. (2019). Presto scales Wilcoxon and auROC analyses to millions of observations. bioRxiv. doi:10.1101/653253

Mann, H. B. and Whitney, D. R. (1947). On a test of whether one of two random variables is stochastically larger than the other. The Annals of Mathematical Statistics, 18(1), 50-60. doi:10.1214/aoms/1177730491

Wilcoxon, F. (1945). Individual comparisons by ranking methods. Biometrics Bulletin, 1(6), 80-83. doi:10.2307/3001968

See Also

heat_map_dot, heat_map

Examples

set.seed(1)
cells <- data.frame(
  CD3 = c(rexp(200, 0.5), rexp(60, 4)) * rbinom(260, 1, 0.7),
  CD19 = c(rexp(200, 4), rexp(60, 0.5)) * rbinom(260, 1, 0.7),
  NKG7 = rexp(260, 1) * rbinom(260, 1, 0.3),
  cluster = rep(c("T cells", "B cells"), c(200, 60))
)
markers <- heat_map_markers(cells, group_by = "cluster", n = 1)
markers

# The top markers of each cluster, grouped
heat_map(cells, features = markers, group_by = "cluster", popup = FALSE)
heat_map_dot(cells, features = markers, group_by = "cluster", popup = FALSE)

Open a popup graphics device for heatmaps

Description

Opens a new graphics device when a popup is requested and the current device already holds a plot. Popups are only opened in interactive sessions: in scripts, R Markdown and other non-interactive sessions the current device is used.

Usage

heat_map_new(popup = FALSE, popup_size = c(8, 8), ...)

Arguments

popup

logical indicating whether a popup graphics device should be opened, set to FALSE by default.

popup_size

indicates the size of the popup graphics device in inches, set to c(8,8) by default.

...

additional arguments passed to dev.new.

Value

No return value, called for side effects.

Author(s)

Dillon Hammill, [email protected]

Examples

# Open platform-specific graphics device
heat_map_new(popup = TRUE)

Read an AnnData (.h5ad) file

Description

heat_map_read_h5ad() opens an AnnData file, as written by scanpy and anndata in Python (or downloaded from CELLxGENE), for heat_map, heat_map_dot, heat_map_summarise, heat_map_markers, heat_map_score and heat_map_smooth, without Python, reticulate or a conversion to another class. The metadata of the cells (obs) and features (var) are read at once; a matrix of values - X, a layer such as "counts", or "raw" - is read the first time it is used, as a sparse dgCMatrix (CSR and CSC matrices are read without copying or sorting them) or a dense matrix, and kept with the object for the next heatmap. A file name ending in .h5ad can also be given to these functions in place of the object, when it is read each time.

Usage

heat_map_read_h5ad(file)

Arguments

file

the path of an .h5ad file.

Details

Columns of obs become the metadata used by group_by and annotation_by: categorical columns as factors (with their levels and missing values), strings as character vectors, and numbers and booleans as they are, with the masks of nullable columns as missing values. Files written by anndata 0.7 (with categories in __categories) and later are read. Features are named by the index of var and can also be named by a column of gene symbols or IDs (feature_name, gene_symbols, gene_name, symbol or gene_ids), e.g. the symbols of a CELLxGENE file whose index holds Ensembl IDs.

Value

an object of class heat_map_h5ad: a list with the file, the metadata of the cells (obs) and features (var, and raw_var for raw), and the matrices it holds (assays: "X", the layers and "raw"), chosen with assay.

Author(s)

Dillon Hammill ([email protected])

See Also

heat_map

Examples

if(requireNamespace("hdf5r", quietly = TRUE)) {
  # 60 cells of three types written by anndata
  file <- system.file("extdata", "example.h5ad", package = "HeatmapR")
  cells <- heat_map_read_h5ad(file)
  cells
  heat_map_dot(cells, features = paste0("GENE", 1:8), group_by = "cell_type",
               popup = FALSE)
  # The counts of a layer, summed in each type of cell and sample
  heat_map_summarise(cells, assay = "counts", group_by = c("cell_type", "sample"),
                     fun = "sum")[, 1:4]
}

Record a custom heatmap

Description

Record custom heatmap layout on current graphics device and save to an R object for future use.

Usage

heat_map_record()

Value

an object of class recordedplot.

Author(s)

Dillon Hammill ([email protected])

Examples

# Heatmap layout
heat_map_layout(c(1,2))

# Construct raw heatmap
heat_map(iris[1:10,],
scale = FALSE,
title = "Iris Raw Heatmap",
axis_label_x = "Plant Parameter",
axis_label_y = "Row ID")

# Construct scaled heatmap
heat_map(iris[1:10,],
scale = "column",
title = "Iris Scaled Heatmap",
axis_label_x = "Plant Parameter",
axis_label_y = "Row ID")

# Record heatmap layout
heat_map_plot <- heat_map_record()

Reset all heatmap related settings

Description

Reset all heatmap related settings

Usage

heat_map_reset()

Value

No return value, called for side effects.

Author(s)

Dillon Hammill ([email protected])

Examples

# Reset HeatmapR settings
heat_map_reset()

Save high resolution images

Description

Save high resolution images

Usage

heat_map_save(
  save_as,
  width = 7,
  height = 7,
  units = "in",
  res = 300,
  multiple = FALSE,
  layout = NULL,
  x = NULL,
  ...
)

Arguments

save_as

name of the file to which the plot should be saved (including the file extension). Supported file formats include png, tiff (or tif), jpeg (or jpg), svg and pdf. File extensions are not case sensitive.

width

numeric indicating the width of exported plot in units, set to 7 by default for image with width of 7 inches.

height

numeric indicating the height of the exported plot in units, set to 7 by default for image with height of 7 inches.

units

units to be used to set plot size, can be either pixels ("px"), inches ("in"), centimetres ("cm") or millimetres ("mm"). Set to "in" by default. Units cannot be altered for svg and pdf graphics devices.

res

resolution in dpi, set to 300 by default.

multiple

logical indicating whether multiple pages should be saved to separate numbered files, set to FALSE by default.

layout

a vector or matrix defining the custom layout of the plot to be created using heat_map_layout, set to NULL by default.

x

optional heat_map object returned by heat_map (or a list of heat_map objects to fill a layout) to draw and save immediately. When supplied, the graphics device is closed once the heatmap(s) have been drawn and there is no need to call heat_map_complete(). Any active heat_map_custom() layout and the current graphics device are left unchanged. Without a layout, each heatmap is drawn on a separate page, so several heatmaps require a pdf file or multiple = TRUE.

...

additional arguments for the appropriate png(), tiff(), jpeg(), svg() or pdf graphics devices. TIFF files are compressed without loss (compression = "lzw") unless another compression is given, except when they are drawn by quartz (the default on macOS), which can't compress them (type = "cairo" can, where R has cairo).

Value

No return value, called for side effects.

Author(s)

Dillon Hammill ([email protected])

Examples

# Save Heatmap
heat_map_save(file.path(tempdir(), "Heatmap.png"),
height = 7,
width = 5)

# Construct Heatmap
heat_map(iris[1:10,],
scale = "column",
title = "Iris Heatmap",
axis_label_x = "Plant Parameter",
axis_label_y = "Row ID")

# Save an existing heatmap
hm <- heat_map(mtcars, scale = "column", popup = FALSE)
heat_map_save(file.path(tempdir(), "mtcars.pdf"), x = hm)

Scale numeric data prior to constructing heat_map

Description

Apply column-wise or row-wise scaling to numeric columns in a matrix or data.frame prior to constructing a heat_map, or transform them for cytometry data.

Usage

heat_map_scale(x, scale = "column", method = "range", cofactor = 5, q = 0.01)

Arguments

x

matrix-like object to be scaled.

scale

indicates whether the data should be scaled by "row" or "column", set to "column" by default. Abbreviations such as "col" are accepted, as are "x" and "y" as aliases for "column" and "row".

method

type of scaling to perform, one of "range", "mean", "zscore", "quantile" or "asinh" (unique abbreviations such as "z" are accepted). Range scaling normalises the data to have limits between 0 and 1. Mean scaling subtracts the mean (calculated excluding missing values) from each value and divides the result by the range. Z-score scaling subtracts the mean from each value and then divides the result by the standard deviation. Rows or columns with no variation are mapped to 0.5 for range scaling and 0 for mean and z-score scaling, rather than NaN. Quantile scaling maps the q and 1 - q quantiles of each column (row; type 7 of Hyndman and Fan 1996, as quantile() finds them) to 0 and 1 and clips the values beyond them, so that a few extreme values don't compress the colours of the rest; when the two quantiles are equal, values above them are 1 and the others 0. The "asinh" transform takes the inverse hyperbolic sine of each value divided by cofactor, the usual transform of cytometry intensities (Bendall et al. 2011; it ignores scale).

cofactor

the cofactor of the "asinh" transform: one number (5 by default, as for mass cytometry; about 150 is common for flow cytometry), or one per numeric column (in order, or named by column).

q

the quantile of quantile scaling, set to 0.01 by default.

Value

a matrix or data.frame containing the scaled data.

Author(s)

Dillon Hammill ([email protected])

References

Bendall, S. C. et al. (2011). Single-cell mass cytometry of differential immune and drug responses across a human hematopoietic continuum. Science, 332(6030), 687-696. doi:10.1126/science.1198704

Hyndman, R. J. and Fan, Y. (1996). Sample quantiles in statistical packages. The American Statistician, 50(4), 361-365. doi:10.1080/00031305.1996.10473566

Examples

# Range scaling
mtcars_scale_range <- heat_map_scale(mtcars,
method = "range")

# Mean scaling
mtcars_scale_mean <- heat_map_scale(mtcars,
method = "mean")

# Z-score scaling
mtcars_scale_zscore <- heat_map_scale(mtcars,
method = "zscore")

# Row-wise z-score scaling
mtcars_scale_rows <- heat_map_scale(mtcars,
scale = "row",
method = "zscore")

# Cytometry: asinh transform with cofactor 5, then each marker scaled to
# 0-1 between its 1st and 99th percentiles
events <- matrix(rexp(3000, 1 / 200), ncol = 3,
                 dimnames = list(NULL, c("CD3", "CD4", "CD8")))
events <- heat_map_scale(events, method = "asinh", cofactor = 5)
events <- heat_map_scale(events, method = "quantile", q = 0.01)

Scores of gene sets in each cell

Description

heat_map_score() scores each cell for each of several sets of features (e.g. the genes of pathways or cell types), so that a heatmap or dot plot can show a few scores in place of hundreds of genes. The scores are returned with the metadata of the cells, so they can be drawn and summarised like any other single-cell data: heat_map(scores, group_by = "cell_type"), heat_map_dot(scores, group_by = "cell_type") or heat_map_summarise(scores, group_by = "cell_type").

Usage

heat_map_score(
  x,
  sets,
  assay = NULL,
  method = c("zscore", "mean", "module"),
  bins = 30,
  controls = 100,
  seed = 1,
  min_size = 1
)

Arguments

x

single-cell data: a SingleCellExperiment, SummarizedExperiment or Seurat object, a sparse matrix or a matrix or data.frame of cells by features (see heat_map).

sets

a named list of sets of features, each a vector of the names of features of x (or of their gene symbols); a single vector is one set. Features that aren't in x are left out with a message; a set with fewer than min_size features in x is an error. The markers returned by heat_map_markers give one set per group (its top markers).

assay

the values of single-cell data to score (see heat_map).

method

"zscore" (default), "mean" or "module" (see Details).

bins, controls

the number of bins of features by mean expression and of control features drawn for each feature of a set, for method = "module", set to 30 and 100 by default as Tirosh et al. (2016) chose them.

seed

the seed of the random numbers that draw the control features (R's own seed is left as it was).

min_size

the fewest features of a set that must be in x, set to 1 by default.

Details

Three scores are computed in compiled code from the non-zero values of sparse data, without a dense copy:

  • "zscore" (the default): the mean of the set's features after each is z-scored across the cells, so that every feature counts the same whatever its level of expression. Features that don't vary are left out.

  • "mean": the mean of the values of the set's features.

  • "module": the mean of the set's features less the mean of control features of similar expression, as Tirosh et al. (2016) score gene sets (and as Seurat's AddModuleScore() does). All the features of x are put into bins bins of equal size by their mean across the cells and, for each feature of the set, controls features are drawn from its bin (other features of the set left out), with a fixed seed, so the scores are the same every time. A score above zero means more expression than features of the same level generally have.

Missing values are left out of a cell's mean.

Value

a numeric matrix with one row per cell (named by the cells) and one column per set (named by the sets), whose attribute "groups" holds the metadata of the cells (a data.frame, read by group_by, split_by and annotation_by), "sets" the features of each set that were scored, "method" the score and, for method = "module", "controls" the control features of each set.

References

Tirosh, I., Izar, B., Prakadan, S. M., Wadsworth, M. H., Treacy, D., Trombetta, J. J., et al. (2016). Dissecting the multicellular ecosystem of metastatic melanoma by single-cell RNA-seq. Science, 352(6282), 189-196. doi:10.1126/science.aad0501

See Also

heat_map_dot, heat_map_summarise

Examples

cells <- heat_map_example("rna", n = 600)
scores <- heat_map_score(
  cells,
  sets = list(
    T = c("CD3E", "IL7R", "CD8A"),
    B = c("MS4A1", "CD79A", "CD79B"),
    Myeloid = c("LYZ", "S100A8", "S100A9", "FCER1A")
  )
)
head(scores)
# A dot plot of the scores of each cell type
heat_map_dot(scores, group_by = "cell_type", popup = FALSE)

Smooth features along pseudotime for a heatmap

Description

heat_map_smooth() bins cells along a trajectory (e.g. their pseudotime) and finds the mean of each feature in each bin, smoothed over neighbouring bins, for heatmaps of genes or markers along pseudotime. With tree_order_x = "peak" (or tree_order_y with swap_axes = TRUE), heat_map() then orders the features by when they peak, so that cascades run diagonally.

Usage

heat_map_smooth(
  x,
  along,
  features = NULL,
  assay = NULL,
  bins = 100,
  span = 5,
  binning = "cells",
  group_by = NULL
)

Arguments

x

single-cell data (a SingleCellExperiment or SummarizedExperiment, a Seurat object, a flowFrame or flowSet, a sparse matrix with one cell per row), or a matrix or data.frame of cells; see heat_map.

along

the position of each cell along the trajectory: the name of a numeric column of the cells' metadata (or of x), several names for several lineages, or a numeric vector with one value per cell. Cells with a missing position are left out (of that lineage).

features

the features to smooth, as names (or indices); see heat_map. Set to NULL by default for every feature.

assay

the values of single-cell data to smooth; see heat_map.

bins

the number of bins along the trajectory (of each lineage), set to 100 by default. A lineage with fewer cells has one bin per cell.

span

the number of bins each mean is taken over, set to 5 by default; 1 takes the mean of each bin on its own.

binning

"cells" (default) for bins with equal numbers of cells, or "width" for bins of equal width along along.

group_by

the lineage of each cell, for trajectories with one along for all lineages: the name of a column of the cells' metadata, or a vector with the lineage of each cell. Each lineage is smoothed on its own.

Details

The cells are put in bins bins along along: bins with equal numbers of cells (binning = "cells"), which follow the density of the cells along the trajectory, or bins of equal width (binning = "width"). The value of each feature in a bin is the mean of the cells in the span bins around it (the bin itself and (span - 1) / 2 bins either side, fewer at the ends), a running mean weighted by the cells in each bin. The means are found in compiled code, without a dense copy of sparse data.

Branching trajectories are smoothed one lineage at a time, from several along columns (one per lineage, e.g. slingshot's pseudotimes, Street et al. 2018, which are missing for cells outside a lineage) or from group_by; the lineages are stacked in the result, and heat_map(group_by = "lineage") draws them side by side.

Value

a numeric matrix with one row per bin (bins of each lineage in turn, named "lineage / bin") and one column per feature, holding the smoothed means. As heat_map_summarise summaries of groups, it keeps the attributes "n" (the number of cells in each bin, for bar_values_y = "n") and "groups": a data.frame with the lineage of each bin and its position (the mean of along over its cells, named as along, or "along"), which heat_map(annotation_by = ) draws as annotation tracks and heat_map(group_by = "lineage") uses to group the bins; and "along", the name of the position's column, from which peak orders (tree_order_x = "peak") read when each bin is, so that the peaks of lineages covering different stretches of the trajectory are compared by their position along it.

Author(s)

Dillon Hammill ([email protected])

References

Street, K. et al. (2018). Slingshot: cell lineage and pseudotime inference for single-cell transcriptomics. BMC Genomics, 19, 477. doi:10.1186/s12864-018-4772-0

See Also

heat_map, heat_map_summarise

Examples

# Twelve genes, each peaking at its own point along pseudotime
set.seed(1)
pseudotime <- runif(3000)
peaks <- seq(0.05, 0.95, length.out = 12)
genes <- sapply(peaks, function(p) {
  rpois(3000, 8 * exp(-((pseudotime - p) / 0.12)^2))
})
colnames(genes) <- paste0("gene", 1:12)
genes <- genes[, sample(12)]
smooth <- heat_map_smooth(genes, along = pseudotime, bins = 50)

# Genes as rows, ordered by when they peak, with pseudotime as a track
heat_map(
  smooth,
  swap_axes = TRUE,
  scale = "row",
  tree_order_y = "peak",
  annotation_by = "along",
  axis_text_x = NA,
  popup = FALSE
)

Styles: settings of heat_map() set once and reused

Description

heat_map_style() keeps settings of heat_map - text sizes and fonts, colours and colour scales, legend options, cell borders and the like - to be used by every heatmap that is given the style (heat_map(style = )) or, set with options(HeatmapR.style = ), by every heatmap of a session, including those drawn by heat_map_dot, heat_map_cor, heat_map_align and heat_map_composition. Arguments given to heat_map() take precedence over the style, and the style over the option, so a heatmap can still change any setting. Settings that a function sets itself (e.g. the circles of a dot plot) take precedence over the style too. A redrawn heatmap keeps the style it was drawn with.

Usage

heat_map_style(...)

Arguments

...

settings, named by the arguments of heat_map, and styles to build on (unnamed; later settings and styles replace earlier ones).

Value

an object of class heat_map_style, a named list of settings.

Author(s)

Dillon Hammill ([email protected])

See Also

heat_map

Examples

report <- heat_map_style(
  cell_col_scale = "viridis",
  cell_border_line_col = "white",
  axis_text_size_x = 0.8,
  axis_text_size_y = 0.8,
  title_text_size = 1.2,
  legend_side = "bottom"
)
report
heat_map(mtcars, scale = "column", style = report, title = "mtcars",
         popup = FALSE)
# Built on, and changed by the arguments of a heatmap
wide <- heat_map_style(report, axis_text_angle_x = 45)
heat_map(mtcars, scale = "column", style = wide, cell_col_scale = "Blue-Red 3",
         popup = FALSE)
# For every heatmap of the session
old <- options(HeatmapR.style = report)
heat_map(iris[1:20, 1:4], popup = FALSE)
options(old)

Summarise groups of rows or columns for a heatmap

Description

heat_map_summarise() reduces the columns (and/or rows) of a matrix or data.frame to one per group, for heatmaps of group summaries such as the mean expression of each gene in each cell type (a pseudobulk view of single-cell data) or the median intensity of each marker in each cluster of cytometry events. Summaries computed with different functions can be combined in heat_map(), e.g. the mean as the colour and the proportion of cells expressing each gene (fun = "detected") as the cell size of a dot plot.

Usage

heat_map_summarise(
  x,
  group_x = NULL,
  group_y = NULL,
  fun = "mean",
  threshold = 0,
  features = NULL,
  assay = NULL,
  group_by = NULL,
  transform = NULL,
  cofactor = 5,
  scale = FALSE,
  q = 0.01,
  scale_when = "last",
  stack_by = NULL,
  bimodal = FALSE
)

Arguments

x

a matrix or data.frame, or single-cell data (a SingleCellExperiment or SummarizedExperiment, a Seurat object, a flowFrame or flowSet, or a sparse matrix with one cell per row; see heat_map). Only numeric columns are summarised; other columns are dropped with a message. Single-cell data are summarised with one row per group of cells and one column per feature. The mean, sum, number, proportion detected and median of sparse data are found from the non-zero values, without a dense copy, and equal those of the dense data. Assays held on disk (DelayedArray, HDF5Array and BPCells matrices) are summarised a block of features at a time, with the same results.

group_x

a vector assigning each column of x to a group, in the order of the columns of x (or named by column name). Each group becomes one column of the result. Columns in a missing group are dropped.

group_y

a vector assigning each row of x to a group, in the order of the rows of x (or named by row name). Each group becomes one row of the result. Rows in a missing group are dropped.

fun

the summary of the values in each group, one of "mean" (default), "median", "sum", "min", "max", "sd", "n" (the number of non-missing values), "detected" (the proportion of non-missing values above threshold) or "dip" (the dip statistic of the values above threshold: see bimodal), or a function taking a numeric vector and returning a single number. Missing values are removed before summarising. "values" keeps the values themselves: the result is then a matrix of lists holding the numeric vector of values in each group, for cell_values in heat_map() to draw their distributions inside the cells.

threshold

values above threshold are counted by fun = "detected", and the dips of fun = "dip" and bimodal are found from them, set to 0 by default.

features

the features of single-cell data to summarise, as names (or indices); see heat_map. Set to NULL by default for every feature.

assay

the values of single-cell data to summarise; see heat_map.

group_by

the group of each cell of single-cell data: the name of a column of the cells' metadata, or a vector with the group of each cell (as group_y); see heat_map. Each group becomes one row of the result. Several column names (or a data.frame or list of several variables, with one value per cell) group the cells by their combinations, e.g. c("cluster", "sample") for the medians of each cluster in each sample, in rows named "cluster / sample" and ordered by cluster, then sample.

transform

"asinh" to transform the values of the cells with the inverse hyperbolic sine of each value divided by cofactor before summarising them (the usual transform of cytometry intensities), or NULL (default) to summarise the values as they are. The zeros of sparse data stay zeros, so they are transformed without a dense copy.

cofactor

the cofactor of transform = "asinh": one number (5 by default, as for mass cytometry; about 150 is common for flow cytometry) or one per feature, named by feature.

scale

the scaling of each feature (column): FALSE (default) for none, or a method of heat_map_scale: "quantile" (0 to 1 between the q and 1 - q quantiles, with the values beyond them clipped), "range", "zscore" or "mean".

q

the quantile of scale = "quantile", set to 0.01 by default.

scale_when

"last" (default) to scale the summaries of the groups, or "first" to scale the cells before summarising them. Scaling sparse data first reads the chosen features as a dense matrix.

stack_by

the part of each cell for stacked bars beside the summaries (e.g. its condition or sample): the name of a column of the cells' metadata, or a vector with the part of each cell. The number of cells of each group in each part is kept in the "stack" attribute of the result, which heat_map(bar_values_y = "n", bar_type_y = "stack") draws. Needs group_by.

bimodal

TRUE to keep the dip of each feature in each group of rows (cells) as the "dip" attribute of the result, and the number of values it was found from as "dip_n", for heat_map(bimodal = TRUE) to outline the groups in which a feature looks like two populations; set to FALSE by default. The dip of Hartigan and Hartigan (1985) is the largest distance between the distribution of the values and the closest unimodal distribution: 0 for one peak of any shape, and up to 0.25 as the values split into separate populations (about 0.02 for two equal populations 3 standard deviations apart, 0.05 for 4). So that the measurement and its transformation don't make peaks of their own, the dip is found from the values above threshold (the cells in which a feature is detected, which leaves out piles of zeros and the lower of the two mirrored peaks the asinh transform with a small cofactor makes of a negative population), after transform and before scaling (quantile scaling clips values into piles), with discrete values such as counts spread evenly over the gaps between them (so that the comb of 1, 2, 3, ... counts isn't read as several peaks) and, for continuous values, the piles at the lowest and highest values (clipping, saturated detectors) left out. Groups with fewer than 20 such values have no dip. The dips are computed in compiled code, from the greatest convex minorant and least concave majorant of the distribution of the values (Hartigan and Hartigan 1985), and equal those of the diptest package.

Populations that differ in several features at once (most often whether the features are detected at all, as in a cluster combining CD4 and CD8 T cells: on the count scale, a feature detected in only some cells falls away steadily from zero, as dropout does, and has one peak) are found across features: the dip of the scores of each group's cells on the first principal component of the correlations of its features (those that vary and are detected in at least 5% of the cells, at least 3 of them; at most 50,000 cells of a group, drawn with a fixed seed). It is only found when that component carries co-variation - an eigenvalue of at least 2, and above the largest eigenvalue of as many independent features (the upper edge of the Marchenko-Pastur law, Marchenko and Pastur 1967) - so that features that each have two peaks of their own (e.g. from the asinh transform) don't add up to a split, and it is kept as the "dip_pc" attribute (and "dip_pc_n", the cells used) in the features that drive the component (more than an equal share of it), NA elsewhere. Needs groups of rows from group_by or group_y.

Value

a numeric matrix with one column per group of group_x (or the columns of x) and one row per group of group_y (or the rows of x), or a matrix of lists for fun = "values". Groups are in the order of their factor levels (sorted for other vectors). Groups without any values are NA. Summaries of groups from group_by keep three attributes, which heat_map() reads: "n", the number of cells in each group (for bar_values_y = "n"); "stack" with stack_by, a matrix with the number of cells of each group (row) in each part (column); and "groups", a data.frame with one row per group holding the grouping columns and the other metadata that is the same for every cell of the group (e.g. the condition of each sample), which heat_map(group_by = , annotation_by = ) can use as the metadata of the rows. With bimodal = TRUE the result also keeps the "dip", "dip_n", "dip_pc" and "dip_pc_n" attributes (see bimodal).

Author(s)

Dillon Hammill ([email protected])

References

Hartigan, J. A. and Hartigan, P. M. (1985). The dip test of unimodality. The Annals of Statistics, 13(1), 70-84. doi:10.1214/aos/1176346577

Marchenko, V. A. and Pastur, L. A. (1967). Distribution of eigenvalues for some sets of random matrices. Mathematics of the USSR-Sbornik, 1(4), 457-483. doi:10.1070/SM1967v001n04ABEH001994

See Also

heat_map

Examples

# Mean of each variable for each number of cylinders
cyl <- heat_map_summarise(mtcars[, -2], group_y = mtcars$cyl)
heat_map(cyl, scale = "column", popup = FALSE)

# Distribution of each variable for each number of cylinders in its cell
heat_map(
  cyl,
  scale = "column",
  cell_values = heat_map_summarise(mtcars[, -2], group_y = mtcars$cyl,
                                   fun = "values"),
  popup = FALSE
)

# Dot plot - mean as colour, proportion above the overall mean as size
z <- scale(mtcars)
heat_map(
  heat_map_summarise(z, group_y = mtcars$gear),
  cell_size = heat_map_summarise(z, group_y = mtcars$gear, fun = "detected"),
  cell_shape = "circle",
  popup = FALSE
)

# Single cells - the median of each marker in each cluster
cells <- data.frame(
  CD3 = c(rnorm(200, 4), rnorm(30, 1)),
  CD19 = c(rnorm(200, 1), rnorm(30, 4)),
  cluster = rep(c("T cells", "B cells"), c(200, 30))
)
heat_map_summarise(cells, group_by = "cluster", fun = "median")

# Cytometry - medians of asinh-transformed intensities, scaled to 0-1
# between the 1st and 99th percentiles of each marker, with the number of
# cells of each condition in each cluster as stacked bars
events <- data.frame(
  CD3 = rexp(2000, 1 / 300),
  CD4 = rexp(2000, 1 / 100),
  CD8 = rexp(2000, 1 / 50),
  cluster = sample(c("T4", "T8", "B"), 2000, replace = TRUE),
  condition = sample(c("control", "stimulated"), 2000, replace = TRUE)
)
medians <- heat_map_summarise(
  events,
  group_by = "cluster",
  fun = "median",
  transform = "asinh",
  cofactor = 5,
  scale = "quantile",
  stack_by = "condition"
)
heat_map(medians, bar_values_y = "n", bar_type_y = "stack", popup = FALSE)

Number of threads used by HeatmapR

Description

The compiled code shares its larger jobs between threads: the distances between rows, the searches for the nearest cluster and the distance updates of the linkage while many clusters remain (more than about 1,500), the groups and the nearest-medoid search of two-stage clustering, the resamples of branch support (tree_support_x, tree_support_y) and the larger steps and blocks of optimal leaf ordering. Results are the same whatever the number of threads.

Usage

heat_map_threads(threads = NULL)

Arguments

threads

the number of threads to use from now on (a whole number of at least 1), NULL to leave it as it is, or NA to return to the default.

Details

By default HeatmapR uses one thread per physical core, but no more than the CPUs the R process may run on (on Linux, e.g. when limited by taskset or a container), no more than the environment variables OMP_THREAD_LIMIT and OMP_NUM_THREADS allow (when they are set) and no more than two while R CMD check limits the number of cores (_R_CHECK_LIMIT_CORES_). Processes forked from R (e.g. by parallel::mclapply()) use one thread unless the number is set. The linkage stops sharing its scans between threads when waiting for them takes longer than the work they save, e.g. when other processes keep the cores busy; results are the same either way. Set the number with heat_map_threads(n) or options(HeatmapR.threads = n), e.g. heat_map_threads(1) when heatmaps are drawn in parallel processes.

Value

the number of threads in use. When threads is given, the number in use before, invisibly.

Examples

# THREADS IN USE
heat_map_threads()

# ONE THREAD, THEN BACK TO THE PREVIOUS SETTING
old <- heat_map_threads(1)
heat_map_threads(old)

Draw a heat_map object

Description

plot() redraws a heatmap on the current graphics device using the arguments originally supplied to heat_map. Any arguments supplied through ... override the original arguments, for example plot(hm, title = "New title"). Use data to redraw the heatmap with new data, as x refers to the heat_map object itself. The dendrograms, k-means clusters and branch support of the heatmap are kept in it and reused when the arguments they depend on (the data, scaling, distance, linkage and tree arguments) haven't changed, so a redraw only draws.

Usage

## S3 method for class 'heat_map'
plot(x, ...)

## S3 method for class 'heat_map'
print(x, ...)

Arguments

x

object of class heat_map.

...

additional arguments passed to heat_map.

Details

print() also redraws the heatmap, unless it was drawn within a custom layout (see heat_map_custom), in which case the recorded page is replayed as is.

Value

x, invisibly.

Examples

hm <- heat_map(mtcars, scale = "column", popup = FALSE)
plot(hm, title = "mtcars")
plot(hm, data = mtcars[1:10, ])

Print a heatmap description as wrapped text

Description

Print a heatmap description as wrapped text

Usage

## S3 method for class 'heat_map_description'
print(x, width = getOption("width"), ...)

Arguments

x

object of class heat_map_description returned by heat_map_describe.

width

width of the wrapped text, set to the console width by default.

...

not used.

Value

x, invisibly.