Package 'bixverse.plots'

Title: Plotting functions for bixverse
Description: This package contains various plotting helpers for the core functions of the bixverse package.
Authors: Gregor Lueg [aut, cre], Liesbeth François [aut]
Maintainer: Gregor Lueg <[email protected]>
License: MIT + file LICENSE
Version: 0.2.9
Built: 2026-10-14 23:54:48 UTC
Source: https://github.com/GregorLueg/bixverse.plots

Help Index


Per-metric density plots from a CellQc object

Description

Requires grouped data; outlier groups are read from per_group_stats.

Usage

## S3 method for class 'CellQc'
density_plot_sc(x, adjust_position_label = 0, palette = BX_PALETTES, ...)

Arguments

x

A CellQc object.

adjust_position_label

Numeric. x-offset for the labels (default: 0).

palette

String. Discrete palette for the group fills and labels. One of c("main", "sequential", "diverging", "viridis", "spectral"), see bx_colors().

...

Ignored.

Value

A named list of ggplot objects, one per metric.


Density plot from a data.table

Description

Group-level outliers are recomputed from per-group medians.

Usage

## S3 method for class 'data.table'
density_plot_sc(
  x,
  grouping_column,
  variable,
  direction = c("twosided", "below", "above"),
  threshold = 3,
  var_name = NULL,
  log_scale = TRUE,
  adjust_position_label = 0,
  palette = BX_PALETTES,
  ...
)

Arguments

x

data.table. Input data containing the QC metric.

grouping_column

Character. Column used to group the densities.

variable

Character. Numeric column to plot on the x-axis.

direction

Character. One of "twosided", "below", "above".

threshold

Numeric. Number of MADs for outlier detection (default: 3).

var_name

Character. x-axis label (default: NULL).

log_scale

Logical. Apply a log10 x-axis (default: TRUE).

adjust_position_label

Numeric. x-offset for the labels (default: 0).

palette

String. Discrete palette for the group fills and labels. One of c("main", "sequential", "diverging", "viridis", "spectral"), see bx_colors().

...

Ignored.

Value

A ggplot object.


Dot plot of marker gene expression across groups

Description

Dot plot of marker gene expression across groups

Usage

dot_plot_sc(
  object,
  features,
  grouping_variable,
  feature_labels = NULL,
  feature_grouping = NULL,
  scale_exp = TRUE,
  modality = c("rna", "adt"),
  cluster_groups = TRUE,
  palette = c("sequential", "spectral", "viridis", "diverging")
)

Arguments

object

A single cell class.

features

Character vector. Gene IDs to plot.

grouping_variable

String. Obs column to group by.

feature_labels

Optional named character vector mapping gene ids to display labels (default: NULL).

feature_grouping

Optional named character vector mapping gene ids to grouping labels, e.g. cell type labels. If feature_labels is provided, the character vectors should contain the mapping of feature display labels to their respecitve groups (e.g. c(CD3E = "T cell", CD8A = "T cell", MS4A1 = "B cell", ...). (default: NULL).

scale_exp

Boolean. Whether to min-max scale mean expression per gene.

modality

String. One of c("rna", "adt").

cluster_groups

Boolean. Use hierarchical clustering on the grouping variable to re-order the group labels based on expression similarity.

palette

String. Continuous palette for the scaled expression. One of c("sequential", "spectral", "viridis", "diverging"), see bx_colors().

Value

A ggplot object.


Embedding plot coloured by an obs column

Description

Embedding plot coloured by an obs column

Usage

embedding_plot_sc(
  object,
  embedding,
  colour_by,
  label_by = NULL,
  discrete = NULL,
  embd_modality = c("rna", "adt", "wnn"),
  point_size = NULL,
  point_alpha = 0.5,
  raster = NULL,
  raster_dpi = c(512, 512),
  palette = NULL,
  label_size = 3,
  label_color = "black",
  label_font = "bold"
)

Arguments

object

A single cell class.

embedding

String. Name of the embedding (e.g. "umap").

colour_by

String. Obs column to colour by.

label_by

String. Optional obs column to label by. (default: NULL).

discrete

Optional boolean. Force a discrete scale by coercing colour_by to a factor. NULL (default) picks the scale from the column type.

embd_modality

String. Modality the embedding is pulled from. One of c("rna", "adt", "wnn"). Use "wnn" for WNN-derived embeddings.

point_size

Optional numeric. Defines the point size. If not provided, will be auto-determined.

point_alpha

Numeric. Defines the alpha.

raster

Optional boolean. Shall the plot be rasterised. If NULL and number of cells is larger than 1e5, defaults to TRUE.

raster_dpi

Two numerics. Pixel resolution for rasterized plots, passed to geom_scattermore(). Default is c(512, 512).

palette

Optional string. Palette for the colour scale, see bx_colors(). NULL (default) resolves to "main" if colour_by is discrete and "sequential" if it is continuous.

label_size

Numeric. Size of the labels

label_color

String. Color fo the labels.

label_font

String. Font of the labels. bixverse::extract_embedding_data().

Value

A ggplot object.


Generate enrichment map igraph (for GSEA)

Description

Helper function to generate an enrichment map based on GSEA results. Similar enriched gene sets are clustered together via their Jaccard similarity (alternatively overlap coefficient) and the function returns an igraph object for subsequent visualisations.

Usage

enrichment_map_gsea(
  res,
  threshold,
  pathways,
  overlap_coefficient = FALSE,
  min_sim = 0.2,
  resolution = 1,
  layout_func = igraph::layout_with_fr,
  ...
)

Arguments

res

data.table with the enrichment results. Needs to have the columns c("pathway_name", "nes", "fdr"), i.e. the output of bixverse::calc_fgsea() or bixverse::calc_blitzgsea(). A geneset_name column is accepted with a deprecation warning.

threshold

Numeric. The FDR threshold you wish to filter for.

pathways

Named list. The original pathway list used for the calculation of the overenrichment analysis.

overlap_coefficient

Boolean. Shall the overlap coefficient be used instead of the Jaccard similarity.

min_sim

Numeric. Minimum similarity between two gene sets to be connected.

resolution

Numeric. The resolution parameter for the Louvain clustering.

layout_func

Layout function. Please see igraph::add_layout_() for options. This one will be used to layout the graph.

...

Further parameters to forward to wrap_and_truncate().

Value

igraph object representing the enrichment map.


Generate enrichment map igraph (for overenrichment tests)

Description

Helper function to generate an enrichment map based on overenrichment results. Similar enriched gene sets are clustered together via their Jaccard similarity (alternatively overlap coefficient) and the function returns an igraph object for subsequent visualisations.

Usage

enrichment_map_oae(
  res,
  threshold,
  pathways,
  overlap_coefficient = FALSE,
  min_sim = 0.2,
  resolution = 1,
  layout_func = igraph::layout_with_fr,
  ...
)

Arguments

res

data.table with the enrichment results. Needs to have the columns c("gene_set_name", "fdr").

threshold

Numeric. The FDR threshold you wish to filter for.

pathways

Named list. The original pathway list used for the calculation of the overenrichment analysis.

overlap_coefficient

Boolean. Shall the overlap coefficient be used instead of the Jaccard similarity.

min_sim

Numeric. Minimum similarity between two gene sets to be connected.

resolution

Numeric. The resolution parameter for the Louvain clustering.

layout_func

Layout function. Please see igraph::add_layout_() for options. This one will be used to layout the graph.

...

Further parameters to forward to wrap_and_truncate().

Value

igraph object representing the enrichment map.


Feature plot over an embedding

Description

Plots the expression of one or more features over an embedding. By default every feature gets its own panel and its own colour bar (scale_mode = "free"), so a weakly expressed gene is not flattened by whatever the loudest gene in the set happens to be. Use scale_mode = "shared" for a single faceted plot with one colour bar across all features.

Usage

feature_plot_sc(
  object,
  features,
  embedding,
  feature_labels = NULL,
  scale = FALSE,
  clip = NULL,
  expr_modality = c("rna", "adt"),
  embd_modality = c("rna", "adt", "wnn"),
  point_size = NULL,
  point_alpha = 0.5,
  raster = NULL,
  raster_dpi = c(512, 512),
  label_by = NULL,
  label_size = 3,
  label_color = "black",
  label_font = "bold",
  highlight_features = FALSE,
  highlight_quantile = 0.25,
  scale_mode = c("free", "shared"),
  palette = c("sequential", "spectral", "viridis", "diverging"),
  ncol = NULL,
  ...
)

Arguments

object

A single cell class.

features

Character vector. Gene/feature IDs to plot, taken from expr_modality.

embedding

String. Name of the embedding.

feature_labels

Optional named character vector mapping gene ids to display labels (default: NULL).

scale

Boolean. Whether to z-score the expression values.

clip

Optional numeric. Clip z-scores if scale = TRUE.

expr_modality

String. Modality the expression is pulled from. One of c("rna", "adt").

embd_modality

String. Modality the embedding is pulled from. One of c("rna", "adt", "wnn"). Use "wnn" for WNN-derived embeddings.

point_size

Optional numeric. Defines the point size. If not provided, will be auto-determined.

point_alpha

Numeric. Defines the alpha.

raster

Optional boolean. Shall the plot be rasterised. If NULL and number of cells is larger than 1e5, defaults to TRUE.

raster_dpi

Two numerics. Pixel resolution for rasterized plots, passed to geom_scattermore(). Default is c(512, 512).

label_by

String. Optional obs column to label by. (default: NULL).

label_size

Numeric. Size of the labels

label_color

String. Color fo the labels.

label_font

String. Font of the labels.

highlight_features

Boolean. Shall the features be more strongly highlighted. Useful for sparsely expressed genes.

highlight_quantile

Numeric between ⁠[0, 1]⁠. Defines the threshold.

scale_mode

String. One of c("free", "shared"). With "free" each feature is drawn as its own plot with its own colour bar and the panels are combined with patchwork::wrap_plots(). With "shared" all features go into one faceted plot with a single colour bar fitted to the pooled expression.

palette

String. Continuous palette for the expression values. One of c("sequential", "spectral", "viridis", "diverging"), see bx_colors().

ncol

Optional integer. Number of columns of the panel grid. Only has an effect if scale_mode = "free". If NULL, patchwork picks the layout.

...

Additional arguments forwarded to bixverse::extract_feature_plot_data() and onward to get_embedding(). Do not pass modality here; use embd_modality instead.

Value

A patchwork object if scale_mode = "free", otherwise a ggplot object.


Scatter / hex plot of two features against each other

Description

Plots two features against each other (typical use case: protein vs mRNA on ADT/RNA data). Each feature may carry a ⁠_rna⁠ or ⁠_adt⁠ suffix to select its modality independently; unsuffixed features fall back to modality. With geom = "density" points are coloured by 2D KDE, with geom = "hex" cells are binned into hexagons.

Usage

feature_scatter_plot_sc(
  object,
  feature_1,
  feature_2,
  geom = c("density", "hex"),
  remove_zeros = TRUE,
  smoothness = 10,
  bins = 60,
  modality = c("rna", "adt"),
  point_size = 2.5,
  point_alpha = 0.5,
  raster = NULL,
  raster_dpi = c(512, 512),
  palette = c("viridis", "sequential", "spectral", "diverging")
)

Arguments

object

A single cell class.

feature_1

String. First feature (x-axis), optionally ⁠_rna⁠ / ⁠_adt⁠ suffixed.

feature_2

String. Second feature (y-axis), optionally ⁠_rna⁠ / ⁠_adt⁠ suffixed.

geom

String. "density" or "hex" (default: "density").

remove_zeros

Boolean. Drop cells where both features are zero (default: TRUE).

smoothness

Numeric. Bandwidth multiplier for the KDE (default: 10). Only used for geom = "density".

bins

Numeric. Number of hex bins (default: 60). Only used for geom = "hex".

modality

String. Fallback modality for unsuffixed features. One of c("rna", "adt").

point_size

Numeric. Point size for density plots (default: 2.5).

point_alpha

Numeric. Alpha for density plots (default: 0.5).

raster

Optional boolean. Shall the plot be rasterised. If NULL and n_cells > 1e5, defaults to TRUE. Only applies to geom = "density".

raster_dpi

Two numerics. Pixel resolution for rasterised plots (default: c(512, 512)).

palette

String. Continuous palette for the density / count scale. One of c("viridis", "sequential", "spectral", "diverging"), see bx_colors().

Value

A ggplot object.


Helper function to get the plot data for GSEA plots

Description

Helper function to get the plot data for GSEA plots

Usage

get_gsea_enrichment_data(
  stats,
  pathways,
  pathways_of_interest,
  gsea_results = NULL,
  gsea_param = 1
)

Arguments

stats

Named numeric vector. The gene level statistic.

pathways

List. A named list with each element containing the genes for this pathway.

pathways_of_interest

String vector. Names of the pathways to plot. These strings need to be represented in the names of pathways.

gsea_results

Optional data.table with the bixverse GSEA results. If provided, the FDR and NES for the given pathway of interest will be also added to the plot.

gsea_param

Numeric. Defaults to 1.

Value

A named list of gsea_par_plot_data objects, one per pathway that survived the size filters. Each one is a list with the following elements:

  • curve_dt - data.table with the running enrichment score, columns rank and ES.

  • ticks_dt - data.table with the positions of the pathway genes, columns rank and stat.

  • stats_dt - data.table with the ranked statistic, columns rank and stat.

  • key_points - Named numeric with pos_es, neg_es and spread_es, plus nes and fdr if gsea_results was provided.

  • additional_label - String or NULL. The NES/FDR annotation.


Heatmap of marker genes x cells across groups

Description

The classic marker heatmap to show which cluster is what: genes as rows, cells as columns, cells grouped by grouping_variable with white gaps and a colour strip per group. With feature_grouping the genes get grouped per cell type, too. Every block of cell group x gene group is drawn as one raster, not one tile per cell.

PDF viewers tend to smooth embedded rasters. If the blocks look blurry in a PDF, save as PNG instead.

Usage

heatmap_plot_sc(
  object,
  features,
  grouping_variable,
  feature_labels = NULL,
  feature_grouping = NULL,
  scale = TRUE,
  clip = 2.5,
  modality = c("rna", "adt"),
  max_cells_per_group = NULL,
  seed = 42L,
  group_gap = 0.002,
  show_feature_labels = NULL,
  palette = c("diverging", "spectral", "viridis", "sequential")
)

Arguments

object

A single cell class.

features

Character vector. Gene IDs to plot, one row each, in this order.

grouping_variable

String. Obs column to group the cells by. Factor levels set the group order.

feature_labels

Optional named character vector mapping gene ids to display labels (default: NULL).

feature_grouping

Optional named character vector mapping gene ids to grouping labels, e.g. cell type labels. If feature_labels is provided, the character vectors should contain the mapping of feature display labels to their respective groups (e.g. c(CD3E = "T cell", CD8A = "T cell", MS4A1 = "B cell", ...). Groups are ordered by first appearance. (default: NULL).

scale

Boolean. Whether to z-score the expression values per gene.

clip

Optional numeric. Clip z-scores if scale = TRUE. Without it a handful of extreme cells flatten the colour range.

modality

String. One of c("rna", "adt").

max_cells_per_group

Optional integer. Subsample every group to at most this many cells. NULL (default) draws all cells.

seed

Integer. Seed for the subsampling.

group_gap

Numeric between ⁠[0, 0.1]⁠. Width of each gap between groups as fraction of the axis length. 0 removes the gaps.

show_feature_labels

Optional boolean. Shall the gene names be shown. NULL (default) shows them for up to 80 genes.

palette

String. Continuous palette for the expression values. One of c("diverging", "spectral", "viridis", "sequential"), see bx_colors().

Value

A ggplot object.


Joint QC plot from a CellQc object

Description

Joint QC plot from a CellQc object

Usage

## S3 method for class 'CellQc'
joint_plot_sc(
  x,
  library_size = "log10_lib_size",
  nb_features = "log10_nnz",
  palette = c("sequential", "spectral", "viridis", "diverging"),
  ...
)

Arguments

x

A CellQc object.

library_size

Character. Column with the library size per cell.

nb_features

Character. Column with the number of features per cell.

palette

String. Continuous palette for the hexbin fill. One of c("sequential", "spectral", "viridis", "diverging"), see bx_colors().

...

Ignored.

Value

A ggExtraPlot object.


Joint QC plot from a data.table

Description

Joint QC plot from a data.table

Usage

## S3 method for class 'data.table'
joint_plot_sc(
  x,
  library_size = "lib_size",
  nb_features = "nnz",
  log_scale = FALSE,
  palette = c("sequential", "spectral", "viridis", "diverging"),
  ...
)

Arguments

x

data.table. Input data containing the QC metrics.

library_size

Character. Column with the library size per cell.

nb_features

Character. Column with the number of features per cell.

log_scale

Logical. Log10-transform both axes (default: FALSE).

palette

String. Continuous palette for the hexbin fill. One of c("sequential", "spectral", "viridis", "diverging"), see bx_colors().

...

Ignored.

Value

A ggExtraPlot object.


Label Centroids in Scatter Plots

Description

Adds boxed text labels at the centroid position of each group in a scatter plot. Computes group centroids with data.table for efficient summarisation. Useful for labelling cluster centres in embedding or dimensionality reduction plots (UMAP, t-SNE, PCA).

Usage

label_centroids(
  data = NULL,
  label_by,
  colour = "black",
  fill = "white",
  alpha = 0.5,
  label.size = 0,
  size = 4,
  fontface = "bold",
  ...
)

Arguments

data

A data.frame or data.table containing the scatter plot points. If NULL, the data from the parent ggplot is used. Must contain the columns referenced by the parent plot's x/y aesthetics and by label_by.

label_by

Character. Name of the (discrete) column to group and label by.

colour

Text colour. Default: "black".

fill

Box fill colour. Default: "white".

alpha

Box fill transparency in [0, 1]. Default: 0.5.

label.size

Box border line width in mm. Set to 0 to hide the border. Default: 0.

size

Text size in mm. Default: 4.

fontface

Font face. Default: "bold".

...

Additional arguments passed to geom_label.

Value

A ggplot layer.

Examples

## Not run: 
embedding_plot_sc(
  object = sc_object,
  embedding = "umap",
  colour_by = "donor_id"
) +
  label_centroids(label_by = "donor_id")

## End(Not run)

miloR neighbourhood graph over an embedding

Description

The Milo neighbourhood graph figure: every tested neighbourhood sits at its index cell in an embedding, sized by its cell count and connected to the neighbourhoods it shares cells with. With colour_by = "logFC" the significant neighbourhoods are filled by their logFC and drawn on top, strongest last, while the rest stay white underneath.

Usage

milo_nhood_plot_sc(
  object,
  milo_res,
  embedding = "umap",
  alpha = 0.1,
  overlap = 1L,
  colour_by = c("logFC", "majority_celltype"),
  show_cells = TRUE,
  embd_modality = c("rna", "adt", "wnn"),
  point_size = NULL,
  point_alpha = 0.4,
  raster = NULL,
  raster_dpi = c(512, 512),
  cell_colour = "grey90",
  edge_colour = "grey50",
  edge_width = c(0.1, 1.5),
  size_range = c(0.5, 4),
  palette = NULL
)

Arguments

object

A single cell class. The one the miloR result was built on.

milo_res

miloR class, run through bixverse::test_nhoods().

embedding

String. Name of the embedding to position the nodes in.

alpha

Numeric. Spatial FDR threshold for a neighbourhood to count as significant (default: 0.1).

overlap

Integer. Minimum number of shared cells for an edge (default: 1L).

colour_by

String. One of c("logFC", "majority_celltype"). The latter needs bixverse::add_nhoods_info() to have been run.

show_cells

Boolean. Draw the cells underneath the graph (default: TRUE).

embd_modality

String. One of c("rna", "adt", "wnn"). Modality the embedding is pulled from.

point_size

Optional numeric. Size of the cells. If not provided, will be auto-determined.

point_alpha

Numeric. Alpha of the cells (default: 0.4).

raster

Optional boolean. Shall the cell layer be rasterised. If NULL and the number of cells is larger than 1e5, defaults to TRUE.

raster_dpi

Two numerics. Pixel resolution for rasterized plots, passed to geom_scattermore(). Default is c(512, 512).

cell_colour

String. Colour of the cell layer (default: "grey90").

edge_colour

String. Colour of the edges (default: "grey50").

edge_width

Two numerics. Range the edge widths are scaled into (default: c(0.1, 1.5)).

size_range

Two numerics. Range the node sizes are scaled into (default: c(0.5, 4)).

palette

Optional string. Palette for the nodes, see bx_colors(). NULL (default) resolves to "diverging" for logFC, centred at zero, and "main" for the cell types.

Value

A ggplot object.

References

Dann, et al., Nat Biotechnol, 2022.


PAGA abstracted graph over an embedding

Description

Draws the PAGA graph with every cluster sitting at the centroid of its cells in an embedding, over a faint scatter of the cells themselves. A free layout of the abstracted graph puts the nodes somewhere arbitrary, which the reader then has to relate back to the embedding by hand. This does not.

The abstracted graph is close to complete on real data, so threshold is doing real work and dropping it to zero gives a hairball. tree_only is the shortcut to the backbone.

Usage

paga_plot_sc(
  object,
  paga_res,
  embedding = "umap",
  threshold = 0.01,
  tree_only = FALSE,
  node_colour_by = NULL,
  show_cells = TRUE,
  label = TRUE,
  embd_modality = c("rna", "adt", "wnn"),
  centroid = c("median", "mean"),
  point_size = NULL,
  point_alpha = 0.4,
  raster = NULL,
  raster_dpi = c(512, 512),
  cell_colour = "grey80",
  edge_colour = "grey40",
  edge_width = c(0.2, 3),
  max_node_size = 12,
  palette = NULL,
  label_size = 3,
  label_color = "black",
  label_font = "bold"
)

Arguments

object

A single cell class.

paga_res

PagaRes class. The output of bixverse::run_paga_sc(), run on this object.

embedding

String. Name of the embedding to position the nodes in.

threshold

Numeric. Edges below this connectivity are dropped (default: 0.01).

tree_only

Boolean. Draw the maximum spanning forest rather than the full abstracted graph (default: FALSE).

node_colour_by

Optional string. A numeric obs column summarised per cluster, e.g. "palantir_pseudotime", giving continuously coloured nodes. NULL (default) colours the nodes discretely by cluster.

show_cells

Boolean. Draw the cells underneath the graph (default: TRUE).

label

Boolean. Label the nodes with their cluster (default: TRUE).

embd_modality

String. One of c("rna", "adt", "wnn"). Modality the embedding is pulled from.

centroid

String. One of c("median", "mean"). How a cluster's position is summarised. Median by default, since embeddings throw stragglers that drag a mean off its cluster.

point_size

Optional numeric. Size of the cells. If not provided, will be auto-determined.

point_alpha

Numeric. Alpha of the cells (default: 0.4).

raster

Optional boolean. Shall the cell layer be rasterised. If NULL and the number of cells is larger than 1e5, defaults to TRUE.

raster_dpi

Two numerics. Pixel resolution for rasterized plots, passed to geom_scattermore(). Default is c(512, 512).

cell_colour

String. Colour of the cell layer (default: "grey80").

edge_colour

String. Colour of the edges (default: "grey40").

edge_width

Two numerics. Range the edge widths are scaled into (default: c(0.2, 3)).

max_node_size

Numeric. Size of the largest node. Node area tracks the cell count, which is what people read off it (default: 12).

palette

Optional string. Palette for the nodes, see bx_colors(). NULL (default) resolves to "main" for the discrete case and "sequential" when node_colour_by is given.

label_size

Numeric. Size of the labels.

label_color

String. Colour of the labels.

label_font

String. Font of the labels.

Value

A ggplot object.

References

Wolf, et al., Genome Biol., 2019.


Wrapper function for standard plot parameters

Description

Wrapper function for standard plot parameters

Usage

params_plots(
  width = 5,
  height = 5,
  file_type = c(".png", ".pdf"),
  unit = c("in", "px", "cm"),
  res = 450L,
  create_dir = TRUE
)

Arguments

width

Numeric. Width of the plot. Defaults to 5.0.

height

Numeric. Height of the plot. Defaults to 5.0.

file_type

String. Plot type to save. Might be expanded to other file types. One of c(".png", ".pdf"). Defaults to ".png".

unit

String. Unit type for width and height. One of c("in", "px", "cm"). Defaults to "in".

res

Integer. Resolution for PNGs. Defaults to 450L.

create_dir

Boolean. Shall the plot directory be generated recursively. Defaults to TRUE.

Value

A named list with the following elements:

  • width - Numeric. Width of the plot. Defaults to 5.0.

  • height - Numeric. Height of the plot. Defaults to 5.0.

  • file_type - String. Plot type to save. Might be expanded to other file types. One of c(".png", ".pdf"). Defaults to ".png".

  • unit - String. Unit type for width and height. One of c("in", "px", "cm"). Defaults to "in".

  • res - Integer. Resolution for PNGs. Defaults to 450L.

  • create_dir - Boolean. Shall the plot directory be generated recursively. Defaults to TRUE.


Wrapper function for volcano plot parameters

Description

Wrapper function for volcano plot parameters

Usage

params_volcano(
  x_axis = "log2FC",
  y_axis = "FDR",
  colour = NULL,
  label_column = NULL,
  top_features_to_label = NULL
)

Arguments

x_axis

String. Column holding the effect size (e.g. "log2FC"). Defaults to "log2FC".

y_axis

String. Column holding the raw significance values (e.g. "FDR", "fdr", "q_value"). The function applies -log10() internally. Defaults to "FDR".

colour

String or NULL. Column to colour points by (continuous gradient). If NULL, points are coloured by x_axis. Defaults to NULL.

label_column

String or NULL. Column holding feature labels. Required if top_features_to_label is set. Defaults to NULL.

top_features_to_label

Integer or NULL. Number of features to label, ranked by y_axis ascending (most significant first). Defaults to NULL.

Value

A named list with the following elements:

  • x_axis - String. Column holding the effect size (e.g. "log2FC"). Defaults to "log2FC".

  • y_axis - String. Column holding the raw significance values (e.g. "FDR", "fdr", "q_value"). The function applies -log10() internally. Defaults to "FDR".

  • colour - String or NULL. Column to colour points by (continuous gradient). If NULL, points are coloured by x_axis. Defaults to NULL.

  • label_column - String or NULL. Column holding feature labels. Required if top_features_to_label is set. Defaults to NULL.

  • top_features_to_label - Integer or NULL. Number of features to label, ranked by y_axis ascending (most significant first). Defaults to NULL.


Binary heatmap, e.g. SCENIC regulon on/off calls

Description

Draws a samples x features on/off matrix in the style of the SCENIC paper: features as rows, samples as columns, black for on and white for off. Every block of sample group x feature group is drawn as one raster, so the plot stays light no matter how many samples there are, and the blocks are separated by white gaps. Groups get a thin colour strip with their labels written next to it. Sample and feature groups share one colour mapping, so a feature group with the same name as a sample group gets the same colour. group_annotation adds a second strip with a legend between the matrix and the sample group strip, e.g. the response group of each cell line.

Filtering, ordering and binning happen in bixverse::extract_binary_heatmap_data(). If the samples were binned the cells show the fraction of samples on as a grey ramp.

PDF viewers tend to smooth embedded rasters. If the blocks look blurry in a PDF, save as PNG instead.

Usage

plot_binary_heatmap(
  x,
  sample_groups = NULL,
  feature_groups = NULL,
  heatmap_params = bixverse::params_binary_heatmap(),
  show_feature_labels = NULL,
  group_gap = 0.001,
  group_annotation = NULL,
  annotation_colours = NULL,
  palette = c("main", "sequential", "diverging", "viridis", "spectral"),
  .verbose = FALSE
)

Arguments

x

Either a BinaryHeatmapData from bixverse::extract_binary_heatmap_data() or a logical matrix of samples x features, which then gets passed through it.

sample_groups

Optional named character vector or factor mapping samples to groups. Only used if x is a matrix.

feature_groups

Optional named character vector or factor mapping features to groups. Only used if x is a matrix.

heatmap_params

List. Output of bixverse::params_binary_heatmap(). Only used if x is a matrix.

show_feature_labels

Optional boolean. Shall the feature names be shown. NULL (default) shows them for up to 80 features.

group_gap

Numeric between ⁠[0, 0.1]⁠. Width of each gap between groups as fraction of the axis length. Applied per boundary, so with many groups keep it small. 0 removes the gaps.

group_annotation

Optional named character vector or factor mapping every sample group to a coarser label. Factor levels set the legend order. Ignored if there is only one sample group.

annotation_colours

Optional named character vector of colours for the group_annotation labels. NULL (default) uses viridis.

palette

String. Discrete palette for the group strips, see bx_colors().

.verbose

Boolean. Controls verbosity of the extraction.

Value

A ggplot object.

References

Aibar, et al., Nat Methods, 2017


Plot observed enrichment scores against the blitzGSEA null

Description

For each pathway of interest, draws the fitted null density at that pathway's size and drops the observed enrichment score on top, with the tail beyond it shaded. This is where the p-value comes from: blitzGSEA never permutes per pathway, it reads the score off the gamma tail interpolated to the set size.

The raw permutation scores never cross the Rust boundary, so this is the fitted density, not a histogram of null draws.

Usage

plot_blitzgsea_es_null(
  null_model,
  res,
  pathways_of_interest,
  n_points = 512L,
  text_size = 3
)

Arguments

null_model

BlitzGseaNull object from bixverse::blitzgsea_calibrate(). Has to be the null the results were scored against.

res

data.table. Output of bixverse::calc_blitzgsea(). Needs the columns c("pathway_name", "es", "size", "pvals", "fdr").

pathways_of_interest

String vector. Names of the pathways to plot. These need to be represented in res$pathway_name.

n_points

Integer. Resolution of the density curve. Defaults to 512L.

text_size

Numeric. Size of the annotation text. Defaults to 3.

Value

A named list of ggplot objects, one per element of pathways_of_interest.

References

Lachmann, et al., Bioinformatics, 2022


Plot the blitzGSEA calibration

Description

Diagnostic for a BlitzGseaNull. Shows the smoothed gamma parameters against anchor set size for both tails, plus the fraction of positive null scores. A fit that sags at one end of the size range is obvious here and invisible in the results table.

The KS goodness-of-fit p-values are in the subtitle. Low values mean the gamma tails do not describe the permutation scores well and the p-values are optimistic. More permutations is the usual fix.

Usage

plot_blitzgsea_null(null_model, line_size = 0.8, point_size = 1.2)

Arguments

null_model

BlitzGseaNull object from bixverse::blitzgsea_calibrate().

line_size

Numeric. Line width. Defaults to 0.8.

point_size

Numeric. Point size for the anchor knots. Defaults to 1.2.

Value

A ggplot object, facetted over the parameter type.

References

Lachmann, et al., Bioinformatics, 2022


igraph enrichment map to ggraph plot

Description

Takes in the output from enrichment_map_oae() or enrichment_map_gsea() and generates a ggraph object for subsequent saving, etc.

Usage

plot_enrichment_map_ggraph(
  g,
  label_nodes = "adaptive",
  labels_to_include = NULL,
  adaptive_thresholds = c(`15` = 3, `5` = 2, `2` = 1, `1` = 0),
  font_size = 4,
  ...
)

Arguments

g

igraph. Output from enrichment_map functions.

label_nodes

String. Controls which nodes to label. Options:

  • "all": Label all nodes

  • "adaptive": Adaptive labelling based on community size (default)

  • NULL: No labels

  • Integer: Label top N nodes by size

labels_to_include

Optional string. These are labels you want to include no matter what.

adaptive_thresholds

Named numeric. The names indicate the community size and the values how many pathways per community to show. An example would be c("15" = 3, "5" = 2, "2" = 1, "1" = 0), which is also the default.

font_size

Numeric. Font size of the labels on top of the enrichment map.

...

Other parameters you wish to forward to ggraph::geom_node_text().

Value

A ggplot2 object with the enrichment map


igraph enrichment map to VisNetwork interactive network

Description

Takes in the output from enrichment_map_oae() or enrichment_map_gsea() and generates an interactive VisNetwork widget.

Usage

plot_enrichment_map_visnetwork(g)

Arguments

g

igraph. Output from enrichment_map functions.

Value

The interactive visnetwork


Generate GSE dotplots

Description

This function can take in the output of bixverse::gse_hypergeometric() or bixverse::gse_hypergeometric_list() and generates in the former case a single plot and in the latter case a list of plots per target set.

Usage

plot_gse_dotplot(
  res,
  size_range = c(2, 5),
  viridis_option = "D",
  direction = -1,
  max_terms = NULL,
  .verbose = TRUE,
  ...
)

Arguments

res

data.table with the enrichment results. Needs to have the columns c("hits", "target_set_lengths", "gene_set_name", "gene_set_lengths", "fdr").

size_range

Numerical vector of size 2. Defines the size range for the dots in the plot.

viridis_option

String. The option to forward to ggplot2::scale_fill_viridis_c().

direction

1 or -1. The direction in the colour palette.

max_terms

Optional integer. Show only the this many most significant gene sets. Applied per target set when several were tested. Defaults to NULL, i.e. everything that passed the enrichment threshold.

.verbose

Boolean. Controls verbosity of the function.

...

Further parameters to forward to wrap_and_truncate(), which shortens the gene set labels.

Value

If the output of bixverse::gse_hypergeometric_list() was provided, a list of dotplots per target gene set. Otherwise, a single GSE OAE dot plot.


Plot GSEA enrichment results

Description

Helper function to create the classical GSEA plots for a set of pathways of interest. You can also provide the underlying GSEA results to add the FDR and NES information to the plot.

Usage

plot_gsea_enrichment(
  stats,
  pathways,
  pathways_of_interest,
  gsea_results = NULL,
  gsea_param = 1,
  tick_size = 0.2,
  text_size = 5
)

Arguments

stats

Named numeric vector. The gene level statistic.

pathways

List. A named list with each element containing the genes for this pathway.

pathways_of_interest

String vector. Names of the pathways to plot. These strings need to be represented in the names of pathways.

gsea_results

Optional data.table with the bixverse GSEA results. If provided, the FDR and NES for the given pathway of interest will be also added to the plot.

gsea_param

Numeric. Defaults to 1.

tick_size

Numeric. The tick size. Defaults to 0.2.

text_size

Numeric. The text size. Defaults to 5. Only relevant when gsea_results is provided.

Value

A named list of ggplot objects, one per element of pathways_of_interest that survived the size filters.


Generate adjusted scores for plotting mitch results

Description

Function that takes results from bixverse::calc_mitch(), extracts the individual scores and p-values for each contrast, runs an FDR correction on top of the p-values and sets scores above the provided FDR threshold to 0.

Usage

prepare_mitch_scores(res, fdr_threshold = 0.05)

Arguments

res

data.table. Output of bixverse::calc_mitch().

fdr_threshold

Numeric. The FDR threshold you want to apply.

Value

A list with the following two elements

  • fdr_corrections - FDR-corrected scores as a matrix of the individual contrast p-values.

  • adj_scores - The extract scores per contrast with scores above the individual FDR threshold set to 0.


General helper to save all types of plots to file

Description

General helper to save all types of plots to file

Usage

save_plot(plot, file_name = NULL, path, plot_params = params_plots())

Arguments

plot

The plot you want to save to disk.

file_name

Optional String. If not provided, the plot will be named after the R variable.

path

Directory. Where to save the plot to.

plot_params

List. Output of params_plots(). A list with the following elements:

  • width - Width of the plot.

  • height - Height of the plot.

  • file_type - Which file type.

  • unit - Which unit do width and height describe.

  • res - Resolution for PNG plots

Value

Saves the plot to disk and returns invisible.


Save a list of plots

Description

Save a list of plots

Usage

save_plot_ls(plot_ls, path, plot_params = params_plots())

Arguments

plot_ls

Named list of plots. The names will serve as file names (the extension will be added by the function)

path

Directory. Where to save the plot to.

plot_params

List. Output of params_plots(). A list with the following elements:

  • width - Width of the plot.

  • height - Height of the plot.

  • file_type - Which file type.

  • unit - Which unit do width and height describe.

  • res - Resolution for PNG plots

Value

Saves the plots to disk and returns invisible.


Bixverse Color Scale (Discrete)

Description

Bixverse Color Scale (Discrete)

Usage

scale_color_bx(palette = "main", reverse = FALSE, ...)

Arguments

palette

Palette name (default: "main")

reverse

Reverse colors? (default: FALSE)

...

Additional arguments passed to scale_color_manual

Value

A ggplot2 scale object


Bixverse Color Scale (Continuous)

Description

Bixverse Color Scale (Continuous)

Usage

scale_color_bx_c(palette = "sequential", reverse = FALSE, n = 20, ...)

Arguments

palette

Palette name (default: "sequential")

reverse

Reverse colors? (default: FALSE)

n

Integer. Number of colours to interpolate over (default: 20), see bx_colors().

...

Additional arguments passed to scale_color_gradientn

Value

A ggplot2 scale object


Bixverse Fill Scale (Discrete)

Description

Bixverse Fill Scale (Discrete)

Usage

scale_fill_bx(palette = "main", reverse = FALSE, ...)

Arguments

palette

Palette name (default: "main")

reverse

Reverse colors? (default: FALSE)

...

Additional arguments passed to scale_fill_manual

Value

A ggplot2 scale object


Bixverse Fill Scale (Continuous)

Description

Bixverse Fill Scale (Continuous)

Usage

scale_fill_bx_c(palette = "sequential", reverse = FALSE, n = 20, ...)

Arguments

palette

Palette name (default: "sequential")

reverse

Reverse colors? (default: FALSE)

n

Integer. Number of colours to interpolate over (default: 20), see bx_colors().

...

Additional arguments passed to scale_fill_gradientn

Value

A ggplot2 scale object


Stacked violin plot of gene expression across groups

Description

Stacked violin plot of gene expression across groups

Usage

stacked_violin_plot_sc(
  object,
  features,
  grouping_variable,
  feature_labels = NULL,
  scale = FALSE,
  clip = NULL,
  modality = c("rna", "adt"),
  palette = BX_PALETTES
)

Arguments

object

A single cell class.

features

Character vector. Gene IDs to plot, one row each.

grouping_variable

String. Obs column to group by.

feature_labels

Optional named character vector mapping gene ids to display labels (default: NULL).

scale

Boolean. Whether to z-score the expression values.

clip

Optional numeric. Clip z-scores if scale = TRUE.

modality

String. One of c("rna", "adt").

palette

String. Discrete palette for the group fills. One of c("main", "sequential", "diverging", "viridis", "spectral"), see bx_colors().

Value

A ggplot object.


Bixverse ggplot2 Theme

Description

A custom theme for the bixverse ecosystem based on the ggplot2::theme_minimal()

Usage

theme_bx(
  base_size = 12,
  base_family = "Helvetica",
  base_line_size = 0.5,
  base_rect_size = 0.5
)

Arguments

base_size

Base font size (default: 12)

base_family

Base font family (default: "Helvetica")

base_line_size

Base line size (default: 0.5)

base_rect_size

Base rectangle size (default: 0.5)

Value

A ggplot2 theme object

Examples

## Not run: 
library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  theme_bx()

## End(Not run)

Per-metric violin plots from a CellQc object

Description

Per-metric violin plots from a CellQc object

Usage

## S3 method for class 'CellQc'
violin_plot_sc(
  x,
  log_scale = FALSE,
  show_outlier = TRUE,
  raster = NULL,
  palette = BX_PALETTES,
  ...
)

Arguments

x

A CellQc object.

log_scale

Logical. Apply a log10 y-axis (default: FALSE).

show_outlier

Logical. Overlay outlier points (default: TRUE).

raster

Optional boolean. Shall the plot be rasterised. If NULL and number of cells is larger than 1e5, defaults to TRUE.

palette

String. Discrete palette for the group colours. One of c("main", "sequential", "diverging", "viridis", "spectral"), see bx_colors(). Ignored when show_outlier = TRUE.

...

Ignored.

Value

A named list of ggplot objects, one per metric.


Violin plot from a data.table

Description

Per-cell outliers are recomputed within each grouping_column group.

Usage

## S3 method for class 'data.table'
violin_plot_sc(
  x,
  grouping_column,
  variable,
  direction = c("twosided", "below", "above"),
  threshold = 3,
  group_name = NULL,
  var_name = NULL,
  log_scale = TRUE,
  show_outlier = TRUE,
  raster = NULL,
  palette = BX_PALETTES,
  ...
)

Arguments

x

data.table. Input data containing the QC metric.

grouping_column

Character. Column used for the x-axis groups.

variable

Character. Numeric column to plot on the y-axis.

direction

Character. One of "twosided", "below", "above".

threshold

Numeric. Number of MADs for outlier detection (default: 3).

group_name

Character. x-axis label (default: NULL).

var_name

Character. y-axis label (default: NULL).

log_scale

Logical. Apply a log10 y-axis (default: TRUE).

show_outlier

Logical. Overlay outlier points (default: TRUE).

raster

Optional boolean. Shall the plot be rasterised. If NULL and number of cells is larger than 1e5, defaults to TRUE.

palette

String. Discrete palette for the group colours. One of c("main", "sequential", "diverging", "viridis", "spectral"), see bx_colors(). Ignored when show_outlier = TRUE.

...

Ignored.

Value

A ggplot object.


Create a volcano plot

Description

Helper function to generate volcano plots for differental gene/transcript/protein expression analysis. The function applies under the hood a -log10(stat) transformation to the respective statistic you want to display on the y axis. If you provide labels, the top features to label will be chosen by ranking the -log10(stat).

Usage

volcano_plot(
  dt,
  volcano_plot_params = params_volcano(),
  x_lab = NULL,
  y_lab = NULL,
  plot_title = NULL,
  plot_sub_title = NULL
)

Arguments

dt

A data.table/data.frame holding the differential expression results.

volcano_plot_params

A list as returned by params_volcano().

x_lab

Optional string. Overwrite of the x label of the plot. If not provided, will default to volcano_plot_params$x_axis.

y_lab

Optional string. Overwrite of the x label of the plot. If not provided, will default to -log10(volcano_plot_params$y_axis).

plot_title

Optional string. If provided, the plot will get a title.

plot_sub_title

Optional string. If provided, adds this as a sub title to the plot.

Value

A ggplot object.


Helper function to wrap and truncate text

Description

Helper function to wrap and truncate text

Usage

wrap_and_truncate(text, width = 40L, max_lines = 2L, whitespace_only = TRUE)

Arguments

text

String. The string to truncate.

width

Integer. Maximum width of a given line.

max_lines

Integer. Maximum lines before truncating.

whitespace_only

Boolean. Shall the string wrapping happen only around whitespaces.

Value

The string wrapped and/or truncated.