| 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 |
Create a complex heatmap using base graphics
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, ... )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, ... )
x |
matrix or data.frame containing the data to display in the heatmap,
or single-cell data: a |
scale |
logical indicating whether the data should be scaled prior to
constructing the heatmap ( |
scale_method |
indicates the type of scaling to perform on |
dist_method |
indicates the type of distance metric to use when
constructing dendrograms, set to |
clust_method |
indicates the type of agglomeration method to use when
performing hierarchical clustering, set to |
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 |
round |
indicates the number of decimal places to round values when
|
tree |
options include |
tree_x |
logical indicating whether dendrograms should be constructed
for the x axis (columns), set to NULL by default. Alternatively, a
pre-computed |
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_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 |
tree_support_x |
|
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 |
tree_kmeans_x |
number of k-means clusters (Hartigan and Wong 1979) to
split the columns of |
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_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_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_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 |
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 |
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 |
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_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 |
tree_support_y |
|
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 |
tree_kmeans_y |
number of k-means clusters to split the rows of
|
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_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_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_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 |
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 |
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 |
cell_size |
logical indicating whether each cell in the heatmap should
be scaled by the value in |
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
|
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 |
cell_col_scale_limits |
a numeric vector of length 2 specifying custom
limits for the colour scale as |
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_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_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 |
cell_size_scale_limits |
a numeric vector of length 2 specifying custom
limits for the size scale as |
cell_size_scale_method |
indicates how values are mapped to cell sizes,
either |
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 |
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 |
cell_uncertainty |
a numeric matrix with the same dimensions as |
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 |
cell_split |
a numeric matrix with the same dimensions as |
cell_split_labels |
two labels for the halves of the cells in the
legend - the values in |
cell_split_size |
a numeric matrix with the same dimensions as
|
cell_col_empty |
a colour to use for missing values in |
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 |
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 |
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_border_mask |
a matrix of the same dimensions as |
cell_text |
logical indicating whether the values in |
cell_text_font |
an integer to control the font face of cell text, set
to 1 by default. See |
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 |
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 |
bar_type_x |
the type of plot drawn for |
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 |
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 |
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 |
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 |
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 |
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 |
bar_type_y |
the type of plot drawn for |
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 |
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 |
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 |
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 |
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 |
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 |
axis_text_side_x |
indicates whether the x axis text should be on the
|
axis_text_font_x |
integer to control the font face of x axis labels,
set to 1 by default. See |
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
|
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
|
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
|
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 |
axis_text_side_y |
indicates whether the y axis text should be on the
|
axis_text_font_y |
integer to control the font face of y axis labels,
set to 1 by default. See |
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
|
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 |
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
|
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 |
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 |
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
|
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
|
annotation_y |
a data.frame of metadata describing the rows of
|
annotation_colours |
a named list of colours for the annotations, e.g.
|
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
|
legend_side |
where to draw the legend, either |
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_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
|
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
|
legend_size_format |
the text of the size legend: |
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 |
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 |
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 |
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
|
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 |
mark_labels_x, mark_labels_y
|
labels for the columns or rows in
|
mark_line_col |
colour of the leader lines connecting mark labels to
their rows or columns, set to |
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 |
zoom_size_x, zoom_size_y
|
size of the zoom panel relative to the
heatmap - its height for |
zoom_side_x, zoom_side_y
|
the side of the heatmap each zoom panel is
drawn on: |
cell_raster |
whether to draw the cells as raster images, which is much
faster and gives smaller files for large heatmaps. Set to |
cell_values |
a matrix of lists with the same dimensions as |
cell_glyph |
how the values in |
cell_glyph_range |
the range of values spanned by each glyph, shared
by the cells of each |
cell_glyph_col |
colour of the lines of the glyphs, set to
|
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 |
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
|
assay |
the values of single-cell data to show: an assay of a
|
group_by |
the group of each cell (e.g. its cluster or cell type): the
name of a column of the cells' metadata ( |
group_max |
the largest number of cells to show from each group of
|
annotation_by |
annotations of the cells drawn as tracks beside the
heatmap (as |
swap_axes |
logical indicating whether single-cell data should be
drawn with one row per feature and one column per cell (as Seurat's
|
transform |
|
cofactor |
the cofactor of |
scale_q |
the quantile of |
bimodal |
|
style |
a style from |
... |
additional arguments passed to |
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.
Dillon Hammill ([email protected])
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/
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 )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 )
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.
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", ... )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", ... )
x |
a named list of two or more numeric matrices or data.frames (e.g.
from |
main |
the data set (name or position) whose rows are clustered, set to the first by default. |
axis |
|
scale, scale_method
|
how to scale each data set before it is drawn:
|
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 |
tree_kmeans |
the number of k-means clusters of the shared rows
(columns with |
tree_blocks |
logical, whether to cluster the columns (rows with
|
dist_method, clust_method, tree_order
|
how the shared rows are
clustered: as |
... |
other arguments of |
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().
an object of class heat_map, as returned by
heat_map.
heat_map (cell_col_blocks_x),
heat_map_summarise
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 )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 )
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.
heat_map_app( x = NULL, ..., allow_code = TRUE, max_upload = 1024, launch.browser = interactive() )heat_map_app( x = NULL, ..., allow_code = TRUE, max_upload = 1024, launch.browser = interactive() )
x |
data to start with: a matrix, data frame or single-cell object
(anything |
... |
settings to start with, named by the arguments of
|
allow_code |
logical indicating whether settings may be R code run in
this R session (such as |
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 |
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.
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.
Dillon Hammill ([email protected])
heat_map, heat_map_html,
heat_map_save
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") }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") }
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.
heat_map_arrange( ..., layout = NULL, share = c("colour", "size"), popup = TRUE, popup_size = NULL )heat_map_arrange( ..., layout = NULL, share = c("colour", "size"), popup = TRUE, popup_size = NULL )
... |
heatmaps (objects of class |
layout |
the layout of the panels, as in |
share |
what the heatmaps share: |
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 |
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.
a list of the redrawn heatmaps (objects of class heat_map),
invisibly.
Dillon Hammill ([email protected])
heat_map_custom, heat_map_save
# 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)# 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)
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.
heat_map_check_colours( x, deficiency = c("deuteranopia", "protanopia", "tritanopia"), min_difference = 10 )heat_map_check_colours( x, deficiency = c("deuteranopia", "protanopia", "tritanopia"), min_difference = 10 )
x |
a heatmap (an object of class |
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. |
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.
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.
Dillon Hammill ([email protected])
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/
heat_map_describe for alternative text
# 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)# 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
heat_map_clust( x, tree = "row", dist = "euclidean", method = "complete", scale = FALSE, cut = NULL, order = "default", max = 5000, ... )heat_map_clust( x, tree = "row", dist = "euclidean", method = "complete", scale = FALSE, cut = NULL, order = "default", max = 5000, ... )
x |
matrix-like object to cluster - its numeric columns. Distances,
linkage and cuts are computed in compiled code (only a distance function
supplied to |
tree |
indicates whether hierarchical clustering should be performed by
|
dist |
method passed to |
method |
agglomeration method, one of the methods of
|
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 |
order |
how the branches of the dendrogram are ordered:
|
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 |
... |
additional arguments passed to |
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.
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.
Dillon Hammill ([email protected])
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
# 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# 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
heat_map_complete()heat_map_complete()
No return value, called for side effects.
Dillon Hammill ([email protected])
# 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()# 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()
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.
heat_map_composition( x, group_by, sample_by, annotation_by = NULL, values = c("proportion", "percent", "count", "clr"), bars = TRUE, tree_y = TRUE, ... )heat_map_composition( x, group_by, sample_by, annotation_by = NULL, values = c("proportion", "percent", "count", "clr"), bars = TRUE, tree_y = TRUE, ... )
x |
single-cell data (see |
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
|
annotation_by |
columns of the metadata that describe the samples
(e.g. |
values |
what each cell of the heatmap shows: |
bars |
logical, whether to draw the number of cells of each sample as
bars beside the rows, set to |
tree_y |
logical, whether to cluster the samples, set to |
... |
other arguments of |
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.
an object of class heat_map, as returned by
heat_map; heat_map_info()$data holds the values, one
row per sample.
Dillon Hammill ([email protected])
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
heat_map_summarise (stack_by) for the make-up
of groups as stacked bars
cells <- heat_map_example("rna") heat_map_composition( cells, group_by = "cell_type", sample_by = "sample", annotation_by = "condition", popup = FALSE )cells <- heat_map_example("rna") heat_map_composition( cells, group_by = "cell_type", sample_by = "sample", annotation_by = "condition", popup = FALSE )
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).
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, ... )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, ... )
x |
single-cell data (see |
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 |
sample_by |
the sample of each cell (e.g. the donor), as for
|
features |
the features to test and draw (names, indices or a named
list of groups of features), or |
assay |
the assay of single-cell objects (see |
contrast |
the two conditions compared, as |
values |
|
transform, cofactor
|
the transform of the values of the cells before
they are summarised, e.g. |
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 |
n |
the number of features drawn for each group when |
stars |
the adjusted p-values below which cells get one, two and
three stars, |
draw |
logical, whether to draw the heatmap (default) or only return the results. |
... |
other arguments of |
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.
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.
Dillon Hammill ([email protected])
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
heat_map_markers for markers of each group against
the other cells, heat_map_composition for differences in
the make-up of samples
# 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 )# 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 )
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.
heat_map_cor( x, method = c("pearson", "spearman", "kendall"), use = "pairwise.complete.obs", lower = "ellipse", upper = "number", diag = NULL, tree = TRUE, clust_method = "average", ... )heat_map_cor( x, method = c("pearson", "spearman", "kendall"), use = "pairwise.complete.obs", lower = "ellipse", upper = "number", diag = NULL, tree = TRUE, clust_method = "average", ... )
x |
a numeric matrix or data.frame whose columns are correlated with
|
method |
the correlation coefficient computed by
|
use |
how |
lower |
the shape of the cells below the diagonal, set to
|
upper |
the shape of the cells above the diagonal, set to
|
diag |
the cells on the diagonal: |
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 |
clust_method |
the agglomeration method passed to
|
... |
additional arguments passed to |
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.
a heat_map object (see heat_map) whose data
is the correlation matrix.
Dillon Hammill ([email protected])
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
# 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 )# 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 )
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).
heat_map_custom(popup = TRUE, popup_size = c(8, 8), layout = NULL, ...)heat_map_custom(popup = TRUE, popup_size = c(8, 8), layout = NULL, ...)
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 |
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 |
... |
additional arguments passed to |
No return value, called for side effects.
Dillon Hammill ([email protected])
heat_map_custom( popup = FALSE, layout = c(1,2) ) heat_map( mtcars ) plot( mtcars[, 1:2], pch = 16 ) heat_map_complete()heat_map_custom( popup = FALSE, layout = c(1,2) ) heat_map( mtcars ) plot( mtcars[, 1:2], pch = 16 ) heat_map_complete()
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.
heat_map_data(x, what = c("cells", "rows", "columns", "tree_x", "tree_y"))heat_map_data(x, what = c("cells", "rows", "columns", "tree_x", "tree_y"))
x |
object of class |
what |
the table to return: |
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.
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.
Dillon Hammill ([email protected])
heat_map_info for the same information as matrices
and vectors, and heat_map_grob to combine heatmaps with
ggplot2 plots.
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")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")
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.
heat_map_describe(x, digits = 3, max_groups = 8)heat_map_describe(x, digits = 3, max_groups = 8)
x |
object of class |
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. |
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.
a character string of class heat_map_description, printed
as wrapped text. Use as.character() for the plain string.
Dillon Hammill ([email protected])
hm <- heat_map( mtcars, scale = "zscore", tree = "both", tree_cut_y = 3, legend_title = "z-score", title = "mtcars", popup = FALSE ) heat_map_describe(hm)hm <- heat_map( mtcars, scale = "zscore", tree = "both", tree_cut_y = 3, legend_title = "z-score", title = "mtcars", popup = FALSE ) heat_map_describe(hm)
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.
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", ... )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", ... )
x |
single-cell data, a matrix or a data.frame (see
|
features |
the features to show (see |
group_by |
the group of each cell, the name of a column of its
metadata or a vector (see |
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
|
assay |
the values of single-cell data to show (see
|
scale |
how the means are scaled within each feature for their
colour: |
scale_limits |
the limits that scaled means are clipped to, set to
|
threshold |
values above |
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 |
swap_axes |
logical indicating whether the features should be drawn
as rows and the groups as columns, set to |
bimodal |
|
transform |
|
cofactor |
the cofactor of |
marker_colour, marker_size
|
for a dot plot of markers ( |
... |
other arguments passed to |
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.
Dillon Hammill ([email protected])
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
heat_map_markers, heat_map_summarise
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)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)
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.
heat_map_downsample(groups, n = 500, seed = 2357)heat_map_downsample(groups, n = 500, seed = 2357)
groups |
a vector with the group of each cell (e.g. its cluster).
Cells without a group ( |
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. |
the indices of the cells kept, in increasing order.
Dillon Hammill ([email protected])
groups <- rep(c("T cells", "B cells", "NK cells"), c(2000, 300, 40)) keep <- heat_map_downsample(groups, n = 100) table(groups[keep])groups <- rep(c("T cells", "B cells", "NK cells"), c(2000, 300, 40)) keep <- heat_map_downsample(groups, n = 100) table(groups[keep])
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.
heat_map_example( type = c("rna", "cytometry", "trajectory"), class = c("data.frame", "SingleCellExperiment"), n = NULL )heat_map_example( type = c("rna", "cytometry", "trajectory"), class = c("data.frame", "SingleCellExperiment"), n = NULL )
type |
the kind of data: |
class |
|
n |
the number of cells (or events), set to |
"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.
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.
Dillon Hammill ([email protected])
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
heat_map, heat_map_dot,
heat_map_markers, heat_map_summarise,
heat_map_smooth
# 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)# 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)
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.
heat_map_grob(x, ...)heat_map_grob(x, ...)
x |
object of class |
... |
arguments passed to |
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().
a grob that draws the heatmap.
Dillon Hammill ([email protected])
heat_map_data to rebuild a heatmap with
ggplot2 from its data.
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) }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) }
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:
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() )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() )
x |
a heatmap (an object of class |
... |
arguments of |
file |
the HTML file to write, or |
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 |
|
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. |
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.
an object of class heat_map_html, invisibly: the path of the
page (file), with its size. Printing it opens the page.
Dillon Hammill ([email protected])
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)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)
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.
heat_map_info(x)heat_map_info(x)
x |
object of class |
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.
Dillon Hammill ([email protected])
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]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
heat_map_layout(layout = NULL)heat_map_layout(layout = NULL)
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 |
No return value, called for side effects.
Dillon Hammill ([email protected])
# 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()# 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()
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.
heat_map_markers( x, group_by, features = NULL, assay = NULL, n = 5, min_detected = 0.1, min_logfc = 0.25, threshold = 0 )heat_map_markers( x, group_by, features = NULL, assay = NULL, n = 5, min_detected = 0.1, min_logfc = 0.25, threshold = 0 )
x |
single-cell data, a matrix or a data.frame (see
|
group_by |
the group of each cell, the name of a column of its
metadata or a vector (see |
features |
the features to score, set to |
assay |
the values of single-cell data to score (see
|
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 |
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.
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.
Dillon Hammill ([email protected])
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
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)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)
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.
heat_map_new(popup = FALSE, popup_size = c(8, 8), ...)heat_map_new(popup = FALSE, popup_size = c(8, 8), ...)
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 |
... |
additional arguments passed to
|
No return value, called for side effects.
Dillon Hammill, [email protected]
# Open platform-specific graphics device heat_map_new(popup = TRUE)# Open platform-specific graphics device heat_map_new(popup = TRUE)
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.
heat_map_read_h5ad(file)heat_map_read_h5ad(file)
file |
the path of an |
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.
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.
Dillon Hammill ([email protected])
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] }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 custom heatmap layout on current graphics device and save to an R object for future use.
heat_map_record()heat_map_record()
an object of class recordedplot.
Dillon Hammill ([email protected])
# 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()# 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
heat_map_reset()heat_map_reset()
No return value, called for side effects.
Dillon Hammill ([email protected])
# Reset HeatmapR settings heat_map_reset()# Reset HeatmapR settings heat_map_reset()
Save high resolution images
heat_map_save( save_as, width = 7, height = 7, units = "in", res = 300, multiple = FALSE, layout = NULL, x = NULL, ... )heat_map_save( save_as, width = 7, height = 7, units = "in", res = 300, multiple = FALSE, layout = NULL, x = NULL, ... )
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 |
height |
numeric indicating the height of the exported plot in
|
units |
units to be used to set plot size, can be either pixels
( |
res |
resolution in dpi, set to 300 by default. |
multiple |
logical indicating whether multiple pages should be saved to
separate numbered files, set to |
layout |
a vector or matrix defining the custom layout of the plot to be
created using |
x |
optional |
... |
additional arguments for the appropriate |
No return value, called for side effects.
Dillon Hammill ([email protected])
# 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)# 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)
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.
heat_map_scale(x, scale = "column", method = "range", cofactor = 5, q = 0.01)heat_map_scale(x, scale = "column", method = "range", cofactor = 5, q = 0.01)
x |
matrix-like object to be scaled. |
scale |
indicates whether the data should be scaled by |
method |
type of scaling to perform, one of |
cofactor |
the cofactor of the |
q |
the quantile of quantile scaling, set to 0.01 by default. |
a matrix or data.frame containing the scaled data.
Dillon Hammill ([email protected])
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
# 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)# 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)
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").
heat_map_score( x, sets, assay = NULL, method = c("zscore", "mean", "module"), bins = 30, controls = 100, seed = 1, min_size = 1 )heat_map_score( x, sets, assay = NULL, method = c("zscore", "mean", "module"), bins = 30, controls = 100, seed = 1, min_size = 1 )
x |
single-cell data: a SingleCellExperiment, SummarizedExperiment or
Seurat object, a sparse matrix or a matrix or data.frame of cells by
features (see |
sets |
a named list of sets of features, each a vector of the names
of features of |
assay |
the values of single-cell data to score (see
|
method |
|
bins, controls
|
the number of bins of features by mean expression and
of control features drawn for each feature of a set, for |
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 |
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.
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.
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
heat_map_dot, heat_map_summarise
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)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)
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.
heat_map_smooth( x, along, features = NULL, assay = NULL, bins = 100, span = 5, binning = "cells", group_by = NULL )heat_map_smooth( x, along, features = NULL, assay = NULL, bins = 100, span = 5, binning = "cells", group_by = NULL )
x |
single-cell data (a |
along |
the position of each cell along the trajectory: the name of
a numeric column of the cells' metadata (or of |
features |
the features to smooth, as names (or indices); see
|
assay |
the values of single-cell data to smooth; see
|
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 |
|
group_by |
the lineage of each cell, for trajectories with one
|
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.
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.
Dillon Hammill ([email protected])
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
# 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 )# 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 )
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.
heat_map_style(...)heat_map_style(...)
... |
settings, named by the arguments of |
an object of class heat_map_style, a named list of settings.
Dillon Hammill ([email protected])
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)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)
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.
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 )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 )
x |
a matrix or data.frame, or single-cell data (a
|
group_x |
a vector assigning each column of |
group_y |
a vector assigning each row of |
fun |
the summary of the values in each group, one of |
threshold |
values above |
features |
the features of single-cell data to summarise, as names
(or indices); see |
assay |
the values of single-cell data to summarise; see
|
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 |
transform |
|
cofactor |
the cofactor of |
scale |
the scaling of each feature (column): |
q |
the quantile of |
scale_when |
|
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 |
bimodal |
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
|
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).
Dillon Hammill ([email protected])
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
# 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)# 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)
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.
heat_map_threads(threads = NULL)heat_map_threads(threads = NULL)
threads |
the number of threads to use from now on (a whole number of
at least 1), |
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.
the number of threads in use. When threads is given, the
number in use before, invisibly.
# THREADS IN USE heat_map_threads() # ONE THREAD, THEN BACK TO THE PREVIOUS SETTING old <- heat_map_threads(1) heat_map_threads(old)# THREADS IN USE heat_map_threads() # ONE THREAD, THEN BACK TO THE PREVIOUS SETTING old <- heat_map_threads(1) heat_map_threads(old)
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.
## S3 method for class 'heat_map' plot(x, ...) ## S3 method for class 'heat_map' print(x, ...)## S3 method for class 'heat_map' plot(x, ...) ## S3 method for class 'heat_map' print(x, ...)
x |
object of class |
... |
additional arguments passed to |
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.
x, invisibly.
hm <- heat_map(mtcars, scale = "column", popup = FALSE) plot(hm, title = "mtcars") plot(hm, data = mtcars[1:10, ])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
## S3 method for class 'heat_map_description' print(x, width = getOption("width"), ...)## S3 method for class 'heat_map_description' print(x, width = getOption("width"), ...)
x |
object of class |
width |
width of the wrapped text, set to the console width by default. |
... |
not used. |
x, invisibly.