Plotting API reference#

cytearc.plotting is CyteArc’s plotting API. Import it as splt and call functions such as splt.embedding(...), splt.dotplot(...), and splt.cluster_tree(...). For functions whose first argument is a datastore, ds.plots.embedding(...) and related accessor methods provide the same behavior with that argument already bound. Store-backed graph plotters mirror their DataStore counterparts and require an exact graph= reference. dotplot and matrixplot take features= as gene names or FeatureRef values, or as a mapping of group names to such lists. Their color bar names the means it draws: “Mean expression” for the RNA assay and otherwise the assay, such as “Mean of GeneScores”, and so does the color bar of a stacked violin that distribution(kind="stacked_violin", color_by="mean") colors by its group means. Diagnostics remain standalone: qc takes a DataFrame, elbow and highly_variable_features take arrays, and graph_qc takes a sparse graph.

A completed PipelineRun can be passed to ds.plots.embedding(run=run, layout="umap", color_by="clusters"). The run supplies the layout (layout names a run output, "umap" by default) and the cells, and every cell input comes from the run. There is no live fallback in run mode:

  • color_by takes one item or a list, drawn as one panel each. A string or CellField names a frozen run cell field from run.cells.columns, such as clusters, doublet_score, a multimodal run’s weight_<assay> modality weights, or a column frozen with snapshot_columns. An ArtifactRef must be an output of the run, such as one of its Leiden candidates in run["leiden"], which ds.artifacts.find("clusters", graph=run["connectivity_map"], method="leiden", resolution=1.0) also finds. Any other ref raises ValueError; color by it with the granular layout=run["umap"] route instead.

  • facet_by, as a string or CellField, subset_by, Highlight(by=...) and DensityOverlay(group_by=...) name frozen run cell fields. A name that is neither a frozen field nor, for color_by, a gene raises KeyError listing the run’s cell fields.

  • A gene name or FeatureRef reads the live counts of the run’s assay, run.assay, over the run’s cells and normalizes them with the assay’s live normalizer. A multimodal run’s assay is its first source run’s assay. A run freezes no gene values, so a gene color requires an explicit normalization=NormalizationSpec(...), which provenance records; without one it raises ValueError.

  • cell_key other than "I", a from_assay other than the run’s assay, and point_sizes raise ValueError. For per-cell sizes, pass layout=run["umap"] with point_sizes as a pandas Series indexed by cell ID.

Run plots record the run as provenance.extras["run"], a mapping with runId and label. layout_key= remains the live-metadata source. Mixed source modes are rejected. For large continuous fields, ds.plots.embedding_raster(run=run, layout="umap", color_by="doublet_score") uses the same frozen run selection blockwise; its color_by (a string or CellField) and subset_by name frozen run cell fields.

Granular workflows pass exact refs to the same datastore-owned plotting surface:

Plot

Explicit artifact inputs

embedding

layout=embedding_ref, optionally color_by=cluster_ref

dot or matrix plot

groups=cluster_ref

composition

categories=cluster_ref

distribution

grouping=cluster_ref

cluster connectivity

graph=graph_ref, groups=cluster_ref, layout=embedding_ref

modality weights

graph=wnn_graph_ref, layout=embedding_ref

Paris hierarchy

graph=graph_ref, clusters=paris_ref

marker heatmap

marker=marker_ref

pseudotime heatmap

aggregation=aggregation_ref

lineage heatmap and trends

aggregation=lineage_aggregation_ref

lineage curves

curves=curves_ref, layout=embedding_ref

lineage tree

tree=tree_ref, layout=embedding_ref

mapping score

mapping_score(result_ref, reference=reference, layout=embedding_ref)

label-transfer evidence, confusion, and calibration

mapping_evidence(transfer_ref), mapping_confusion(transfer_ref, known_labels=...), mapping_calibration(transfer_ref, known_labels=...)

guide calls of a CRISPR screen

guide_calls(calls_ref)

fitted guide thresholds of a CRISPR screen

guide_thresholds(calls_ref), or guide_thresholds(calls_ref, guides=[...]) for one panel per guide and sample

perturbation efficiency of a CRISPR screen

efficiency(efficiency_ref)

E-distance of each perturbation from the control cells

edistance(edistance_ref)

Mixscape’s knocked-out and escaping cells of each target

mixscape(classes_ref), or mixscape(classes_ref, panel="scores") for each target’s scores and fitted distributions

fold change and p-value of each tested pair of a target and a gene

association_volcano(tests_ref), or association_volcano(tests_ref, targets=[...]) for the pairs of some targets

calibration of the association tests on negative controls, and their power on positive controls

association_calibration(tests_ref)

clusters of perturbations by their profiles

perturbation_clusters(clusters_ref) for the heatmap of their correlations in leaf order, or perturbation_clusters(clusters_ref, panel="embedding", label=[...]) for their layout with chosen perturbations named

clones per clone size and the largest clones, of clones or clonotypes

clone_abundance(clones_ref), or clone_abundance(clones_ref, group_by="sample") for one line per group, and per receptor type for clonotypes

expansion categories and the clonal space of each group of cells

clonal_expansion(expansion_ref), or clonal_expansion(expansion_ref, group_by="cell_type") to regroup the cells

rarefaction and extrapolation curves of the Hill numbers of each group

clonal_rarefaction(ds.clones.rarefaction(clones_ref, group_by="sample")), or base="coverage" against the sample coverage

diversity indices of each group, one panel of bars per index

clonal_diversity(ds.clones.diversity(clones_ref, group_by="sample")), or indices=["chao1", "gini"] for other indices

clones shared between samples or cell types

clone_overlap(ds.clones.overlap(clones_ref, group_by="cell_type")), or index="jaccard" for another index

chosen clones across time points or cell types

clone_tracking(ds.clones.track(clones_ref, group_by="time_point"), order=[...])

fate coupling of every pair of groups with the tree of their order

clone_coupling(ds.clones.coupling(clones_ref, group_by="cell_type")), or value="z_score" for the z-scores against shuffled labels

each clone’s late cells by fate, by dominant fate

clone_fate_bias(bias_ref), or normalize=True for shares

barcodes per cell, UMIs per barcode and reads per molecule of imported lineage barcodes

barcode_calls(barcodes_ref), or barcode_calls(barcodes_ref, max_barcodes_per_cell=5) to gather cells of five barcodes or more in the last bar

the fraction of cells that each site of a lineage recorder reads as marked, unknown, unedited or missing

recorder_states(alleles_ref), or recorder_states(alleles_ref, max_sites=20) to draw the 20 sites read in the most cells

a cell phylogeny with the clones cut from it, its clades collapsed to at most 100 wedges

phylogeny(clones_ref) of clones from ds.clones.phylogeny_clones, or phylogeny(clones_ref, max_leaves=1_000, tree="E7.5-R1-C1") for more wedges of one tree

receptor types, chain pairings and chains per cell of imported immune receptors

receptor_qc(receptors_ref), or receptor_qc(receptors_ref, group_by="sample") for one bar per group

V, D, J or constant gene usage of each locus

gene_usage(ds.repertoire.gene_usage(receptors_ref, group_by="sample")), or the usage of genes="j_call" or level="family"

V-J gene pairing of each locus

gene_pairing(ds.repertoire.gene_usage(receptors_ref, genes=("v_call", "j_call"), cell_selection=t_cells))

junction lengths of each locus

spectratype(ds.repertoire.spectratype(receptors_ref, group_by="sample")), or the lengths of sequence="nt"

depth of variant counts at each site and in each cell

variant_depth(counts_ref), or variant_depth(counts_ref, group_by="sample") for one histogram per group

each variant’s variance-mean ratio against its strand correlation, informative variants marked

variant_statistics(selection_ref)

each cell’s allele frequency of each informative variant, uncovered entries apart

allele_frequencies(selection_ref), or allele_frequencies(selection_ref, clones=clones_ref) for cells ordered by clone

the fraction of cells with each genotype call at each site, by group, and the calls of one site on an embedding

genotypes(genotypes_ref, group_by="cell_type"), or genotypes(genotypes_ref, sites=["CALR"], layout=embedding_ref) to color the cells of an embedding of the genotypes’ cells by their call at CALR

An embedding colored by an artifact, embedding(layout=embedding_ref, color_by=labels_ref), reads the artifact’s values for the layout’s cells, so the artifact can hold more cells than the layout: labels computed on every cell color a run’s layout of fewer cells, and keep the colors that a layout of all their cells gives them. An artifact that holds no value for some cells of the layout raises ValueError; compute it on cells that include the layout’s, such as the run’s analysis_cell_selection.

Labels beside another artifact are read the same way: composition(categories=cluster_ref, grouping=sample_labels_ref) reads the grouping for the cells of categories, and cluster_connectivity reads groups for the graph’s cells, so labels of more cells serve, and labels that miss some of those cells raise ValueError that names the cells to compute them on. A layout must hold the cells that it draws: those of the graph in cluster_connectivity and modality_weights, of the trajectory in lineage_curves and lineage_tree, and of the genotypes in genotypes. Any cell selection of those cells serves, whichever operation made it, such as one that select_cells makes of a run’s cells; a layout of other cells raises ValueError.

ds.clusters.connectivity(graph, groups) returns the weights that cluster_connectivity draws as nodes and edges tables, without a layout, a figure or the plotting dependencies (DataStore API reference). ds.trajectory.curves_in_layout(curves, layout) returns the points that lineage_curves draws, the same way.

A figure of a clone or repertoire summary takes the record that the summary returns, such as the CloneOverlap of ds.clones.overlap, so the summary is computed once, can be read before it is drawn, and sets the figure’s groups and cells; from the store it reads only what it calls the clones and the labels that its groups’ colors range over. A figure of a saved result takes its artifact. Figures that split cells by group take group_by, one cell metadata column or several, and groups, a label artifact or a NamedCellArtifact, alone or together, and group the cells as the clone summaries do: by the combinations of their labels, named by the labels joined by commas. A figure of a summary takes groups=NamedCellArtifact(name, artifact) of the artifact that the summary grouped by, to name it. A limit on what a figure draws is named for the items it limits, such as max_clones, max_genes and max_barcodes_per_cell.

The figures of clones, clone_abundance, clonal_expansion, clonal_rarefaction, clonal_diversity, clone_overlap, clone_tracking, clone_coupling and clone_fate_bias, those of immune receptors and lineage records, receptor_qc, gene_usage, gene_pairing, spectratype, barcode_calls, recorder_states and phylogeny, and those of variants, variant_depth, variant_statistics, allele_frequencies and genotypes, keep one set of conventions:

  • Names. Titles, axes and legends name the clones as their artifact does, clones, clonotypes or clonotype clusters, such as “Clonotype sizes” and “Clonotypes across groups”. Clonotypes are labeled by their representative’s junction, with their number where two drawn share one, and tables that list clones hold clone, the ID, beside label, the text drawn.

  • Group colors. A grouping by one cell metadata column takes the column’s stored display palette, or colors assigned over every label of the column, in their stored order for a column stored as ordered, so a figure of some cells colors each group as a figure of all of them does. A label artifact’s groups take the categories and colors that the artifact records, as imported clusters keep them, or else colors over every label of the artifact, receptor types one palette of their own, and groups of several columns colors over the groups drawn. Only a figure that colors its groups reads those labels: a column’s a stored chunk at a time, and a label artifact’s within the store’s memory budget.

  • Group order. Groups follow the labels of their first column, then of their second, each column’s labels in the order that the column or label artifact stores, as a stored display or ordered categories, and then in natural order; receptor types follow their vocabulary, TCR, BCR, ambiguous, multichain and no IR. Every axis and legend that names the groups lists them so, and the tables that a figure builds, such as the matrix of clone_overlap; a summary’s own tables keep the summary’s order, and clone_coupling places its groups by its dendrogram.

  • Vocabularies. Receptor types, chain pairings, the VJ and VDJ arms of a receptor, loci, the states of a recorder site and genotype calls each take one palette, in every figure that draws them. No value, such as "no IR", a site without a read, a genotype call of no evidence or an allele frequency of a cell not covered, takes the scales’ missing gray, and what carries nothing, such as an unedited site, a filtered call or a variant that is not informative, a muted gray. Legends name values in words, such as “Unknown mark” or “Wild type”, and tables keep their tokens, such as unknown_mark or wild_type. The libraries of lineage barcodes take colors over every library of their artifact.

  • Heatmaps. clone_overlap and clone_coupling take color_scale, a ColorScale that sets the color map and limits, so two figures can share them. By default overlap indices and couplings of at least 0 take viridis over the values drawn, and z-scores and couplings below 0 take RdBu_r centered on 0. The diagonal is blank, and a pair that was not compared, or whose z-score is not finite, takes the scale’s missing color. The locus panels of gene_usage and gene_pairing share one color bar, from 0 to the largest fraction of any locus, so a color means one fraction in every panel, and allele_frequencies colors frequencies from 0 to 1.

  • Legends. Each legend is titled and stands beside its panel, a grouping’s legend titled by its columns joined by commas, where a label artifact takes its name or the title of its record; panels that share colors, such as a rarefaction’s orders or a spectratype’s loci, share one legend beside their first row, the calls of genotypes one legend beside its last panel, and a figure without a grouping, whose cells form the one group “all cells”, draws none of its groups. The axis that names the groups takes the same title in both panels of clonal_expansion, below the matrix of clone_overlap and clone_coupling, in clone_tracking, in the group axes of gene_usage, in the lower grouped panel of receptor_qc, and beside the bars of genotypes, which are named by site and group and titled as “Site” followed by the grouping; clonal_diversity names its groups on the axis of its bars and titles them in its legend alone. The receptor types that clonotypes keep apart take the title “Receptor type”. A legend lists at most 80 entries, in up to four columns that fit the row of its panel, and says how many of how many it lists when it leaves some out, such as “Clone (80 of 120)”. Every legend is reported in PlotResult.legends with its scale in PlotResult.scales, with show_legend=False too, so compose_results draws a legend that several figures share once.

  • Bars and axes. A stacked bar draws its first part at the left, or at the top of a vertical bar, in its legend’s order, and fractions span the axis from 0 to 1; parts that make no whole, such as the chains of a receptor’s two arms, stand side by side. A part of a whole is a fraction, such as “Fraction of the site’s cells”. An axis of bars or of a heatmap names as many of its items as its length holds once the figure is laid out, at most 40: every one, or else every second, third or nth from the first, so that names never run into each other. A heatmap prints its values when it has at most 12 rows and columns, and the tables hold every item. A log axis reads plain numbers: whole numbers on an axis of counts, and numbers such as 0.5 on one of mean depths or variance-mean ratios. A panel that leaves items out says so in its title or on its axis, such as “The 40 of 312 clones with the most late cells”, “V gene (30 of 52)” or “Cells (2,000 of 5,000)”, or “Largest 20 clonotypes” for the largest clones.

  • Sizes. A figure is at most a page wide, 7.5 inches. A panel that grows with its items grows for each item it names, small multiples such as the orders of a rarefaction or the loci of gene usage fill rows of three, heatmaps of loci rows of two, and a row too wide for the page shrinks its panels to share it.

  • Nothing to draw. A figure without anything to draw raises ValueError, and a panel beside others that draw, such as one of clonal_diversity whose index is defined for no group, one of barcode_calls that no library fills or the cells panel of variant_depth whose grouped cells have no depth, says so.

  • Provenance. notes holds the plot’s name, and extras holds the reference of each artifact drawn: clones in the figures of clones, any other artifact that the figure takes under its argument’s name, such as expansion, bias, receptors, barcodes, alleles, counts, variants or genotypes, and source, the receptors or clonotypes that gene usage and junction lengths count. It holds the settings under their names, and the grouping of a figure that groups cells, its columns’ titles joined by commas.

layout_key and string forms on plotters that still accept them refer to deliberate live metadata inputs. Distribution grouping instead requires either an exact categorical artifact, named or not, or an explicit CellField, with cell_selection= when a frozen metadata subset is intended.

CellField(key, label=...) names a live column wherever a plot takes one: embedding(color_by=...), distribution(grouping=..., split_by=..., sample_by=...), composition(category_by=..., sample_by=..., subject_by=..., pair_by=..., condition_by=...), dotplot and matrixplot(group_by=..., sample_by=...), where a tuple group_by takes one for each column, cluster_connectivity(group_by=...) and embedding(facet_by=...). Where the plot draws the column’s axis or legend, the label titles it in place of the column’s name; it titles the legend of a composition’s conditions in place of “Condition”, and names the column in each facet’s title, such as Stage=early; dotplot and matrixplot join the titles of two columns with “ / “. The grouping arguments of composition, dotplot, matrixplot, cluster_connectivity, distribution(split_by=..., sample_by=...) and embedding(facet_by=...) read the column by its key, which provenance records, so a label changes no table, and refuse any other value with TypeError and a CellField of kind="continuous" with ValueError, each naming the argument, before the plot reads the store. A plot recipe names a live column as {"key": "cell_type", "label": "Cell type"} in groupBy, or a column of its list, categoryBy, sampleBy, subjectBy, pairBy, conditionBy, splitBy or facetBy.

NamedCellArtifact(name, artifact) titles a label artifact wherever a plot takes one: embedding(color_by=...), distribution(grouping=...), composition(categories=..., grouping=...), dotplot and matrixplot(groups=...), cluster_connectivity(groups=...), and the groups of the figures and summaries of clones, receptors and variants. The name titles the artifact’s panel, axis and legend, and keys an embedding’s panel. It never enters a summary, its grouping or an artifact’s identity, so a summary of a named artifact is the summary of the bare artifact, and naming the artifact another way reuses it. Without a name, a plot titles an artifact from its record: the obs key of an H5AD cluster_keys import, the column that a snapshot or a label transfer copied, the method and resolution of a Leiden clustering, such as “Leiden, resolution 1.0”, or else its kind in words, such as “Cluster labels”. Two distinct artifacts that their records title alike take the start of their IDs after the title, such as “Leiden, resolution 1.0 (3f9a2c)”. A plot recipe names an artifact as {"name": "Cell type", "artifact": "cellTypes"} in grouping, categories, groups or colorBy, where artifact is the key of the artifact that run_recipe(artifacts=...) supplies.

Dot plots and matrix plots name the grouping columns of their tables by role, whatever the grouping columns are called: group holds the first group_by key’s values or the groups= labels, subgroup the second key’s values, and sample the sample_by value. They are followed by feature, feature_group, mean, fraction, n_cells and variance, and an aggregate over samples adds n_samples. A grouping column can therefore be named feature, mean or sample, and provenance.extras["group_by"] keeps the source column names. With standardize="feature", mean stays raw and a zscore column of tables["aggregate"] holds the plotted values, while tables["per_sample"] keeps the per-sample means without it; provenance.extras["color_values"] names the plotted column. A matrix plot’s tables["matrix"] is the drawn matrix, like the matrix of marker_heatmap: one row per feature (index feature) and one column per group label (columns group). marker_heatmap’s matrix holds the standardized values of its marker features, one column per group of the marker search. The annotation tables of both are indexed by the same labels.

Default category colors are assigned over every value of the colored column or label artifact, not only over the plotted cells, so groups, subset_by, or a cell_key subset never recolors a category: Alpha keeps its color in an embedding, a violin, a composition and a cluster tree of any of its subsets. Categories take their natural order, so "2" precedes "10".

A column’s stored display sets the order, colors and labels of its categories instead, such as the categories and uns["<column>_colors"] that an H5AD import keeps. The clusters that cluster_keys imports record a display on their label artifact, which plots read in the same way, a new snapshot_cluster_labels keeps the display and stored order that the column or label artifact it freezes records when it is made, and a run records the display of each column that snapshot_columns freezes, so plots of a snapshot and run plots draw the column as plots of the live column do. A column stored as ordered and without a display, a categorical column whose categories are ordered or a column whose levels attribute comes with ordered=True, keeps its categories in their stored order, and default colors follow that order. Categories that a stored display or order leaves out follow its categories in natural order, each in the default color of its place in that order, as the groups of every plot follow a stored order. A CategoricalScale sets only the fields it names, and the others keep the stored values: labels alone renames categories in their stored order and colors, order alone keeps the stored colors, palette alone keeps the stored order, and palette_name replaces the stored colors in the stored order. Labels replace the stored labels category by category. A palette names every category that the plot shows, and an order lists every one. Requested groups order an embedding’s legend unless the scale sets order. The stored order also orders the groups of dotplot and matrixplot, where the groups of two group_by columns follow the first column’s order and then the second’s, an embedding’s facets, the bars of a composition by sample_by or grouping and its conditions by condition_by, and the groups of marker_heatmap by the clusters that its marker search compared; group_order, the order of a categorical_scale, facet_order and the categories that an embedding’s groups=[...] requests set the order instead, and the labels of a column or artifact that stores no order take their natural order. Tick and legend labels in every plot, including violins, histograms, dot plots, and matrix plots, show the resulting labels. cluster_tree colors its clusters, and the categories of a categorical fill_by_value column, as an embedding colored by them does, unless color_key or cmap sets their colors.

A colormap argument, such as cmap, heatmap_cmap, clusterbar_cmap or lineage_cmap, and the cmap of a ColorScale or DensityOverlay, takes the name of a colormap that matplotlib.colormaps holds, seaborn’s included, or a Colormap that it holds under that name, since plots draw, record and compose a colormap by its name. A Colormap of your own, or one changed from another, such as viridis.with_extremes(bad="gray"), serves once matplotlib.colormaps.register holds it under a name of its own. A plot refuses any other value with an error that names the argument, before it reads the store. qc takes any palette that seaborn reads as cmap, and marker_heatmap also a list of colors. The lineages of lineage_trends and lineage_curves and the gene modules of lineage_heatmap and pseudotime_heatmap take the colorblind palette, Okabe and Ito’s eight colors followed by four more, in order, unless lineage_cmap or clusterbar_cmap gives a colormap to sample at evenly spaced positions; past the palette’s 12 colors they take evenly spaced hues, with a warning.

Embeddings draw categorical colors, and continuous colors they do not sort, in a seeded shuffle, so cells stored last, such as the last sample of a merged store, do not cover the others. Each cell draws at its rank in numpy.random.default_rng(seed).permutation(n) over the n cells of the layout, so the order is reproducible and the same in every panel; seed=None keeps the stored order. Gene and other feature colors draw high values on top by default, as in scanpy; sort_values=False shuffles them too, and sort_values=True also sorts metadata colors. provenance.extras["draw_order"] records each color’s order. On-data labels start at their cluster’s median and, once the layout is final, move apart by at most about one label height without coming closer to another cluster’s median than to their own. Side legends list the categories that fit beside the figure, which grows to hold them when CyteArc sizes it. Embeddings settle their layout and point sizes without rendering the points, so the scatter is drawn only when the figure is shown or saved.

missing_color replaces the missing color of whichever scale an embedding uses, and a log ColorScale draws values that are not positive in that color instead of raising. clip_fraction takes its quantiles from the drawn cells. Cells without a facet_by value get their own facet, titled with the facet column’s missing label, and facets wrap at four columns, each color or layout starting a new row. embedding_raster paints a pixel whose cells all lack a value in the missing color, while empty pixels show the axes background.

Violins scale every body, including each half of a split violin, to the full width, as in scanpy. A violin estimates its density from at most max_density_points values, a seeded sample that keeps its smallest and largest value. Stacked compositions draw the first category on top, in the legend’s order. With swap_axes=True, dot plots list the first group at the top. A clustered matrix plot draws the dendrogram of each clustered axis beside the matrix, and a mapping of feature groups draws one bracketed row per feature and group, indexing tables["matrix"] by feature_group and feature.

Plots treat rows that a nullable metadata column or label artifact flags in its linked missing mask as missing, never as their stored placeholder. Dot plots and matrix plots leave those cells out of every group and report their number as dropped_group_cells. Composition plots count a missing category in the NA category and leave cells with a missing sample label out of every sample. Embeddings and cluster trees show missing colors or fill values as missing, and cluster_connectivity rejects missing group labels and coordinates. An embedding colored by a label artifact also draws a blank label, such as that of a cell without a clone or clonotype, in the missing color rather than as a category. The legends of embeddings, compositions, perturbation_clusters and the annotation strips of matrixplot and marker_heatmap list the values drawn in the missing color last, under the scale’s missing label, such as “NA”. The legends that compose_results draws for them list that entry too, and a legend that several figures share lists it when any of them draws such values.

A feature has no value in a cell that its assay did not measure, which the assay’s membership column <assay>_I marks False (Assay membership); such a cell holds zero counts, which are no measurement. Plots read only the measured cells and normalize only them, so a normalizer fitted over the cells that it reads, such as ATAC TF-IDF, gives a measured cell the value of a read of the measured cells alone. Embeddings draw an unmeasured cell in the scale’s missing_color and leave it out of the color limits, and provenance.extras["color_limits"] holds None for a color or panel without a value among the drawn cells. Distribution plots leave it out of the feature’s panel and table, and a feature panel whose assay measured none of the selected cells raises ValueError that names the membership column. Dot plots and matrix plots compute mean, fraction, and variance over the cells of a group with a value, which n_cells counts, so fraction is the share of measured cells above expression_cutoff; a group without a measured cell keeps its row with n_cells 0 and NaN statistics and draws no dot or a missing matrix cell, and an aggregate over samples skips such a sample in every statistic and in n_samples. Cluster-tree fill values and the group means of marker_heatmap leave out unmeasured cells. Dot plots, matrix plots, embeddings, distribution plots, and marker_heatmap record provenance.extras["unmeasured_cells"], a mapping from each feature assay to the number of plotted cells that it did not measure, when that number is not zero.

On a store merged from sources that measured different features, such as two antibody panels, a feature also has no value in a cell whose source did not measure it, as the assay’s feature columns measured_in_<source> record (Import and export API reference). Each cell’s source is its label in the cell column of sources that the merge or composite writes beside the record, dataset unless source_column names another. Plots read and normalize each feature over the cells whose source measured it, so the CLR of an antibody that one source stained spans that source’s cells, and they draw and summarize the other cells as they do unmeasured cells: in missing_color, out of the distribution, and out of the statistics and n_cells of dot and matrix plots.

WNN is the default for DataStore.integration.modalities. Its integrated graph stores one weight per input assay and cell. Use ds.plots.modality_weights(graph=wnn_graph, layout=embedding) or cytearc.plotting.modality_weights() to show those weights over an explicit embedding of the graph’s cells. Explicit SNN graphs do not contain modality weights.

Store-backed plotters and diagnostics generally return a PlotResult and render by default with show=True. run_recipe returns a PlotRecipeResult and defaults to show=False. Helpers differ: label_panels returns None, theme_context is an iterator, and compose_results returns a PlotResult without a show parameter.

Pass show=False to every call that draws on a figure you will change or add panels to, such as each target= call that fills a panel of your own figure, then show the complete figure once with plt.show(), which Jupyter also calls at the end of each cell. A call with the default show=True shows the figure as it stands when the call returns. In Jupyter, PlotResult.show() displays any figure, one passed with target= or composed with compose_results included, and then closes it in pyplot, as plt.show() does, so that the end of the cell does not show it a second time. Neither plt.show() nor the end of the cell shows a figure that pyplot has closed, so a line or panel drawn on it after the call does not appear, and two panels filled by calls with the default show=True give two images, the first with one panel empty. A closed figure can still be saved or drawn on, and display(fig) or result.show() shows it with everything drawn on it.

cytearc.plotting.allele_frequencies(store, variants, *, clones=None, max_cells=2000, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot each cell’s allele frequency of each informative variant.

variants is a variant_selection artifact from ds.variants.informative; its informative variants are the rows, in their order along the genome, and cells are the columns, colored from 0 to 1. With clones, such as one from ds.variants.frequency_clones, the cells with a clone are drawn ordered by clone, largest first, under a bar of clone colors whose legend names the clones as their artifact does, and clonotypes across receptor types by each cell’s clonotype within its type, as the clone summaries measure them; without it, the cells that the statistics covered are drawn in their order. A cell that was not covered at a variant’s site has no allele frequency and is drawn in the gray of no value, apart from a frequency of 0. At most max_cells cells are drawn, chosen evenly along the order so that each clone keeps its share, and the axis says how many of how many it draws.

Tables: frequencies (ids, variant, frequency, NaN where the cell was not covered) and cells (ids, clone, NA without clones).

Raises:
  • TypeError – If an argument has the wrong type, or the store does not load variant selections, counts or clones.

  • ValueError – If variants is not a variant_selection artifact, the selection has no informative variant, or no cell has a clone.

Return type:

PlotResult

cytearc.plotting.association_calibration(store, tests, *, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot whether the association tests keep their error rate, and find effects.

tests is a perturbation_associations artifact of ds.perturbation.associations, as ds.perturbation.load_associations reads it. Its negative-control pairs test groups of non-targeting guides against the other control cells, or against all other cells in tests at high MOI, so no gene should change, and its positive-control pairs, such as each target with its own gene, should change. Three panels in a row, whose axes take the keys "qq", "fold_changes" and "controls", follow the calibration check of the SCEPTRE book.

"qq" draws -log10 of the negative-control p-values against the quantiles of as many uniform p-values. Calibrated p-values follow the identity line and mostly stay within the shaded band, between the 2.5% and 97.5% quantiles of Beta(i, n - i + 1), which the i-th smallest of n uniform p-values follows. The discovery p-values are drawn in blue over them, against the quantiles of their own number, and rise above the line where perturbations change genes. The axis holds the band and the negative controls, so a discovery p-value above it, like any p-value below 1e-300, is drawn as an upward triangle at the top edge.

"fold_changes" is a histogram of the negative-control log2 fold changes, with a dashed line at their mean, which lies near 0 when the tests are calibrated. "controls" draws -log10 of the positive-control and negative-control p-values as two strips, each point moved sideways at random with a fixed seed so that the points stay apart. Its title counts the negative-control pairs that the tests call significant, the false discoveries, with their grade. Without a tested positive-control pair, the panel says so. A p-value below 1e-300 is drawn at the top edge.

When the tests are one-sided, the labels of the p-value axes name the side tested. A panel rasterizes its points when it draws more than 50,000. The plot raises ValueError when no negative-control pair passed QC. The table "qq" holds the drawn p-values with set, target, feature, p_value and expected, the uniform quantile i / (n + 1); "band" holds the band’s rank, expected, lower and upper p-values, at every rank of at most 1,000 negative-control pairs and at 1,000 ranks spread on the log scale otherwise; "fold_changes" holds the histogram’s bin_start, bin_stop and pairs; and "controls" holds the drawn controls with set, target, feature and p_value.

Return type:

PlotResult

cytearc.plotting.association_volcano(store, tests, *, targets=None, label_top=10, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot how much and how significantly each perturbation changes each gene.

tests is a perturbation_associations artifact of ds.perturbation.associations, as ds.perturbation.load_associations reads it. Each discovery pair of a target and a gene that passed QC gets a point at its log2 fold change, the gene’s counts in the target’s cells against the counts that its null fit predicts for them, fitted on the target’s and the control cells, or on all cells in tests at high MOI, and at -log10 of its p-value. A point is blue when the pair is significant at the false discovery rate of the tests and gray otherwise. A dashed line marks the largest p-value of a significant pair, the cut of the Benjamini-Hochberg procedure, which runs over the pairs of every target. When the tests are one-sided, the label of the p-value axis names the side tested.

A p-value below 1e-300, such as 0 when it underflows, is drawn as an upward triangle at the top edge. A fold change of minus infinity, when the target’s cells hold no counts of the gene, is drawn as a triangle at the left edge. The label_top pairs with the smallest p-values, ties broken by the larger size of z and then by target and gene, are labeled target:feature_name beside their points, with the gene’s name from the record’s feature_name column, and label_top=0 labels none. A label that would overlap a label of a smaller p-value moves to the other side of its point, or above or below it with a thin line to it. The points are rasterized when there are more than 50,000.

targets keeps the pairs of those targets, and the plot raises ValueError naming any target without discovery pairs. The plot also raises ValueError when none of the kept pairs passed QC. The title counts the significant pairs among the drawn pairs, and the pairs left out because they were not tested. The table "volcano" holds the drawn pairs with every column of the record, from the smallest p-value to the largest, ties broken as for the labels, so its first label_top rows are the labeled pairs.

Return type:

PlotResult

cytearc.plotting.barcode_calls(store, barcodes, *, max_barcodes_per_cell=10, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot the barcodes per cell, the UMIs per barcode and the reads per molecule.

barcodes is a lineage_barcodes artifact, such as one from ds.clones.import_barcodes. The three panels show what clone calling filters: the cells by their number of distinct barcodes, cells without a barcode included, with max_barcodes_per_cell or more in the last bar; each library’s pairs of a cell and a barcode by their UMIs; and each library’s molecules by their reads, on log scales, so molecules of 0 reads appear in the table only. Barcodes of one or two UMIs and molecules of one read are mostly errors and ambient molecules. A library that counts no UMIs or no reads is left out of its panel, and a panel that no library fills says so. The libraries take colors over every library of the artifact, under one legend beside the last panel that draws them.

Tables: barcodes_per_cell (n_barcodes, n_cells), umis_per_barcode (library, umis, n_pairs) and reads_per_molecule (library, reads, n_molecules).

Raises:
  • TypeError – If an argument has the wrong type, or the store does not load lineage barcodes.

  • ValueError – If barcodes is not a lineage_barcodes artifact, or holds no cell.

  • KeyError – If the store holds no such artifact.

  • RuntimeError – If an artifact is incomplete, as a call that stopped before it finished leaves it.

  • MemoryError – If reading the artifact does not fit the memory budget.

Return type:

PlotResult

cytearc.plotting.clonal_diversity(store, diversity, *, indices=('n_clones', 'shannon', 'inverse_simpson'), groups=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot diversity indices of groups of cells, one panel of bars per index.

diversity is the result of ds.clones.diversity, which sets the groups. indices names one or several columns of its indices table, by default ("n_clones", "shannon", "inverse_simpson"): the clones, Shannon entropy and the inverse Simpson index, which are the observed Hill numbers of orders 0, 1, as its logarithm, and 2. Each panel draws one bar per group, in the groups’ colors, and the panels fill rows of three, with one legend of the groups beside the first row; the groups stand in one order in every panel, so a panel directly right of another leaves their names to it, also on caller axes. A group whose index is not defined, such as Pielou’s evenness of a group of one clone, draws no bar, and a panel of none says so; a figure of none is refused. An observed index grows with the cells of a group, so compare groups of different sizes by the Hill numbers at a common coverage or size, which the record’s hill table holds.

groups, a NamedCellArtifact of the label artifact that the record groups by, titles the artifact by its name; without it, the figure takes the title of the artifact’s record.

Tables: indices, the record’s indices; the record’s group_keys holds each group’s labels.

Raises:
  • TypeError – If diversity is not a ClonalDiversity record, another argument has the wrong type, or the store does not name clones for figures or give the labels that the groups’ colors range over.

  • ValueError – If indices is empty, names an index twice or one that ds.clones.diversity does not measure, or the record holds no group, or no group of it has a value of any index named.

  • KeyError – If theme names no theme, or the store does not hold the record’s clones.

  • RuntimeError – If the record’s clones are incomplete, as a call that stopped before it finished leaves them.

Return type:

PlotResult

cytearc.plotting.clonal_expansion(store, expansion, *, group_by=None, groups=None, count='cells', normalize=True, splits=(10, 100, 1000, 10000, 30000, 100000), target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot the clonal expansion and clonal space of groups of cells.

expansion is a clonal_expansion artifact, such as one from ds.clones.expansion. The first panel draws one stacked bar per group: the fraction of its cells (count="cells") or of its clones (count="clones") in each expansion category, as scirpy’s summarize_clonal_expansion and scRepertoire’s clonalHomeostasis do. The second panel ranks each group’s clones by their cells in the group and draws the fraction of its cells that the clones of each window of ranks hold, as scRepertoire’s clonalProportion does: a sample whose ten largest clones hold most of its cells is dominated by a few clones. Windows that hold no cell are left out.

The groups are the expansion’s own, such as its samples, unless group_by names cell metadata columns, one or several, such as the cell type, or groups a cell-label artifact, such as a clustering; the plotted groups are then the combinations of their labels, as the clone summaries group cells. Both panels title their group axis by the grouping: the columns’ names, a NamedCellArtifact as groups by its name, or else the title of the artifact’s record. The groups follow the order that their columns or label artifact store, then natural order, and receptor types their vocabulary’s. Each cell keeps the category measured within its expansion group, so grouping the cells by cell type shows which cell types hold the expanded cells of their samples; the ranks are counted within the plotted groups. Labels that the clones keep apart stay apart: the plotted groups of clonotypes are each group’s receptor types, named like "blood, TCR". Cells without a category or a group are left out.

Tables: categories (group, category, then n_cells or n_clones, and fraction) and rank_windows (group, window, n_cells and fraction).

Raises:
  • TypeError – If an argument has the wrong type, or the store does not load, group or name clones for figures.

  • ValueError – If expansion is not a clonal_expansion artifact, count is neither "cells" nor "clones", a group_by column is missing, named twice or kept apart by the clones already, two groups get one name, or no cell with a group has a category.

  • KeyError – If the store holds no such artifact.

  • RuntimeError – If an artifact is incomplete, as a call that stopped before it finished leaves it.

  • MemoryError – If reading the artifact or grouping the cells does not fit the memory budget.

Return type:

PlotResult

cytearc.plotting.clonal_rarefaction(store, rarefaction, *, base='size', groups=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot the rarefaction and extrapolation curves of groups of cells.

rarefaction is the result of ds.clones.rarefaction, which sets the groups, the orders and the sizes of each curve. Each panel draws one order of Hill numbers, the effective number of clones, against the cells sampled (base="size") or the sample coverage (base="coverage"), as iNEXT’s ggiNEXT draws them: one line per group, solid where the group is rarefied, dashed where it is extrapolated, and a point at its observed size. With base="size" a last panel draws each group’s sample coverage against its size, which shows how complete each sample is. Curves that keep rising at the observed point have not reached their plateau: more cells would find more clones. The panels fill rows of three, and one legend of the groups stands beside the first row.

groups, a NamedCellArtifact of the label artifact that the record groups by, titles the artifact by its name; without it, the figure takes the title of the artifact’s record.

Tables: curves, the record’s curves (group, order, size, method, diversity, coverage); the record’s group_keys holds each group’s labels.

Raises:
  • TypeError – If rarefaction is not a Rarefaction record, another argument has the wrong type, or the store does not name clones for figures or give the labels that the groups’ colors range over.

  • ValueError – If base is neither "size" nor "coverage", or the record holds no curve.

  • KeyError – If theme names no theme, or the store does not hold the record’s clones.

  • RuntimeError – If the record’s clones are incomplete, as a call that stopped before it finished leaves them.

Return type:

PlotResult

cytearc.plotting.clone_abundance(store, clones, *, group_by=None, groups=None, max_clones=20, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot how many clones have each size, and the largest clones.

clones is a clone artifact, such as one from ds.clones.import_clones or ds.repertoire.clonotypes. The first panel counts clones by their number of cells on log scales: in most experiments many clones hold one or a few cells, and expanded clones form the tail. The second panel draws the max_clones clones with the most cells, labeled with their IDs. Clonotypes are labeled instead by the junction amino acids of their representative cell’s VDJ_1 chain, or of its VJ_1 chain without a VDJ chain, such as CASSLGQAYEQYF, and those defined by receptor_arms="VJ" by the VJ_1 chain first, which their cells share. Where two of the clonotypes drawn share a junction, each label also shows the clonotype’s number, the rank in its ID, such as CAVA 1 and CAVA 3. The figure names the clones as their artifact does, so for clonotypes the second panel’s title reads Largest 20 clonotypes, and for clonotype clusters, which a distance metric defines, Largest 20 clonotype clusters.

group_by names cell metadata columns, one or several, such as the sample or time point, and groups a cell-label artifact, such as a clustering; the groups are the combinations of their labels, as the clone summaries group cells, named by their labels joined by commas. A NamedCellArtifact as groups titles the artifact by its name in the legend, and a bare artifact takes the title of its record. With a grouping, the first panel draws one line per group, counting the cells of each clone within the group, and the second stacks each clone’s cells by group, with one legend of the groups. Cells without a group are left out. Clonotypes are counted within each receptor type, as every clone summary counts them, so their groups are the receptor types, or each group’s receptor types, named like "s1, TCR"; clonotypes defined across receptor types are counted by each cell’s clonotype within its type, labeled as the clonotypes within types label its cells, by its own representative’s junction, then its type, such as CASSB (TCR 2).

Tables: sizes (group, clone_size, n_clones) and top, one row per clone drawn and group, the largest clone first, zeros included (clone, label, group, n_cells); without a grouping, every cell is in the group "all cells". Groups are values of the tables, so a group may take any name.

Raises:
  • TypeError – If an argument has the wrong type, or the store does not load, group or name clones for figures.

  • ValueError – If clones is not a clone artifact, a group_by column is missing, named twice or kept apart by the clones already, two groups get one name, or no cell, or no cell with a group, has a clone.

  • KeyError – If the store holds no such artifact.

  • RuntimeError – If an artifact is incomplete, as a call that stopped before it finished leaves it.

  • MemoryError – If reading the artifact or grouping the cells does not fit the memory budget.

Return type:

PlotResult

cytearc.plotting.clone_coupling(store, coupling, *, value='coupling', color_scale=None, groups=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot the fate coupling of every pair of groups as a heatmap with its dendrogram.

coupling is the result of ds.clones.coupling. value is "coupling" (the default), the method’s value, which ranks the pairs, or "z_score", the coupling’s distance from its null in null standard deviations, which checks whether a pair beats chance. The groups follow the result’s average-linkage order, whose dendrogram is drawn above the matrix. The diagonal is left blank, and pairs that were not compared and z-scores that are not finite take the scale’s missing color; z-scores of a coupling measured without permutations are refused, since it has none. By default z-scores, and couplings below 0, take a scale centered on 0, from minus to plus their largest size, and other couplings viridis; color_scale sets the map and limits instead, so two figures can share them.

The grouping titles the axis below the matrix: the columns’ names, the name of groups, a NamedCellArtifact of the label artifact that the record groups by, or else the title of the artifact’s record.

Tables: matrix (groups by groups, in the drawn order) and pairs.

Raises:
  • TypeError – If coupling is not a CloneCoupling record, color_scale is not a ColorScale, another argument has the wrong type, or the store does not name clones for figures.

  • ValueError – If value is unknown, or names z-scores of a coupling measured without permutations, the record compares no pair, or the coupling’s order does not follow its linkage.

  • KeyError – If theme names no theme, color_scale names no color map, or the store does not hold the record’s clones.

  • RuntimeError – If the record’s clones are incomplete, as a call that stopped before it finished leaves them.

Return type:

PlotResult

cytearc.plotting.clone_fate_bias(store, bias, *, max_clones=40, normalize=False, groups=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot the fates of the clones of early cells, each clone’s late cells by fate.

bias is a clone_fate_bias artifact, such as one from ds.clones.fate_bias. The plot draws the max_clones clones with the most late cells, ties to the larger clone overall, grouped by their dominant fate, the fate that holds the most of their late cells, in the order of the fates, and within a fate from the most late cells to the fewest; clones whose late cells tie between fates come last. The fates follow the order that their columns or label artifact store, then natural order, and the receptor types their vocabulary’s. The lower panel stacks each clone’s late cells by fate, the first fate on top, or their fractions with normalize=True, and the upper panel draws its early cells. The fates take the colors of their groups, as every figure grouped by the same columns colors them, and a title that drops clones says how many it draws of how many. Clones are labeled as clone_abundance labels them: by their IDs, and clonotypes by their representative’s junction, with their number where two drawn share one.

groups, a NamedCellArtifact of the label artifact that the record groups by, titles the artifact by its name; without it, the figure takes the title of the artifact’s record.

Tables: clones, one row per clone drawn, in the drawn order (clone, label, fate, the dominant fate, missing for a tie, n_early_cells, n_late_cells), and fates, one row per clone drawn and fate, zeros included (clone, label, fate, n_cells, the clone’s late cells in the fate). Fates are values of the tables, so a fate may take any name.

Raises:
  • TypeError – If an argument has the wrong type, or the store does not load or name clones for figures, or give the labels that the fates’ colors range over.

  • ValueError – If bias is not a clone_fate_bias artifact, or no clone of the early cells has late cells.

  • KeyError – If the store holds no such artifact.

  • RuntimeError – If an artifact is incomplete, as a call that stopped before it finished leaves it.

  • MemoryError – If reading the artifact, or the labels of the clones drawn, does not fit the memory budget.

Return type:

PlotResult

cytearc.plotting.clone_overlap(store, overlap, *, index='morisita_horn', color_scale=None, groups=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot an overlap index between every pair of groups as a heatmap.

overlap is the result of ds.clones.overlap, which sets the groups. index is one of its indices: "shared", "jaccard", "sorensen", "overlap", "cosine", "morisita_horn" (the default) and "abundance_cosine". The diagonal is left blank so that the colors span the pairs, and pairs that were not compared take the scale’s missing color; the matrix table holds each group’s clones on its diagonal for "shared" and 1 otherwise. color_scale sets the color map and limits, viridis over the pairs’ values by default, so two figures can share them.

The groups follow the order that their columns or label artifact store, then natural order, and the grouping titles the axis below the matrix: the columns’ names, the name of groups, a NamedCellArtifact of the label artifact that the record groups by, or else the title of the artifact’s record.

Tables: matrix (groups by groups, in the drawn order) and pairs, the record’s pairs.

Raises:
  • TypeError – If overlap is not a CloneOverlap record, color_scale is not a ColorScale, another argument has the wrong type, or the store does not name clones for figures.

  • ValueError – If index is not an overlap index, or the record compares no pair.

  • KeyError – If theme names no theme, color_scale names no color map, or the store does not hold the record’s clones.

  • RuntimeError – If the record’s clones are incomplete, as a call that stopped before it finished leaves them.

Return type:

PlotResult

cytearc.plotting.clone_tracking(store, tracking, *, order=None, groups=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot the fraction of cells of chosen clones across groups of cells.

tracking is the result of ds.clones.track, which chooses the clones and sets the groups: the top_n clones with the most cells in each group, or the clones it was given. Each clone draws one line across the groups, such as time points or cell types, of its fraction of each group’s cells with a clone. A line is labeled with its clone’s ID, or for a clonotype with its representative’s junction, such as CASSA, and also its number where two of the clonotypes followed share a junction, such as CASSA 1 and CASSA 3, as clone_abundance labels the largest clones. Groups are placed by their labels in the group_by columns and the groups artifact, joined by commas; order lists those names from left to right, or values whose text is the name, such as time points as integers, and by default the names follow the order that their columns or label artifact store, then natural order. The legend lists the clones, the largest first.

The grouping titles the axis of the groups: the columns’ names, the name of groups, a NamedCellArtifact of the label artifact that the record groups by, or else the title of the artifact’s record.

Tables: tracking, the record’s table with each clone’s label after its clone (clone, label, group, n_cells and fraction); the record’s group_keys holds each group’s labels.

Raises:
  • TypeError – If tracking is not a CloneTracking record, order is not a sequence of group names, another argument has the wrong type, or the store does not name or label clones for figures.

  • ValueError – If order does not list the groups, or the record follows no clone.

  • KeyError – If the store does not hold the record’s clones.

  • RuntimeError – If the record’s clones are incomplete, as a call that stopped before it finished leaves them.

  • MemoryError – If reading the labels of the clones followed does not fit the memory budget.

Return type:

PlotResult

cytearc.plotting.cluster_connectivity(store, *, group_by=None, layout_key=None, groups=None, layout=None, graph, cell_key='I', position='median', positions=None, categorical_scale=None, size_scale=None, minimum_edge_weight=0.02, max_edges_per_node=None, show_cells=False, cell_size=None, cell_alpha=0.3, cell_color=None, node_edgecolor=None, node_linewidth=0.8, edge_color=None, edge_alpha=0.45, edge_width_range=(0.4, 5.0), labels=True, target=None, figsize=None, theme='notebook', show=True)#

Plot cluster connectivity on an existing two-dimensional cell layout.

rawWeight is the sum of intercluster weights after reciprocal sparse graph entries are counted once. normalizedWeight divides that value by sqrt(incidentWeight[source] * incidentWeight[target]). Incident weight is the sum of weighted cell degrees in each cluster, including internal cluster edges. Clusters with zero incident weight receive a normalized value of zero. DataStore.clusters.connectivity returns these weights as tables without drawing a figure.

layout must hold the graph’s cells, whichever operation made its cell selection. groups are read for the graph’s cells, which their own cells must include, so labels of more cells serve. A layout of other cells, or groups without a label for some of the graph’s cells, raise ValueError. A NamedCellArtifact as groups titles the groups’ legend by its name; a bare artifact takes the title of its record. group_by names a live column as text or as a CellField, whose label titles the legend in place of the column’s name.

Return type:

PlotResult

cytearc.plotting.cluster_tree(store, *, graph, clusters, from_assay=None, fill_by_value=None, force_ints_as_cats=True, width=1, lvr_factor=0.5, vert_gap=0.2, min_node_size=10, node_size_multiplier=10000.0, node_power=1.2, root_size=100, non_leaf_size=10, show_labels=True, fontsize=10, root_color='#C0C0C0', non_leaf_color='k', cmap=None, color_key=None, edgecolors='k', edgewidth=1, alpha=0.7, figsize=(5, 5), ax=None, theme='notebook', show=True)#

Plot the coalesced hierarchy for a clustering result.

Clusters, and the categories of a categorical fill_by_value column, take the colors that an embedding colored by them takes: the categories and colors that the column or the clustering stores, such as the uns colors that an H5AD import keeps, or else default colors assigned over every label of the column in natural order. color_key names a color for each category, and cmap, a Matplotlib colormap name or a registered Colormap, is sampled at evenly spaced positions over the categories instead. A numeric fill takes cmap, viridis by default.

Return type:

PlotResult

cytearc.plotting.compose_results(figure, results, *, panel_labels=True, shared_legends=True, owns_figure=False, theme=None)#

Merge caller-targeted plot results into one inspectable figure result.

With shared_legends=True, the legends of the children are drawn again beside the figure and their colorbars below their axes, once for legends that several children share. A categorical legend lists the scale’s missing label last when a child draws values without a category, and a legend that several children share lists it when any of them does. A child that reports no legend, or one that cannot be drawn this way, such as a line legend or a categorical legend whose scale has no order or palette, keeps the legends and colorbars it drew.

The result’s axes holds every axis of the children that the figure still draws, the insets that a panel holds included, such as a matrix plot’s dendrograms, keyed by the child’s name or position and the axis’s key. A child’s colorbar that a shared colorbar replaces is no longer drawn and is left out.

Return type:

PlotResult

cytearc.plotting.composition(store, *, category_by=None, categories=None, cell_key='I', sample_by=None, grouping=None, subject_by=None, pair_by=None, condition_by=None, study_design=None, kind='stacked', show_summary=True, uncertainty=None, categorical_scale=None, bar_width=0.82, bar_gap=0.12, segment_edgecolor=None, segment_linewidth=0.5, show_percent_labels=False, label_min_fraction=0.08, percent_format='{:.0%}', target=None, figsize=None, max_figure_width=7.5, theme='notebook', show_legend=True, show=True)#

Show how cell categories (clusters, cell types) vary across samples.

kind="stacked" draws stacked bars. With sample_by, there is one bar per sample; without it, one bar for the whole dataset. grouping is the immutable artifact counterpart to sample_by for analytical groupings such as clusters. It is available only for stacked composition. Beside categories, its labels are read for the cells of categories, which its own cells must include, so a grouping of more cells, such as labels of every cell, serves; a grouping that holds no label for some of them raises ValueError. A NamedCellArtifact as categories or grouping titles the legend or the bar axis by its name; a bare artifact takes the title of its record. The cell columns of category_by, sample_by, subject_by, pair_by and condition_by are named as text or as a CellField. A column’s name titles the legend of the categories and the bar axis of the samples, and the legend of the conditions is titled “Condition”; a CellField’s label titles them instead. The bars follow the order that sample_by or grouping stores, as a stored display or ordered categories, and natural order without one. kind="per_sample" draws one point per sample in each category (requires sample_by or a StudyDesign).

For paired before/after designs, pass condition_by together with subject_by or pair_by (directly or via study_design). CyteArc then connects the same subject across conditions inside each category. When a subject has several samples in one condition, those proportions are averaged for the connecting line. Conditions follow the order that condition_by stores, or else come before/after names first, such as “baseline” before “treated”, and the others in natural order. Per-sample plots show sample means with 95% confidence intervals by default. Use uncertainty to select standard deviation, standard error, or no interval.

Figure width is capped so large category lists stay page-sized.

Return type:

PlotResult

cytearc.plotting.distribution(store, keys, *, grouping=None, cell_selection=None, groups=None, split_by=None, sample_by=None, study_design=None, sample_stat='mean', expression_cutoff=0.0, subset_by=None, from_assay=None, normalization=None, categorical_scale=None, split_scale=None, kind='violin', bins=40, max_points=10000, max_density_points=20000, point_size=0.8, point_alpha=0.28, seed=0, color='steelblue', color_by='group', color_scale=None, orientation='vertical', row_standardize=False, share_y=None, violin_inner='quartile', violin_linewidth=0.8, violin_alpha=0.9, italicize_features=False, target=None, figsize=None, max_figure_width=7.5, title=None, theme='notebook', show_legend=True, stats_results=None, stats_keys=None, stats_bracket_height=None, stats_show_p=True, show=True)#

Compare value distributions for QC metrics or genes.

keys may be cell-metadata columns (for example RNA_nCounts), gene names, or one exact cell_cycle artifact. The artifact form plots its canonical s_score and g2m_score arrays. kind selects the display: "violin", "box", "hist", or "ecdf". With With grouping, each category gets its own distribution along the x-axis and a distinct color. A CellField label or a NamedCellArtifact name titles the group axis; a bare artifact takes the title of its record.

Cell selection (same knobs as embeddings):

  • cell_selection: exact frozen selection; omit it to include every cell for metadata-backed values

  • subset_by: boolean metadata column; keep True cells

  • groups: keep or order grouping categories

For violins and boxes, CyteArc can overlay a subsample of cells as points. max_points limits how many points are drawn (0 disables points). The public default is 10000 for compatibility. Explicit None uses a kind-specific behavior: no overlay for stacked violins and 10000 for other kinds. Histograms always use every selected cell. Regular multi-gene violin and box panels share their value scale by default. Stacked violins keep independent scales unless share_y=True. With horizontal orientation, the same option shares the x-axis value scale.

Every violin, including each half of a split violin, is scaled to the full width, as in scanpy, so a group whose values pile up at zero still shows its shape. A violin with more than max_density_points values estimates its density, and draws its quartiles, from a seeded random max_density_points of them that keeps its smallest and largest value, which bounds the cost on large datasets; None uses every value. Smaller violins use every value, and provenance.notes gains "subsampled_density" when any violin was subsampled.

Default group colors are assigned over every label of the grouping column or artifact, so a group keeps its color whatever groups or subset_by select. Tick and legend labels follow CategoricalScale.labels, from categorical_scale, split_scale, or the column’s stored display.

Set sample_by or study_design to summarize cells within biological samples before plotting. A study design’s subject_by or pair_by column is used only with paired Wilcoxon stats_results, matching run_statistical_testing. split_by draws two violin halves for a second categorical variable. split_by and sample_by name cell columns as text or as a CellField, whose label titles the legend of the split in place of the column’s name.

Pass stats_results (a single StatisticalTestResult, or a mapping from panel label to one) to annotate significance brackets over the drawn violins or boxes. Brackets are pure matplotlib overlays positioned by the displayed category order; pairwise tables place one bracket per row, while one-way ANOVA and Kruskal-Wallis omnibus results span every group. A Dunn posthoc table is preferred over its Kruskal-Wallis omnibus table when both are present. The annotation prefers p_value_adjusted when present. Nothing is recomputed here. Results must carry the selection, grouping, tested-value, assay, sample-design, and normalization identity recorded by run_statistical_testing; incompatible or incomplete results are skipped with a warning. Statistical overlays cannot be combined with split_by.

For kind="stacked_violin", pass color_by="mean" to color each stacked violin by its group mean on a continuous scale, whose color bar names the means: “mean expression” for the RNA assay and otherwise the assay, such as “mean of GeneScores”. Pass a ColorScale to control the mapping: cmap chooses the colormap, vmin/vmax fix explicit limits, quantiles clips extreme means, and vcenter enables diverging maps. The color scale follows share_y: scope="shared" when share_y=True and scope="panel" otherwise. ColorScale’s general scope="feature" default is treated as automatic here; explicit "shared" or "panel" overrides it. A scope="shared" scale is drawn as a colorbar on the right; scope="panel" rescales each row independently and draws a single reference colorbar. On caller-supplied axes the colorbar is not drawn; its limits are exposed through PlotResult.legends. color_by="mean" cannot be combined with split_by.

Raises:

ValueError – If a gene’s assay measured none of the plotted cells.

Return type:

PlotResult

cytearc.plotting.dotplot(store, *, features, group_by=None, groups=None, cell_key='I', from_assay=None, sample_by=None, study_design=None, normalization=None, expression_cutoff=0.0, standardize='none', color_scale=None, size_scale=None, categorical_scale=None, group_order=None, feature_order=None, swap_axes=False, marker_edgecolor=None, marker_linewidth=0.3, label_wrap=None, italicize_features=False, target=None, figsize=None, max_figure_width=7.5, theme='notebook', show_legend=True, show=True)#

Dotplot of expression by group.

Color is the mean value in the group, and the color bar names it: “Mean expression” for the RNA assay and otherwise the assay, such as “Mean of GeneScores”. Dot size is the fraction of measured cells above expression_cutoff. Pass features as a list of genes, or as a mapping of group name to gene list when you want gene-set brackets. Different features of one assay that carry the same explicit FeatureRef.label are pooled into one row. Any other label shared by different features raises, including a label shared across assays.

With sample_by, a column name or a CellField, or with study_design.sample_by, each sample contributes equally: CyteArc first summarizes within sample, then averages across samples. Without it, every cell contributes equally.

group_by names one cell column or two, each as text or a CellField. Groups follow group_order, or the order of categorical_scale, which must list every group. Otherwise they follow the categories of their first column, then of their second, each column in the order that it stores, as a stored display or ordered categories, and in natural order without one; a label artifact’s groups follow the order it stores.

The group axis is titled by the titles of the group_by columns, a CellField’s label or else its key, joined by “ / “, or by the name of a NamedCellArtifact as groups, or else by the title of the label artifact’s record.

Return type:

PlotResult

cytearc.plotting.edistance(store, edistance, *, max_rows=40, alpha=0.05, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot how far each perturbation moves its cells from the control cells.

edistance is a perturbation_edistance artifact of ds.perturbation.edistance, as ds.perturbation.load_edistance reads it. Each tested target, or each tested guide when the E-distances were measured by guide, gets one row labeled with its name. A point marks the E-distance between the cells that carry the perturbation and the control cells in the coordinates it was measured in, such as a PCA; it grows as the perturbation moves its cells away from the control cells. The E-distance is an unbiased estimate, so a perturbation whose cells look like the control cells can fall a little left of the line at 0. A point is blue when the row is significant at the false discovery rate alpha, its adjusted p-value at most alpha, and gray otherwise, and its area grows with the cells that carry the perturbation. When the E-distances were measured without permutation tests, no row has a p-value: every point is blue, and the title says so.

When more than max_rows rows were tested, the plot keeps the max_rows rows with the largest E-distances, ties broken by name. The rows run from the largest E-distance at the top to the smallest at the bottom. Rows whose status is not "tested" are left out, and the title counts them by status; the plot raises ValueError when no row was tested. The table "edistance" holds the drawn rows of the record, with every column, in drawing order.

Return type:

PlotResult

cytearc.plotting.efficiency(store, efficiency, *, max_rows=40, alpha=0.05, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot how strongly each perturbation changes the expression of its target gene.

efficiency is a perturbation_efficiency artifact of ds.perturbation.efficiency, as ds.perturbation.load_efficiency reads it. Each tested target, or each tested guide when the efficiency was measured by guide, gets one row labeled with its name. A point marks the log2 fold change of the target gene’s mean expression in the cells that carry the perturbation against control cells, so a knockdown falls left of the line at 0 and an activation right of it. A point is blue when the row is significant at the false discovery rate alpha, its adjusted p-value at most alpha, and gray otherwise, and its area grows with the cells that carry the perturbation. When those cells hold no counts of the gene, the fold change is minus infinity: a triangle at the left edge marks it, and the row’s label ends in “(no counts)”.

When more than max_rows rows were tested, the plot keeps the max_rows rows with the smallest adjusted p-values, ties broken by name. The rows run from the strongest knockdown at the top to the strongest activation at the bottom. Rows whose status is not "tested" are left out, and the title counts them by status; the plot raises ValueError when no row was tested. The table "efficiency" holds the drawn rows of the record, with every column, in drawing order.

Return type:

PlotResult

cytearc.plotting.elbow(variance_explained, figsize=(None, 2), theme='notebook', show=True)#

Plot explained variance and mark the detected elbow.

Principal components are numbered from 1, as dims counts them, so the elbow line stands at the number of the PC where the curve bends. The variance_explained table holds pc, variance_explained and is_elbow for each PC, and provenance.extras["elbow_pc"] holds the elbow PC’s number, or None when no elbow is detected. Fewer than three values, or values that are all equal, have no elbow. Without a width in figsize, the figure is a quarter inch wide for each PC and at least 2.25 inches wide.

Return type:

PlotResult

cytearc.plotting.embedding(store, *, layout_key=None, layout=None, color_by=None, facet_by=None, facet_order=None, cell_key='I', from_assay=None, normalization=None, point_size=None, point_sizes=None, point_size_range=(1.0, 28.0), point_edgecolor=None, point_edgewidth=None, point_alpha=1.0, sort_values=None, color_scale=None, categorical_scale=None, default_color='steelblue', missing_color=None, clip_fraction=0.0, subset_by=None, groups=None, n_columns=None, target=None, figsize=None, theme='notebook', legend_loc='auto', max_on_data_labels=40, show_legend=True, show_titles=True, frame='minimal', density_overlay=None, highlight=None, seed=0, rasterize_threshold=50000, show=True)#

Scatter cells on one or more 2D layouts (UMAP, t-SNE, and similar).

color_by accepts a cell-metadata column, a gene name, or a list of either. With several genes, CyteArc draws one panel per gene. With facet_by, each gene becomes a row of facet panels that wraps at four columns, and cells without a facet value get their own panel, titled with the facet column’s missing label (NA by default). Facets follow groups or facet_order, or else the order that the facet column stores, as a stored display or ordered categories, and natural order without one. facet_by names the column as text or as a CellField, whose label names the column in each facet’s title, such as Stage=early, and refuses another value or kind="continuous". Color limits for a gene are shared across facets so panels stay comparable. Multiple layout_key values produce the cartesian product of layouts and colors in one figure, one layout per row of panels.

Common choices:

  • subset_by: keep cells marked True in a boolean metadata column.

  • groups: keep only these categories. Applies to facet_by when set, otherwise to the first categorical color_by column. Also sets legend order when categorical_scale.order is omitted.

  • legend_loc: "auto" puts a side legend when there are few categories, labels on the clusters for medium category counts, and a wrapped side legend for larger sets. Use "right", "on_data", or "none" to force a placement. On-data labels sit at their cells’ median and move apart by at most about one label height, never closer to another cluster’s median than to their own. A side legend lists the categories that fit beside the figure, the most frequent first.

  • frame: "minimal" (default) keeps an L-shaped axes edge without UMAP tick labels. "none" removes the box. "axes" keeps UMAP1 / UMAP2 labels on the outer panels.

  • point_size: leave as None to size markers from the cell count. Pass a number (matplotlib marker area) or point_sizes for per-cell sizes such as mapping confidence: a pandas Series of the plotted cells’ sizes indexed by cell ID, whose values of other cells are left out.

  • sort_values: whether continuous colors draw high values last, so expressing cells sit on top of the cloud. The default, None, sorts gene and other feature colors and shuffles the rest; True sorts every continuous color and False none.

  • seed: categorical colors, and continuous colors that are not sorted, draw their cells in a shuffled order, so cells stored last, such as the last sample of a merged store, do not cover the others. Each cell draws at its rank in numpy.random.default_rng(seed).permutation(n) over the n cells of the layout, so the order is reproducible and the same in every panel. None draws cells in stored order.

  • missing_color: the color of cells without a value. It replaces the missing color of whichever categorical or continuous scale applies.

  • clip_fraction: clip continuous values to these quantiles of the drawn cells, for example 0.01 for the 1st to 99th percentile.

  • theme: "notebook" or "paper" for white figures; "dark" for dark notebook themes.

An artifact in color_by takes an embedding artifact as layout, and its cells must include the layout’s. NamedCellArtifact(name, artifact) titles its panel and legend, and keys its panel, by name; a bare artifact takes the title of its record, such as the column that a snapshot copied or “Leiden, resolution 1.0”. Its values are read for the layout’s cells: its values are read for the layout’s cells, so labels computed on every cell can color a run’s layout of fewer cells. An artifact that holds no value for some cells of the layout raises ValueError; compute it on cells that include the layout’s, such as the run’s analysis_cell_selection.

Default category colors are assigned over every value of the colored column or label artifact, not only the drawn cells, so a category keeps its color in plots of different subsets or groups. A stored display or a categorical_scale order or palette sets them instead, and an immune_receptors artifact draws its receptor types in the colors of receptor_qc unless a categorical_scale is given. A log ColorScale draws values that are not positive in its missing color.

Returns a PlotResult. Access .figure in notebooks, or call .save(...) / .close() when you own the figure.

Return type:

PlotResult

cytearc.plotting.embedding_raster(store, *, layout_key=None, layout=None, color_by=None, cell_key='I', pixels=400, block_rows=None, color_scale=None, missing_color=None, subset_by=None, target=None, figsize=None, theme='notebook', seed=0, show=True)#

Draw a layout as a pixel image for large cell counts.

Prefer this over embedding() when you only need a continuous cell-metadata color (for example RNA_nCounts) and the dataset is large enough that a full scatter is slow or memory-heavy. Values are read in row blocks, so full columns are not loaded at once.

Provide exactly one coordinate source. layout consumes an immutable embedding artifact and its stored cell selection. layout_key reads two explicit live metadata columns named {layout_key}1 and {layout_key}2.

color_by must be continuous metadata, not a gene. Pass CellField(key, kind="continuous") when an integer column should be treated as continuous. Categorical colors are not supported here. Empty pixels show the axes background, white in the light themes. A pixel whose cells all lack a color value takes the missing color, as such cells do in embedding(): ColorScale.missing_color, gray by default, or missing_color as an explicit override. Pass subset_by to keep cells marked True in a boolean cell-metadata column.

Return type:

PlotResult

cytearc.plotting.gene_pairing(store, usage, *, max_genes=20, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot how the V and J genes of each locus pair, one panel per locus.

usage is the result of ds.repertoire.gene_usage for the pairs of genes=("v_call", "j_call") without groups, which sets the level, the slots, the cells and what is counted. Each panel draws the fraction of the locus’s chains with each pair of its max_genes V genes and max_genes J genes with the most chains, its axes saying how many of how many they draw when they leave some out. The panels stand two to a row and share one color bar, from 0 to the largest fraction drawn. The plot raises ValueError when usage counts other gene fields or groups of cells, or no chain has both calls.

Tables: pairs, the record’s rows.

Raises:
  • TypeError – If usage is not a GeneUsage record, or another argument has the wrong type.

  • ValueError – If usage counts other gene fields or groups of cells, or no chain has both calls.

  • KeyError – If theme names no theme.

Return type:

PlotResult

cytearc.plotting.gene_usage(store, usage, *, max_genes=30, groups=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot the gene usage of groups of cells, one panel per locus.

usage is the result of ds.repertoire.gene_usage for one gene field, such as genes="j_call", which sets the groups, the level, the slots and what is counted. Each panel holds one locus, such as TRA or TRB, and at most max_genes of its genes: those that rank highest in any group, so each group’s most used genes are drawn even where they are rare over all groups, listed by their chains over all groups, its axis saying how many of how many it draws when it leaves some out: for groups of group_by columns or a groups artifact, a heatmap of each gene’s fraction of each group’s chains of that locus, which names the group even where one group holds the locus, the panels of every locus sharing one color bar from 0 to the largest fraction drawn, two panels to a row; without, bars in the locus’s color, three panels to a row. With count="clonotypes" the fractions count clonotypes, or clonotype clusters for clonotypes that a distance metric linked. The plot raises ValueError when usage counts several gene fields or no chain has a call of its field.

groups, a NamedCellArtifact of the label artifact that the record groups by, titles the artifact by its name; without it, the figure takes the title of the artifact’s record.

Tables: usage, the record’s rows.

Raises:
  • TypeError – If usage is not a GeneUsage record, or another argument has the wrong type.

  • ValueError – If usage counts several gene fields, or no chain has a call of its field.

  • KeyError – If the store does not hold the clonotypes that usage counts.

  • RuntimeError – If those clonotypes are incomplete, as a call that stopped before it finished leaves them.

Return type:

PlotResult

cytearc.plotting.genotypes(store, genotypes, *, sites=None, group_by=None, groups=None, layout=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot the cells’ genotype calls by group and on an embedding.

genotypes is a variant_genotypes artifact, such as one from ds.variants.genotypes, and sites the sites to draw, by label or position as ds.variants.load_genotypes takes them, every site by default. The first panel draws, for each site, one bar per group of the fractions of the group’s cells with each call, the first call of the legend at the left; a cell that the calls do not list at a site is missing there. group_by names cell metadata columns, one or several, such as the cell type, and groups a cell-label artifact; the groups are the combinations of their labels, as the clone summaries group cells, named by their labels joined by commas, in the order that their columns or label artifact store, then natural order. Each bar is named by its site and group, and the axis of the bars is titled by Site and the grouping: the columns’ names, a NamedCellArtifact as groups by its name, or else the title of the artifact’s record. Without either, each site has one bar of all cells. Cells without a group are left out.

With layout, an embedding artifact of the genotypes’ cells, whichever operation made its cell selection, such as a UMAP of the cells whose counts were imported, the second panel draws the cells at the embedding’s coordinates, as embedding(layout=...) draws them, colored by their call at the one site that sites names or the genotypes hold; cells without a call there are drawn under the others. The calls take one palette, named in words under one legend beside the last panel, missing in the gray of no value and filtered in the muted gray.

Tables: calls (site, group, call, n_cells, share) and, with a layout, cells (ids, x, y, call).

Raises:
  • TypeError – If layout is not an ArtifactRef, another argument has the wrong type, or the store does not load genotypes or group cells for figures.

  • ValueError – If no cell has a group, a group_by column is missing or named twice, two groups get one name, sites names a site the genotypes do not hold, a layout is drawn for several sites, or layout is not an embedding of the genotypes’ cells.

  • KeyError – If the store holds no such artifact.

  • RuntimeError – If an artifact is incomplete, as a call that stopped before it finished leaves it.

  • MemoryError – If reading the artifact or grouping the cells does not fit the memory budget.

Return type:

PlotResult

cytearc.plotting.graph_qc(graph, theme='notebook', show=True)#

Plot node degree and edge weight distributions for a sparse graph.

Return type:

PlotResult

cytearc.plotting.guide_calls(store, calls, *, max_guides_per_cell=5, bins=20, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot how many guides each cell carries and how many cells carry each guide.

calls is a guide_calls artifact, such as one from ds.perturbation.call_guides or ds.perturbation.import_guide_calls. The first panel counts cells by their number of called guides; its last bar gathers the cells with max_guides_per_cell or more. The second counts, for each guide, the cells in which it is the one called guide and the cells in which it is one of several: one labeled bar per guide for a library of at most 40 guides, and guides ranked by their cells for a larger one. The third shows the top guide’s share of each cell’s guide UMIs, for cells with guide UMIs, by call. A cell with several called guides whose top guide holds nearly all of its guide UMIs may carry one guide and ambient molecules of the others. The plot raises ValueError when the calls hold no cell.

Return type:

PlotResult

cytearc.plotting.guide_thresholds(store, thresholds, *, guides=None, samples=None, max_panels=12, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot the UMI thresholds that guide calling fitted to each guide in each sample.

thresholds is guide calls of ds.perturbation.call_guides with method="poisson_gaussian" or "gaussian", or their guide_thresholds artifact, as ds.perturbation.load_guide_thresholds reads them.

With guides, any collection of guide IDs such as the guides index of the loaded record, each selected guide gets one panel per sample. Bars count the cells at each UMI count of the guide, blue where the count is called and gray where it is not, on log scales; the UMI axis is a log scale of count + 1, so the cells without a UMI of the guide appear at 0. A line on the right axis shows the posterior of the guide population, the model’s probability that a cell with that count carries the guide, at counts from 1 to the guide’s largest. A dashed line marks the model’s threshold, and a dotted line marks the higher threshold that min_umi set for the calls. A panel whose status is not "fitted" names its status and calls no cell; a "no_positive" fit still draws its model.

Without guides, the plot gives an overview of every fit: the model’s threshold against the number of cells with a UMI of the guide, one point per guide and sample on log scales of count + 1, and the number of fits of each status. The points are rasterized when there are more than 50,000.

samples keeps the panels or points of those sample labels. When guides and samples select more than max_panels panels, the plot raises ValueError rather than draw a crowded figure, as it does when the fits hold no guide. A panel’s axes take the guide as key, or (sample, guide) when the fits have a sample column, and its posterior axes take (key, "posterior"). The tables "thresholds" and "histograms" hold the selected rows of the record and, with guides, "posterior" holds the posterior at each drawn count: every count when the guide’s largest is at most 1,000, and otherwise 1,000 counts spread evenly on the log scale.

Return type:

PlotResult

cytearc.plotting.highly_variable_features(mean_nonzero, corrected_variance, n_cells, selected, *, label_size=12, figsize=(4.5, 4.0), point_sizes=(3, 30), colormaps=('winter', 'magma_r'), theme='notebook', show=True)#

Plot mean-variance diagnostics for feature selection.

colormaps colors the features not selected and the selected ones by the number of cells that express them, each a Matplotlib colormap name or a registered Colormap, or None for Matplotlib’s default. The legend marks each group with one marker of one size in the middle color of its colormap. point_sizes holds the two groups’ marker areas in points squared, label_size the size in points of the axis labels and ticks, and figsize the figure’s width and height in inches, or None for CyteArc’s default panel size. Every option is checked before the plot draws.

Return type:

PlotResult

cytearc.plotting.label_panels(axes, *, labels=None, fontsize=None, fontweight='bold', x=-0.06, y=1.04)#

Add A/B/C panel labels to axes in order.

Return type:

None

cytearc.plotting.lineage_curves(store, *, curves, layout, lineages=None, df=None, lineage_cmap=None, line_width=2.5, point_size=None, point_alpha=0.6, cell_color='#d0d0d0', target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Draw fate-weighted lineage curves over a two-dimensional layout.

The curves were fitted in their own coordinates, often many reduced dimensions. To draw one in a layout such as a UMAP, the layout coordinates of the cells are averaged with the lineage’s fate weights along the cells’ positions on the curve and smoothed with the spline the curves were fitted with, as Slingshot’s embedCurves does. ds.trajectory.curves_in_layout returns the points drawn, without a figure. df overrides the curves’ degrees of freedom for this smoothing; like theirs, it lies between 2 and the size of their spline basis, 32 by default. layout must hold every cell of the curves, whichever operation made its cell selection, and may hold more, such as every cell of the graph when the curves follow some of its cells; the plot draws the curves’ cells. A layout that lacks one raises ValueError. The lineages take their colors as in lineage_trends.

Return type:

PlotResult

cytearc.plotting.lineage_heatmap(store, *, aggregation, lineages=None, show_features=None, figsize=None, vmin=None, vmax=None, heatmap_cmap='coolwarm', pseudotime_cmap='viridis', clusterbar_cmap=None, tick_fontsize=10, axis_fontsize=12, feature_label_fontsize=10, theme='notebook', show_legend=True, show=True)#

Plot fate-weighted feature profiles side by side for each lineage.

Rows are features, grouped by module and, within a module, ordered by where their profile peaks. Each lineage’s panel runs from the shared start to its sink, with a strip of the bins’ mean pseudotime above it. Colors span vmin to vmax. By default that is -2 to 2 for z-scaled profiles, and from the smallest mean to the 99th percentile for profiles stored without z-scaling, which the colorbar labels as mean expression.

show_features labels rows beside the last panel. A name matches the retained features case-insensitively and keeps the caller’s spelling, and a FeatureRef finds a feature by name, ID, or index and shows its label, or its name, followed by its ID where another row has that name. A name that several retained features share raises ValueError naming their IDs; pick one with FeatureRef(value=feature_id, by="id"). A feature that the aggregation did not retain is skipped.

The strip beside the rows colors the modules from the colorblind palette in module order, as lineage_trends colors lineages, and more than 12 modules take evenly spaced hues, with a warning; a clusterbar_cmap is sampled at evenly spaced positions instead. heatmap_cmap and pseudotime_cmap color the profiles and the pseudotime strips. Each colormap argument takes a Matplotlib colormap name or a registered Colormap.

Return type:

PlotResult

cytearc.plotting.lineage_tree(store, *, tree, layout, show_cells=True, cell_color='#d0d0d0', point_size=None, point_alpha=0.5, node_size=80.0, node_color='#56B4E9', root_color='#0072B2', leaf_color='#D55E00', edge_color='#555555', labels=True, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Draw a cluster tree over a two-dimensional layout.

Each cluster sits at the median layout position of its cells. The root is a square in root_color, the candidate sinks, the leaves other than the root, are triangles in leaf_color, and the other clusters are circles in node_color; the legend shows each role’s marker. The default colors come from the colorblind palette, and the shapes tell the roles apart in any colors. layout must hold every cell of the tree, whichever operation made its cell selection, and may hold more, such as every cell of the graph when the tree joins clusters of some of its cells; the plot draws the tree’s cells. A layout that lacks one raises ValueError.

Return type:

PlotResult

Plot selected features’ profiles along each lineage.

Each panel is one feature, with one line per lineage through the lineage’s bins, so lineage-specific rises and falls stand side by side. With axis="progress" the bins are spaced by the share of the lineage’s fate weight they have passed, so every bin is equally wide; with axis="pseudotime" they sit at their mean pseudotime, where bins inside an endpoint crowd together.

features names retained features of the aggregation. A name matches case-insensitively and titles its panel in the caller’s spelling. A FeatureRef finds a feature by name, ID, or index, and its panel takes its label, or the feature’s name, followed by its ID where another retained feature has that name. A name that several retained features share raises ValueError naming their IDs; draw one of them with FeatureRef(value=feature_id, by="id").

By default the lineages take the 12 colors of the colorblind palette in order, as CategoricalScale(palette_name="colorblind") assigns them. More than 12 lineages take evenly spaced hues instead, with a warning that they may not be colorblind safe. lineage_cmap takes a Matplotlib colormap, by name or as a registered Colormap, to sample at evenly spaced positions from 0 to 1, and a single lineage then takes the colormap’s first color.

Return type:

PlotResult

cytearc.plotting.mapping_calibration(store, transfer, *, known_labels, metric='voteFraction', direction='auto', thresholds=None, n_thresholds=50, chosen_threshold=None, target=None, figsize=None, theme='notebook', show=True)#

Plot held-out label accuracy against retained coverage per threshold.

transfer is a label_transfer artifact from ds.mapping.transfer_labels, and known_labels the known label of each of its cells, missing where it is unknown, as a pandas Series indexed by cell ID; labels of other cells are left out. Each threshold on metric is applied to the transfer’s saved candidate labels, so no transfer is recomputed. The thresholds replace the transfer’s own rule on the swept metric, threshold_fraction for voteFraction and max_distance for nearestDistance, and every other saved rule still applies. Any other metric is therefore calibrated among the cells that the transfer labeled.

chosen_threshold is added to the thresholds and marked. Without it, the transfer’s own rule on the swept metric, when it has one, is marked: it joins the default thresholds, and with explicit thresholds it is marked only when it is one of them.

Return type:

PlotResult

cytearc.plotting.mapping_confusion(store, transfer, *, known_labels, normalize='true', known_order=None, predicted_order=None, abstention_label='Abstained', color_scale=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot known query labels against the labels of one saved transfer.

transfer is a label_transfer artifact from ds.mapping.transfer_labels. known_labels holds the known label of each cell of the transfer, missing where it is unknown, as a pandas Series indexed by cell ID; labels of other cells are left out. Cells that abstained form the abstention_label column, which must differ from every known and transferred label.

Return type:

PlotResult

cytearc.plotting.mapping_evidence(store, transfer, *, target_groups=None, metrics=('voteFraction', 'topTwoMargin', 'voteEntropy', 'referenceDistancePercentile'), kind='histogram', bins=30, categorical_scale=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot the saved evidence of one label transfer for query groups.

transfer is a label_transfer artifact from ds.mapping.transfer_labels. The plot reads its saved evidence, so it shows exactly the votes and distances that decided the saved labels. target_groups names the group of each cell of the transfer, as a pandas Series indexed by cell ID; values of other cells are left out.

Return type:

PlotResult

cytearc.plotting.mapping_score(store, result, *, reference, target_groups=None, layout=None, kind='embedding', reference_labels=None, size_by_score=False, log_transform=True, multiplier=1000, weighted=True, fixed_weight=0.1, bins=40, point_size=None, color_scale=None, categorical_scale=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot reference-cell mapping scores for one or more query groups.

target_groups names the group of each projected query cell, as a pandas Series indexed by cell ID; values of other cells are left out. kind="box" groups reference cells by reference_labels, a cell column or cell-label artifact of the reference datastore. Reference cells without a usable label are left out of the boxes.

Return type:

PlotResult

cytearc.plotting.marker_heatmap(store, *, marker, topn=5, log_transform=None, vmin=-1, vmax=2, figsize=None, fontsize=10, width_factor=0.03, height_factor=0.02, cmap='magma_r', color_scale=None, row_order=None, column_order=None, cluster_rows=True, cluster_columns=True, cluster_method='ward', cluster_metric='euclidean', row_annotations=None, column_annotations=None, annotation_scales=None, target=None, theme='notebook', show_legend=True, show=True, **heatmap_kwargs)#

Plot standardized expression of the top marker features.

cmap takes a Matplotlib colormap name, a registered Colormap or a list of colors, and a color_scale that names a colormap replaces it.

Return type:

PlotResult

cytearc.plotting.matrixplot(store, *, features, group_by=None, groups=None, cell_key='I', from_assay=None, sample_by=None, study_design=None, normalization=None, expression_cutoff=0.0, value='mean', standardize='none', color_scale=None, feature_order=None, group_order=None, cluster_features=False, cluster_groups=False, cluster_method='average', cluster_metric='euclidean', row_annotations=None, column_annotations=None, annotation_scales=None, categorical_scale=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Heatmap of mean expression or detection fraction by group.

Rows follow the feature input order and columns follow the group order of dotplot(): categorical_scale, or else the order that each grouping column stores, otherwise natural order. Set explicit orders, compared as text, or enable hierarchical clustering independently for either axis; a clustered axis draws its dendrogram beside the matrix. Group ticks show categorical_scale.labels or the stored display labels. value="mean" colors by average expression; value="fraction" colors by the share of measured cells above expression_cutoff. standardize="feature" applies only to means. sample_by has the same equal-sample weighting behavior as dotplot(), and shared feature labels follow the same pooling rule.

As in dotplot(), a mapping of group names to features draws one row per feature and group, so a feature listed under two groups keeps a row in each, and brackets each group’s rows. The matrix table is then indexed by feature_group and feature. Grouped rows keep their groups, so they cannot be clustered. group_by and groups take what dotplot() takes, and title the group axis as dotplot() does.

Return type:

PlotResult

cytearc.plotting.mixscape(store, classes, *, panel='classes', targets=None, max_targets=40, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot the share of each target’s cells that Mixscape calls knocked out, or their scores.

classes is a mixscape_classes artifact of ds.perturbation.mixscape, as ds.perturbation.load_mixscape reads it. Among the cells that carry one target, Mixscape calls each cell knocked out (KO, or the perturbation_type of the classes) or an escaper (NP, not perturbed).

With panel="classes", each target gets one bar, labeled with its name and its cells in every split. The blue part of the bar is the share of its cells called KO and the gray part the share called NP. The bars run from the largest KO share at the top to the smallest, ties broken by name. A target fitted in no split, because it had too few DE genes or KO cells or its fit collapsed, has only NP cells, and the title counts such targets by status. The table "classes" holds one row per drawn target, with target, n_cells, n_ko, n_np and ko_share, in drawing order. Either panel raises ValueError when the classes hold no target.

With panel="scores", each target with a fitted split gets a panel: a histogram of its cells’ scores, their projections onto the target’s perturbation direction, with the KO cells in blue below the NP cells in gray. Two curves show the normal distributions of the fit in the target’s first fitted split: the control component, which keeps the mean and standard deviation of the control cells’ scores, scaled to the NP cells of the histogram, and the perturbed component, scaled to its KO cells. When the classes were split, the histogram pools the target’s fitted splits, and the panel’s title names the split of the curves. A target fitted in no split has no scores and gets no panel; the title counts such targets by status, and the plot raises ValueError when no target is left to draw. The title stands above the panels, or above the first panel’s own title when the plot draws into a caller’s axes, which also holds the legend. A panel’s axes take the target as key. The table "scores" holds one row per drawn cell, indexed by cell ID, with target, split, score, global_class and posterior, in panel order.

targets keeps those targets in that order. Otherwise the plot keeps the max_targets targets with the most cells, fitted targets for panel="scores", ties broken by name, in the order of the bars, and the title says when it leaves any out. When targets names more than max_targets targets, the plot raises ValueError rather than draw a crowded figure. A title counts a target whose splits have different statuses under each status.

Return type:

PlotResult

cytearc.plotting.modality_weights(store, *, graph, layout, point_size=None, point_alpha=1.0, cmap='viridis', n_columns=None, target=None, figsize=None, theme='notebook', frame='minimal', rasterize_threshold=50000, show=True)#

Plot each assay’s WNN contribution over an explicit embedding.

layout must hold the graph’s cells, whichever operation made its cell selection; a layout of other cells raises ValueError. cmap takes a Matplotlib colormap name or a registered Colormap.

Return type:

PlotResult

cytearc.plotting.perturbation_clusters(store, clusters, *, panel='heatmap', perturbations=None, cluster_ids=None, label=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot clusters of perturbations as a heatmap of their profiles or as a map.

clusters is a perturbation_clusters artifact of ds.perturbation.cluster, as ds.perturbation.load_clusters reads it.

With panel="heatmap", the perturbations run in the leaf order of average linkage, from the top down and from the left, and each cell holds the Pearson correlation of two profiles, on a diverging scale from -1 in blue through 0 in white to 1 in red. When the clusters were found by Euclidean distance, each cell holds the distance instead, from 0 in dark blue to the largest drawn distance in white. A bar on the left colors each perturbation by its cluster, gray when HDBSCAN left it unassigned, and numbers each cluster beside the middle of the longest run of its rows; a number that would overlap the number of a longer run is left out. The names of the perturbations run beside the rows and below the columns when the heatmap draws at most 50, and are left out of a larger heatmap, which is too dense to name; perturbations or cluster_ids then draw fewer. The matrix is drawn as one image, so that thousands of perturbations render quickly and save to a small file. The axes take the keys "heatmap", "cluster_bar" and "colorbar". The table "matrix" holds the drawn values with the perturbations in drawing order, and "clusters" holds each drawn cluster’s n_perturbations, the row of its number and whether it is numbered.

With panel="embedding", each perturbation is a point at its place in the clustering’s two-dimensional layout, colored by its cluster, with the unassigned perturbations in gray beneath the others. Each cluster is numbered at the median of its points, and a number that overlaps another moves aside by at most about its height. label names those perturbations: each gets a ring around its point and its name beside it, and a name that would overlap another name or a number moves to the other side, or above or below its point with a thin line to it. The points are rasterized when there are more than 50,000. The axes take the key "embedding". The table "clusters" holds each drawn cluster’s n_perturbations and the median x and y of its points, where its number starts.

A cluster has the same color in both panels and whatever the plot draws. The clusters take eight colors, CyteArc’s colorblind-safe palette without its black, its yellow and its two grayish colors, in the order in which they first appear in the leaf order; the ninth takes the first color again, and its number tells it apart.

perturbations keeps those perturbations, and cluster_ids keeps the perturbations of those clusters, -1 for the unassigned ones; they cannot be combined. The plot raises ValueError when either names a perturbation or a cluster that the clusters lack, and when label names a perturbation that the plot does not draw or comes with panel="heatmap", and when the clusters hold no perturbation. The title counts the drawn perturbations, out of the clustered ones when some are left out, and the drawn clusters and unassigned perturbations. show_legend=False leaves out the colorbar and the cluster numbers. The table "perturbations" holds the drawn rows of the record’s table, indexed by perturbation, in leaf order.

Return type:

PlotResult

cytearc.plotting.phylogeny(store, clones, *, tree=None, max_leaves=100, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot the cell phylogeny that clones were cut from, its clades collapsed to at most max_leaves wedges.

clones are clones cut from a phylogeny by ds.clones.phylogeny_clones, whose phylogeny and cut the figure reads from their provenance. Each tree starts as one wedge, and the clade that holds the most cells opens until max_leaves wedges are drawn: its child of the most cells is drawn alone and its other children as one wedge until they open in turn, so a polytomy opens one child at a time. A clade of the cut is one clone and never opens, nor does a leaf that ends before the cut, so where the trees hold no more of these than max_leaves, every clone is drawn alone. A clade is drawn from its first branching, and leaves that name no cell of the phylogeny’s selection are left out.

The trees run from their roots at the left, each wedge as tall as its cells and stacked from the top, the most cells first. A wedge whose cells are all in one clone takes that clone’s color, by its rank among the cut’s clones, from 56 colors far from gray and from each other, which repeat from the 57th clone; a wedge whose cells all end before the cut, in no clone, takes the missing gray; and every other wedge, of several clones or of a clone and cells before the cut, is gray, “Mixed” in the legend, and says how many clones it holds where it is tall enough, at least a fortieth of the height. The x axis is time for a cut at a time and branchings below the root, single-child nodes merged, for a cut at a depth, with the cut as a dashed line. A forest of more trees than max_leaves draws its largest trees and the others as one gray wedge that says how many trees it holds; tree draws one tree alone. The legend lists the grays drawn and then, the largest first, the clones whose wedges are at least a fortieth of the height, or the largest clone drawn when none is, and its title says how many of the grays and clones drawn it lists when it leaves some out.

Tables: nodes, one row per node or group drawn, in drawing order: tree, node (its position in its tree, as the phylogeny’s nodes table numbers them; -1 for a group of sibling clades or trees), parent (the row it hangs from, -1 for none), wedge (whether it is drawn collapsed), n_cells, n_clones, clone and label (its one clone’s ID and the text drawn, None for none or several), n_clades (the clades that a group holds, 1 otherwise), n_trees, x (its time or depth, a group’s earliest clade’s), start (where its branch starts), end (its latest leaf), and y, low and high, its middle and extent in cells from the top.

Raises:
  • TypeError – If clones is not an ArtifactRef, tree is not text, max_leaves is not an integer, another argument has the wrong type, or the store does not draw phylogenies.

  • ValueError – If clones were not cut from a phylogeny, max_leaves is below 1, or tree names no tree of the phylogeny or one whose leaves name no cell.

  • KeyError – If the store does not hold the clones or their phylogeny.

  • RuntimeError – If the clones or their phylogeny are incomplete.

  • MemoryError – If reading the phylogeny, collapsing it or drawing it does not fit the memory budget.

Return type:

PlotResult

cytearc.plotting.pseudotime_heatmap(store, *, aggregation, show_features=None, feature_order=None, feature_cluster_order=None, figsize=(5, 10), vmin=-2.0, vmax=2.0, heatmap_cmap=None, pseudotime_cmap=None, clusterbar_cmap=None, color_scale=None, feature_cluster_scale=None, pseudotime_scale=None, tick_fontsize=10, axis_fontsize=12, feature_label_fontsize=12, target=None, theme='notebook', show_legend=True, show=True)#

Plot binned feature dynamics ordered by pseudotime.

show_features labels rows of the heatmap. A name matches the retained features case-insensitively and keeps the caller’s spelling, and a FeatureRef finds a feature by name, ID, or index and shows its label, or its name, followed by its ID where another row has that name. A name that several retained features share raises ValueError naming their IDs; pick one with FeatureRef(value=feature_id, by="id"). A feature that the aggregation did not retain is skipped.

Without feature_cluster_scale, the strip beside the rows colors the modules from the colorblind palette in module order, as lineage_heatmap does, and more than 12 modules take evenly spaced hues, with a warning; a clusterbar_cmap is sampled at evenly spaced positions instead. heatmap_cmap colors the profiles, coolwarm by default, and pseudotime_cmap the pseudotime strip, viridis by default, unless color_scale or pseudotime_scale names a colormap. Each colormap argument takes a Matplotlib colormap name or a registered Colormap.

Return type:

PlotResult

cytearc.plotting.qc(data, color='steelblue', cmap='tab20', figsize=None, label_size=10.0, title_size=10, sup_title=None, sup_title_size=12, scatter_size=1.0, max_points=10000, seed=0, show_on_single_row=True, show=True, theme='notebook', group_title=None)#

Plot grouped distributions for cell-level QC metrics.

Above max_points cells, each panel draws the points it shows with seed, a seed of NumPy’s RandomState from 0 to 2**32 - 1. The groups take the colors of cmap, a palette that seaborn’s color_palette reads: the name of a seaborn palette or a Matplotlib colormap, or a list of colors. group_title names what the groups of the groups column are, such as “Sample”: it titles each panel’s axis of the groups and the legend that PlotResult.legends reports. Without it the axis is left blank and the legend is reported as groups, the column’s name; a panel of one group draws no axis of groups to title.

data is a pandas DataFrame with a groups column and one numeric column per metric. The groups of an ordered Categorical follow its categories, as the groups of a column stored as ordered do in the other plots, and the cells without a group come after them, as NA; other groups take natural order.

Return type:

PlotResult

cytearc.plotting.receptor_qc(store, receptors, *, group_by=None, groups=None, normalize=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot the receptor types, chain pairings and chains per cell of imported receptors.

receptors is an immune_receptors artifact, such as one from ds.repertoire.import_receptors. The first panel counts cells by receptor type (TCR, BCR, ambiguous, multichain, no IR), the second by chain pairing, and the third counts cells by their number of chains of each arm, VJ (TRA, TRG, IGK, IGL) and VDJ (TRB, TRD, IGH), side by side, with three or more in the last bar. Many "orphan VDJ" or "orphan VJ" cells point to chains lost in capture, and many "multichain" or "ambiguous" cells to doublets. The panels stand in one column, the categories that hold cells in the colors of their vocabulary.

group_by names cell metadata columns, one or several, such as the sample, and groups a cell-label artifact, such as a clustering; the groups are the combinations of their labels, as the clone summaries group cells, named by their labels joined by commas. With a grouping, the first two panels draw one bar per group, stacked by category, the first on top as its legend lists them, of the fraction of the group’s cells by default (normalize), and cells without a group are left out. The groups follow the order that their columns or label artifact store, then natural order, and the lower of the two panels titles its axis of groups by the grouping: the columns’ names, a NamedCellArtifact as groups by its name, or else the title of the artifact’s record. A label artifact may hold fewer cells than the receptors.

Tables: receptor_type and chain_pairing, one row per group and category, zeros included (group, the category in a column named like the table, n_cells), with every cell in the group "all cells" without a grouping, so a group may take any name; and chains_per_cell (cells per number of chains of each arm, indexed by n_chains).

Raises:
  • TypeError – If an argument has the wrong type, or the store does not load immune receptors or group cells for figures.

  • ValueError – If receptors is not an immune_receptors artifact, a group_by column is missing or named twice, two groups get one name, or no cell, or no cell with a group, is left to draw.

  • KeyError – If the store holds no such artifact.

  • RuntimeError – If an artifact is incomplete, as a call that stopped before it finished leaves it.

  • MemoryError – If reading the artifact or grouping the cells does not fit the memory budget.

Return type:

PlotResult

cytearc.plotting.recorder_states(store, alleles, *, max_sites=40, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot the fraction of cells that each recorder site reads as each state.

alleles is a lineage_alleles artifact, such as one from ds.clones.import_alleles. Each bar is a site of an integration, named {integration}-{site}, stacked by the fraction of the site’s cells that hold a mark, an unknown mark, an unedited site, or no read, the first on top as the legend lists them. A site’s cells are the cells with an allele record, the cells the recorder reached, of which those whose integration lacks the site are left out; a cell that holds several alleles at a site counts once, in its first state in the order above. Sites in natural order; with more than max_sites, 40 by default, the most sites an axis names, the max_sites sites read in the most cells are drawn, the title says how many of how many, and the table keeps every site. Sites that are mostly missing were rarely captured, and sites that are mostly unedited carry little lineage.

Tables: site_states (integration, site, state, n_cells, share), one row per site and state, the record’s site_states() with each share.

Raises:
  • TypeError – If an argument has the wrong type, or the store does not load lineage alleles.

  • ValueError – If alleles is not a lineage_alleles artifact, or holds no allele record.

  • KeyError – If the store holds no such artifact.

  • RuntimeError – If an artifact is incomplete, as a call that stopped before it finished leaves it.

  • MemoryError – If reading the artifact does not fit the memory budget.

Return type:

PlotResult

cytearc.plotting.run_recipe(store, recipe, *, artifacts=None, targets=None, output_dir=None, show=False, continue_on_error=False)#

Run a plotting recipe’s steps in order after any analysis has completed.

With show=True, a figure that a step creates is shown when the step has drawn it, and closed. A figure of the caller’s that steps draw on through targets, in its subfigures too, is shown once, after the last step, in the order of the first step that drew it, so a figure whose panels several steps fill is shown complete, and the warnings that showing it raises are recorded under each step that drew it. A step writes its file from its figure as it stands after the step, so give a figure that several steps fill its output_filename, or outputFilename in a recipe file, on the last of them. Plots do not display themselves otherwise.

A step that raises stops the recipe, after the caller’s figures that the steps before it drew are shown, unless continue_on_error records the error under the step’s name in failures and runs the other steps. A figure that fails to show fails its step, or every step that drew a figure of the caller’s: the error stops the recipe, or with continue_on_error is recorded in failures, and outputs leaves those steps out.

Return type:

PlotRecipeResult

cytearc.plotting.spectratype(store, spectratype, *, groups=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot the junction lengths of groups of cells, one panel per locus.

spectratype is the result of ds.repertoire.spectratype, which sets the groups, the sequence, the slots and what is counted. Each panel draws, for one locus, each group’s fraction of chains at each junction length, one line per group in its color, or bars in the locus’s color for one group. The panels stand three to a row, with one legend of the groups, titled by the grouping, beside the first row. With count="clonotypes" the fractions count clonotypes, or clonotype clusters for clonotypes that a distance metric linked. The plot raises ValueError when no chain has a junction.

groups, a NamedCellArtifact of the label artifact that the record groups by, titles the artifact by its name; without it, the figure takes the title of the artifact’s record.

Tables: spectratype, the record’s rows.

Raises:
  • TypeError – If spectratype is not a Spectratype record, or another argument has the wrong type, or the store does not give the labels that the groups’ colors range over.

  • ValueError – If no chain has a junction.

  • KeyError – If the store does not hold the clonotypes that spectratype counts.

  • RuntimeError – If those clonotypes are incomplete, as a call that stopped before it finished leaves them.

  • MemoryError – If reading the labels that the groups’ colors range over does not fit the memory budget.

Return type:

PlotResult

cytearc.plotting.theme_context(name='notebook')#

Apply a CyteArc theme’s rcParams inside the context and restore them on exit.

Matplotlib’s interactive mode is the exception: it stays as the body of the context leaves it. Jupyter’s inline backend turns interactive mode on when it loads, which happens when the session draws its first figure, so a session whose first figure is a CyteArc plot stays interactive. A call of plt.ion() or plt.ioff() in the body also lasts beyond the context.

Return type:

Iterator[None]

cytearc.plotting.variant_depth(store, counts, *, group_by=None, groups=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot the depth of variant counts at each site and in each cell.

counts is a variant_counts artifact, such as one from ds.variants.import_counts. The first panel draws each site’s mean depth over the cells that the files name, along the contig for sites with coordinates, such as the mitochondrial genome, one line per contig, and as bars for named sites, such as GoT targets or GIFT probes; a site that no cell covers is left out of the log scale. The second panel draws how many cells have each mean depth over the sites, on log bins, leaving out cells of no depth: cells with little depth give little evidence about their variants. The panels stand in one column at the page width.

group_by names cell metadata columns, one or several, such as the sample, and groups a cell-label artifact; the groups are the combinations of their labels, as the clone summaries group cells, named by their labels joined by commas, and a NamedCellArtifact as groups titles the artifact by its name. With a grouping, the second panel draws one histogram per group in the group’s color, under a legend titled by the grouping, and says so when no cell of a group has depth. Cells without a group, and cells that no file names, are left out of it.

Tables: sites (site, contig, position, mean_depth, covered_fraction) and cells (ids, group, mean_depth, n_covered_sites).

Raises:
  • TypeError – If an argument has the wrong type, or the store does not load variant counts or group cells for figures.

  • ValueError – If no file names a cell, no site has depth, no named cell has a group, a group_by column is missing or named twice, two groups get one name, or the counts hold both sites with coordinates and named sites.

  • KeyError – If the store holds no such artifact.

  • RuntimeError – If an artifact is incomplete, as a call that stopped before it finished leaves it.

  • MemoryError – If reading the artifact or grouping the cells does not fit the memory budget.

Return type:

PlotResult

cytearc.plotting.variant_statistics(store, variants, *, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#

Plot each variant’s VMR against its strand correlation.

variants is a variant_selection artifact from ds.variants.informative. Each point is a variant that some cell shows: the Pearson correlation of its forward and reverse counts across cells, against the ratio of the variance of its allele frequency to its mean, on a log scale, as mgatk draws it. Sequencing errors sit on one strand and spread evenly across cells, so informative variants sit at the top right. Informative variants take a color, the others the muted gray, masked ones drawn as crosses, under a legend of the kinds drawn, and the selection’s VMR and strand correlation thresholds are drawn as dotted lines. A variant without a strand correlation, such as one that a single cell shows, is left out; for counts without strands, the x axis is the mean depth at the site instead.

Tables: variants (variant, vmr, strand_correlation, mean_coverage, masked, informative).

Raises:
  • TypeError – If an argument has the wrong type, or the store does not load variant selections.

  • ValueError – If variants is not a variant_selection artifact, or no variant has a value on the x axis.

Return type:

PlotResult

class cytearc.plotting.PlotResult(figure, axes, tables, legends, scales, provenance, owns_figure, theme='notebook')#

Return value from cytearc.plotting functions.

figure is the matplotlib figure. axes maps panel keys to axes. tables holds any summary data used to build the plot. owns_figure is True when CyteArc created the figure. close() closes an owned figure in pyplot and keeps the result metadata.

In IPython, show() displays the figure and then closes it in pyplot, as plt.show() does in Jupyter, so the end of the cell does not draw it a second time. This holds for every figure, a figure passed with target= or composed with compose_results() included. Outside IPython, show() hands an interactive canvas to plt.show() and closes only an owned figure. A closed figure can still be saved or drawn on. In Jupyter, result.show() and display of the figure, result.figure, show it with everything drawn on it, and plt.show() does not. A plot drawn into the axes of a SubFigure keeps the subfigure as figure: show(), close(), save() and save_provenance() act on the whole figure that holds it, result.figure.figure, which is the figure to display.

save(path, *, dpi=None, transparent=False, exact_size=True, tiff_compression='tiff_lzw', provenance_sidecar=False)#

Write the figure to disk (PNG, PDF, SVG, TIFF, and other backends).

The default background is opaque white for light themes and charcoal for the dark theme. Pass transparent=True when the destination supplies its own background. exact_size=True keeps the inch size you set when the figure was created; set it to False only when you want a tight crop for display. provenance_sidecar=True writes a sibling JSON file with the plot metadata, and a path writes it there.

Raises:
  • TypeError – If transparent or exact_size is not a boolean, or provenance_sidecar is neither a boolean nor a path.

  • ValueError – If the path has no extension or a format the canvas cannot write, dpi is not positive, or the sidecar’s path is the figure’s.

Return type:

Path

save_provenance(path, *, figure_path=None, dpi=None)#

Write a JSON file describing scales, legends, and cell counts.

Return type:

Path

class cytearc.plotting.FeatureRef(value, assay=None, by='name', label=None, reduction=None)#

Reference to one assay feature.

Parameters:
  • value (str | int) – Feature name, id, or physical index (see by).

  • assay (str | None) – Assay name. Defaults to the store default assay when omitted.

  • by (Literal['name', 'id', 'index']) – How to look up value: name, id, or index.

  • label (str | None) – Optional display label.

  • reduction (Optional[Literal['mean', 'sum']]) – Required when multiple features match; mean or sum.

class cytearc.plotting.CellField(key, kind='auto', label=None)#

Point color_by or similar arguments at a cell-metadata column.

Use this when the column name alone is ambiguous. kind="categorical" forces discrete colors (useful for integer cluster ids). kind="continuous" forces a colorbar. kind="auto" chooses from the dtype and number of unique values.

class cytearc.plotting.NamedCellArtifact(name, artifact)#

One semantic name bound to an exact cell-aligned artifact.

Plots take it wherever they take a label artifact and title the artifact by name in panels, axes and legends, as CellField.label titles a live column. QC filtering names its artifact metrics by it. The name never enters a summary, a grouping or an artifact’s identity.

class cytearc.plotting.StudyDesign(sample_by, condition_by=None, subject_by=None, pair_by=None, technical_replicate_by=None, technical_replicate_reduction=None)#

Describe samples and conditions for composition and summary plots.

sample_by is the column that identifies biological samples. condition_by is the experimental condition (for example treatment). For paired composition plots, also set subject_by or pair_by so the same donor or pair can be connected across conditions.

class cytearc.plotting.NormalizationSpec(source='assay', transform='none')#

How feature values are read for gene-colored plots.

source="assay" uses the assay’s current normalization settings. source="raw" reads the assay’s stored values: its raw counts, or the values of an assay imported from normalized values. transform="log1p" applies log1p after that fetch, which is the usual choice for gene UMAPs and dotplots when you want a compressed expression scale. With source="assay" it needs a normalizer that supports log_transform.

class cytearc.plotting.ColorScale(cmap=None, vmin=None, vmax=None, vcenter=None, quantiles=None, missing_color='#bdbdbd', scope='feature', scale='linear')#

Continuous color mapping for embeddings and summary plots.

Set vmin / vmax for fixed limits, or quantiles=(low, high) to ignore extreme tails (for example (0.0, 0.99) clips the top 1%). vcenter is for diverging maps such as scaled fold changes. scope controls whether limits are computed per feature (default), per panel, or shared across every continuous panel in the figure. cmap names a colormap that matplotlib.colormaps holds, or leaves the plot’s default; a Colormap of your own serves once matplotlib.colormaps.register holds it under a name of its own. A plot refuses any other cmap before it reads the store.

class cytearc.plotting.CategoricalScale(order=None, palette=None, labels=None, missing_color=None, missing_label=None, palette_name=None)#

Category order, colors and labels for discrete embeddings and compositions.

order sets legend and axis order; a category that a plot shows and order leaves out raises an error. palette maps each category to a color string; a category that a plot shows and palette leaves out raises an error, so pass a complete map when you customize colors. labels maps categories to the text that ticks and legends show. palette_name picks the generated colors, "default" or "colorblind". missing_color and missing_label draw and name cells without a category.

A column’s stored display, or the order of a column stored as ordered, gives the values of the fields this scale leaves unset: labels alone renames categories in their stored order and colors, order alone keeps the stored colors, and palette alone keeps the stored order. labels merge with the stored labels category by category. A palette_name replaces the stored colors and keeps the stored order. Categories that the stored order leaves out follow it in natural order, each in the generated color of its place. Fields still unset when a plot is drawn take the defaults: the natural order of the categories, colors of the "default" palette, each category’s own text, "#bdbdbd" and "NA".

class cytearc.plotting.SizeScale(vmin=0.0, vmax=1.0, size_min=10.0, size_max=200.0)#

Maps numeric values to marker area. Detection fraction uses domain [0, 1].

class cytearc.plotting.DensityOverlay(kind='line', statistic='density', pixels=160, sigma=2.0, min_support=0.25, levels=5, max_hotspots=None, group_by=None, groups=None, color=None, cmap=None, alpha=0.75, linewidth=0.8, halo_color=None, halo_width=0.0, zorder=4.0)#

Contours drawn over an embedding.

group_by and groups optionally restrict the cells used to estimate the surface without changing the cells displayed underneath. statistic="mean" contours a smoothed local mean of the continuous panel values and attenuates pixels with less than min_support effective support. max_hotspots can retain only the strongest connected regions at the lowest contour level. cmap names a Matplotlib colormap that colors the contour levels, as a ColorScale names one; without it every level takes color.

class cytearc.plotting.Highlight(by=None, groups=None, indices=None, color='#d62728', dim_alpha=0.12, alpha=1.0, size_multiplier=1.5, halo_color=None, halo_width=0.8)#

Emphasize a metadata selection while retaining surrounding context.

class cytearc.plotting.PlotRecipe(steps)#

An ordered collection of plotting steps.

class cytearc.plotting.PlotStep(name, plot, kwargs=<factory>, artifact_kwargs=<factory>, target=None, output=None, output_filename=None)#

One named plotting call in a recipe.

class cytearc.plotting.PlotPanelTarget(panel)#

Reference an axes supplied to the recipe runner by panel name.

class cytearc.plotting.PlotOutputSettings(filename, dpi=None, transparent=False, exact_size=True)#

Per-step export settings resolved below the runner output directory.

class cytearc.plotting.PlotOutput(name, result, path=None)#

The successful result of one recipe step.

class cytearc.plotting.PlotRecipeResult(outputs=(), written_paths=(), warnings=(), failures=<factory>)#

Results and diagnostics from a recipe execution.

class cytearc.plotting.PlotProvenance(cytearc_version=<factory>, assay=None, cell_key=None, n_cells=0, n_samples=None, renderer='matplotlib', notes=(), extras=<factory>)#
class cytearc.plotting.LegendSpec(kind, label=None, extras=<factory>)#

Description of a legend or colorbar attached to a plot.

cytearc.plotting.THEMES#

Registry of built-in plotting theme definitions.