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_bytakes one item or a list, drawn as one panel each. A string orCellFieldnames a frozen run cell field fromrun.cells.columns, such asclusters,doublet_score, a multimodal run’sweight_<assay>modality weights, or a column frozen withsnapshot_columns. AnArtifactRefmust be an output of the run, such as one of its Leiden candidates inrun["leiden"], whichds.artifacts.find("clusters", graph=run["connectivity_map"], method="leiden", resolution=1.0)also finds. Any other ref raisesValueError; color by it with the granularlayout=run["umap"]route instead.facet_by, as a string orCellField,subset_by,Highlight(by=...)andDensityOverlay(group_by=...)name frozen run cell fields. A name that is neither a frozen field nor, forcolor_by, a gene raisesKeyErrorlisting the run’s cell fields.A gene name or
FeatureRefreads 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 explicitnormalization=NormalizationSpec(...), which provenance records; without one it raisesValueError.cell_keyother than"I", afrom_assayother than the run’s assay, andpoint_sizesraiseValueError. For per-cell sizes, passlayout=run["umap"]withpoint_sizesas 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 |
|
dot or matrix plot |
|
composition |
|
distribution |
|
cluster connectivity |
|
modality weights |
|
Paris hierarchy |
|
marker heatmap |
|
pseudotime heatmap |
|
lineage heatmap and trends |
|
lineage curves |
|
lineage tree |
|
mapping score |
|
label-transfer evidence, confusion, and calibration |
|
guide calls of a CRISPR screen |
|
fitted guide thresholds of a CRISPR screen |
|
perturbation efficiency of a CRISPR screen |
|
E-distance of each perturbation from the control cells |
|
Mixscape’s knocked-out and escaping cells of each target |
|
fold change and p-value of each tested pair of a target and a gene |
|
calibration of the association tests on negative controls, and their power on positive controls |
|
clusters of perturbations by their profiles |
|
clones per clone size and the largest clones, of clones or clonotypes |
|
expansion categories and the clonal space of each group of cells |
|
rarefaction and extrapolation curves of the Hill numbers of each group |
|
diversity indices of each group, one panel of bars per index |
|
clones shared between samples or cell types |
|
chosen clones across time points or cell types |
|
fate coupling of every pair of groups with the tree of their order |
|
each clone’s late cells by fate, by dominant fate |
|
barcodes per cell, UMIs per barcode and reads per molecule of imported lineage barcodes |
|
the fraction of cells that each site of a lineage recorder reads as marked, unknown, unedited or missing |
|
a cell phylogeny with the clones cut from it, its clades collapsed to at most 100 wedges |
|
receptor types, chain pairings and chains per cell of imported immune receptors |
|
V, D, J or constant gene usage of each locus |
|
V-J gene pairing of each locus |
|
junction lengths of each locus |
|
depth of variant counts at each site and in each cell |
|
each variant’s variance-mean ratio against its strand correlation, informative variants marked |
|
each cell’s allele frequency of each informative variant, uncovered entries apart |
|
the fraction of cells with each genotype call at each site, by group, and the calls of one site on an embedding |
|
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, besidelabel, 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
matrixofclone_overlap; a summary’s own tables keep the summary’s order, andclone_couplingplaces 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 asunknown_markorwild_type. The libraries of lineage barcodes take colors over every library of their artifact.Heatmaps.
clone_overlapandclone_couplingtakecolor_scale, aColorScalethat 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 ofgene_usageandgene_pairingshare one color bar, from 0 to the largest fraction of any locus, so a color means one fraction in every panel, andallele_frequenciescolors 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
genotypesone 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 ofclonal_expansion, below the matrix ofclone_overlapandclone_coupling, inclone_tracking, in the group axes ofgene_usage, in the lower grouped panel ofreceptor_qc, and beside the bars ofgenotypes, which are named by site and group and titled as “Site” followed by the grouping;clonal_diversitynames 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 inPlotResult.legendswith its scale inPlotResult.scales, withshow_legend=Falsetoo, socompose_resultsdraws 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 ofclonal_diversitywhose index is defined for no group, one ofbarcode_callsthat no library fills or the cells panel ofvariant_depthwhose grouped cells have no depth, says so.Provenance.
notesholds the plot’s name, andextrasholds the reference of each artifact drawn:clonesin the figures of clones, any other artifact that the figure takes under its argument’s name, such asexpansion,bias,receptors,barcodes,alleles,counts,variantsorgenotypes, andsource, the receptors or clonotypes that gene usage and junction lengths count. It holds the settings under their names, and thegroupingof 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.
variantsis avariant_selectionartifact fromds.variants.informative; its informative variants are the rows, in their order along the genome, and cells are the columns, colored from 0 to 1. Withclones, such as one fromds.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 mostmax_cellscells 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) andcells(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
variantsis not avariant_selectionartifact, the selection has no informative variant, or no cell has a clone.
- Return type:
- 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.
testsis aperturbation_associationsartifact ofds.perturbation.associations, asds.perturbation.load_associationsreads 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 withset,target,feature,p_valueandexpected, the uniform quantile i / (n + 1);"band"holds the band’srank,expected,lowerandupperp-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’sbin_start,bin_stopandpairs; and"controls"holds the drawn controls withset,target,featureandp_value.- Return type:
- 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.
testsis aperturbation_associationsartifact ofds.perturbation.associations, asds.perturbation.load_associationsreads 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_toppairs with the smallest p-values, ties broken by the larger size ofzand then by target and gene, are labeledtarget:feature_namebeside their points, with the gene’s name from the record’sfeature_namecolumn, andlabel_top=0labels 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.targetskeeps 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 firstlabel_toprows are the labeled pairs.- Return type:
- 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.
barcodesis alineage_barcodesartifact, such as one fromds.clones.import_barcodes. The three panels show what clone calling filters: the cells by their number of distinct barcodes, cells without a barcode included, withmax_barcodes_per_cellor 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) andreads_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
barcodesis not alineage_barcodesartifact, 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:
- 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.
diversityis the result ofds.clones.diversity, which sets the groups.indicesnames one or several columns of itsindicestable, 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’shilltable holds.groups, aNamedCellArtifactof 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’sgroup_keysholds each group’s labels.- Raises:
TypeError – If
diversityis not aClonalDiversityrecord, 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
indicesis empty, names an index twice or one thatds.clones.diversitydoes not measure, or the record holds no group, or no group of it has a value of any index named.KeyError – If
themenames 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:
- 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.
expansionis aclonal_expansionartifact, such as one fromds.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’ssummarize_clonal_expansionand scRepertoire’sclonalHomeostasisdo. 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’sclonalProportiondoes: 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_bynames cell metadata columns, one or several, such as the cell type, orgroupsa 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, aNamedCellArtifactasgroupsby 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, thenn_cellsorn_clones, andfraction) andrank_windows(group,window,n_cellsandfraction).- Raises:
TypeError – If an argument has the wrong type, or the store does not load, group or name clones for figures.
ValueError – If
expansionis not aclonal_expansionartifact,countis neither"cells"nor"clones", agroup_bycolumn 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:
- 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.
rarefactionis the result ofds.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’sggiNEXTdraws them: one line per group, solid where the group is rarefied, dashed where it is extrapolated, and a point at its observed size. Withbase="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, aNamedCellArtifactof 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’sgroup_keysholds each group’s labels.- Raises:
TypeError – If
rarefactionis not aRarefactionrecord, 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
baseis neither"size"nor"coverage", or the record holds no curve.KeyError – If
themenames 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:
- 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.
clonesis a clone artifact, such as one fromds.clones.import_clonesords.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 themax_clonesclones with the most cells, labeled with their IDs. Clonotypes are labeled instead by the junction amino acids of their representative cell’sVDJ_1chain, or of itsVJ_1chain without a VDJ chain, such asCASSLGQAYEQYF, and those defined byreceptor_arms="VJ"by theVJ_1chain 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 asCAVA 1andCAVA 3. The figure names the clones as their artifact does, so for clonotypes the second panel’s title readsLargest 20 clonotypes, and for clonotype clusters, which a distance metric defines,Largest 20 clonotype clusters.group_bynames cell metadata columns, one or several, such as the sample or time point, andgroupsa 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. ANamedCellArtifactasgroupstitles 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 asCASSB (TCR 2).Tables:
sizes(group,clone_size,n_clones) andtop, 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
clonesis not a clone artifact, agroup_bycolumn 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:
- 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.
couplingis the result ofds.clones.coupling.valueis"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_scalesets 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, aNamedCellArtifactof 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) andpairs.- Raises:
TypeError – If
couplingis not aCloneCouplingrecord,color_scaleis not aColorScale, another argument has the wrong type, or the store does not name clones for figures.ValueError – If
valueis 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
themenames no theme,color_scalenames 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:
- 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.
biasis aclone_fate_biasartifact, such as one fromds.clones.fate_bias. The plot draws themax_clonesclones 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 withnormalize=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 asclone_abundancelabels them: by their IDs, and clonotypes by their representative’s junction, with their number where two drawn share one.groups, aNamedCellArtifactof 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), andfates, 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
biasis not aclone_fate_biasartifact, 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:
- 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.
overlapis the result ofds.clones.overlap, which sets the groups.indexis 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; thematrixtable holds each group’s clones on its diagonal for"shared"and 1 otherwise.color_scalesets 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, aNamedCellArtifactof 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) andpairs, the record’s pairs.- Raises:
TypeError – If
overlapis not aCloneOverlaprecord,color_scaleis not aColorScale, another argument has the wrong type, or the store does not name clones for figures.ValueError – If
indexis not an overlap index, or the record compares no pair.KeyError – If
themenames no theme,color_scalenames 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:
- 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.
trackingis the result ofds.clones.track, which chooses the clones and sets the groups: thetop_nclones 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 asCASSA, and also its number where two of the clonotypes followed share a junction, such asCASSA 1andCASSA 3, asclone_abundancelabels the largest clones. Groups are placed by their labels in thegroup_bycolumns and thegroupsartifact, joined by commas;orderlists 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, aNamedCellArtifactof the label artifact that the record groups by, or else the title of the artifact’s record.Tables:
tracking, the record’stablewith each clone’slabelafter itsclone(clone,label,group,n_cellsandfraction); the record’sgroup_keysholds each group’s labels.- Raises:
TypeError – If
trackingis not aCloneTrackingrecord,orderis 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
orderdoes 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:
- 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.
rawWeightis the sum of intercluster weights after reciprocal sparse graph entries are counted once.normalizedWeightdivides that value bysqrt(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.connectivityreturns these weights as tables without drawing a figure.layoutmust hold the graph’s cells, whichever operation made its cell selection.groupsare 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, raiseValueError. ANamedCellArtifactasgroupstitles the groups’ legend by its name; a bare artifact takes the title of its record.group_bynames a live column as text or as aCellField, whose label titles the legend in place of the column’s name.- Return type:
- 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_valuecolumn, take the colors that an embedding colored by them takes: the categories and colors that the column or the clustering stores, such as theunscolors that an H5AD import keeps, or else default colors assigned over every label of the column in natural order.color_keynames a color for each category, andcmap, a Matplotlib colormap name or a registeredColormap, is sampled at evenly spaced positions over the categories instead. A numeric fill takescmap, viridis by default.- Return type:
- 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
axesholds 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:
- 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. Withsample_by, there is one bar per sample; without it, one bar for the whole dataset.groupingis the immutable artifact counterpart tosample_byfor analytical groupings such as clusters. It is available only for stacked composition. Besidecategories, its labels are read for the cells ofcategories, 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 raisesValueError. ANamedCellArtifactascategoriesorgroupingtitles the legend or the bar axis by its name; a bare artifact takes the title of its record. The cell columns ofcategory_by,sample_by,subject_by,pair_byandcondition_byare named as text or as aCellField. 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”; aCellField’s label titles them instead. The bars follow the order thatsample_byorgroupingstores, as a stored display or ordered categories, and natural order without one.kind="per_sample"draws one point per sample in each category (requiressample_byor aStudyDesign).For paired before/after designs, pass
condition_bytogether withsubject_byorpair_by(directly or viastudy_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 thatcondition_bystores, 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. Useuncertaintyto select standard deviation, standard error, or no interval.Figure width is capped so large category lists stay page-sized.
- Return type:
- 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.
keysmay be cell-metadata columns (for exampleRNA_nCounts), gene names, or one exactcell_cycleartifact. The artifact form plots its canonicals_scoreandg2m_scorearrays.kindselects the display:"violin","box","hist", or"ecdf". With Withgrouping, each category gets its own distribution along the x-axis and a distinct color. ACellFieldlabel or aNamedCellArtifactname 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 valuessubset_by: boolean metadata column; keepTruecellsgroups: keep or order grouping categories
For violins and boxes, CyteArc can overlay a subsample of cells as points.
max_pointslimits how many points are drawn (0disables points). The public default is10000for compatibility. ExplicitNoneuses a kind-specific behavior: no overlay for stacked violins and10000for 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 unlessshare_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_pointsvalues estimates its density, and draws its quartiles, from a seeded randommax_density_pointsof them that keeps its smallest and largest value, which bounds the cost on large datasets;Noneuses every value. Smaller violins use every value, andprovenance.notesgains"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
groupsorsubset_byselect. Tick and legend labels followCategoricalScale.labels, fromcategorical_scale,split_scale, or the column’s stored display.Set
sample_byorstudy_designto summarize cells within biological samples before plotting. A study design’ssubject_byorpair_bycolumn is used only with paired Wilcoxonstats_results, matchingrun_statistical_testing.split_bydraws two violin halves for a second categorical variable.split_byandsample_byname cell columns as text or as aCellField, whose label titles the legend of the split in place of the column’s name.Pass
stats_results(a singleStatisticalTestResult, 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 prefersp_value_adjustedwhen present. Nothing is recomputed here. Results must carry the selection, grouping, tested-value, assay, sample-design, and normalization identity recorded byrun_statistical_testing; incompatible or incomplete results are skipped with a warning. Statistical overlays cannot be combined withsplit_by.For
kind="stacked_violin", passcolor_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 aColorScaleto control the mapping:cmapchooses the colormap,vmin/vmaxfix explicit limits,quantilesclips extreme means, andvcenterenables diverging maps. The color scale followsshare_y:scope="shared"whenshare_y=Trueandscope="panel"otherwise.ColorScale’s generalscope="feature"default is treated as automatic here; explicit"shared"or"panel"overrides it. Ascope="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 throughPlotResult.legends.color_by="mean"cannot be combined withsplit_by.- Raises:
ValueError – If a gene’s assay measured none of the plotted cells.
- Return type:
- 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. Passfeaturesas 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 explicitFeatureRef.labelare 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 aCellField, or withstudy_design.sample_by, each sample contributes equally: CyteArc first summarizes within sample, then averages across samples. Without it, every cell contributes equally.group_bynames one cell column or two, each as text or aCellField. Groups followgroup_order, or the order ofcategorical_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_bycolumns, aCellField’s label or else its key, joined by “ / “, or by the name of aNamedCellArtifactasgroups, or else by the title of the label artifact’s record.- Return type:
- 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.
edistanceis aperturbation_edistanceartifact ofds.perturbation.edistance, asds.perturbation.load_edistancereads 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 ratealpha, its adjusted p-value at mostalpha, 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_rowsrows were tested, the plot keeps themax_rowsrows 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:
- 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.
efficiencyis aperturbation_efficiencyartifact ofds.perturbation.efficiency, asds.perturbation.load_efficiencyreads 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 ratealpha, its adjusted p-value at mostalpha, 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_rowsrows were tested, the plot keeps themax_rowsrows 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:
- 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
dimscounts them, so the elbow line stands at the number of the PC where the curve bends. Thevariance_explainedtable holdspc,variance_explainedandis_elbowfor each PC, andprovenance.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 infigsize, the figure is a quarter inch wide for each PC and at least 2.25 inches wide.- Return type:
- 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_byaccepts a cell-metadata column, a gene name, or a list of either. With several genes, CyteArc draws one panel per gene. Withfacet_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 (NAby default). Facets followgroupsorfacet_order, or else the order that the facet column stores, as a stored display or ordered categories, and natural order without one.facet_bynames the column as text or as aCellField, whose label names the column in each facet’s title, such asStage=early, and refuses another value orkind="continuous". Color limits for a gene are shared across facets so panels stay comparable. Multiplelayout_keyvalues produce the cartesian product of layouts and colors in one figure, one layout per row of panels.Common choices:
subset_by: keep cells markedTruein a boolean metadata column.groups: keep only these categories. Applies tofacet_bywhen set, otherwise to the first categoricalcolor_bycolumn. Also sets legend order whencategorical_scale.orderis 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 asNoneto size markers from the cell count. Pass a number (matplotlib marker area) orpoint_sizesfor 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;Truesorts every continuous color andFalsenone.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 innumpy.random.default_rng(seed).permutation(n)over thencells of the layout, so the order is reproducible and the same in every panel.Nonedraws 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 example0.01for the 1st to 99th percentile.theme:"notebook"or"paper"for white figures;"dark"for dark notebook themes.
An artifact in
color_bytakes an embedding artifact aslayout, and its cells must include the layout’s.NamedCellArtifact(name, artifact)titles its panel and legend, and keys its panel, byname; 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’sanalysis_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_scaleorder or palette sets them instead, and animmune_receptorsartifact draws its receptor types in the colors ofreceptor_qcunless acategorical_scaleis given. A logColorScaledraws values that are not positive in its missing color.Returns a
PlotResult. Access.figurein notebooks, or call.save(...)/.close()when you own the figure.- Return type:
- 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 exampleRNA_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.
layoutconsumes an immutable embedding artifact and its stored cell selection.layout_keyreads two explicit live metadata columns named{layout_key}1and{layout_key}2.color_bymust be continuous metadata, not a gene. PassCellField(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 inembedding():ColorScale.missing_color, gray by default, ormissing_coloras an explicit override. Passsubset_byto keep cells markedTruein a boolean cell-metadata column.- Return type:
- 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.
usageis the result ofds.repertoire.gene_usagefor the pairs ofgenes=("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 itsmax_genesV genes andmax_genesJ 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 raisesValueErrorwhenusagecounts other gene fields or groups of cells, or no chain has both calls.Tables:
pairs, the record’s rows.- Raises:
TypeError – If
usageis not aGeneUsagerecord, or another argument has the wrong type.ValueError – If
usagecounts other gene fields or groups of cells, or no chain has both calls.KeyError – If
themenames no theme.
- Return type:
- 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.
usageis the result ofds.repertoire.gene_usagefor one gene field, such asgenes="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 mostmax_genesof 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 ofgroup_bycolumns or agroupsartifact, 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. Withcount="clonotypes"the fractions count clonotypes, or clonotype clusters for clonotypes that a distance metric linked. The plot raisesValueErrorwhenusagecounts several gene fields or no chain has a call of its field.groups, aNamedCellArtifactof 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
usageis not aGeneUsagerecord, or another argument has the wrong type.ValueError – If
usagecounts several gene fields, or no chain has a call of its field.KeyError – If the store does not hold the clonotypes that
usagecounts.RuntimeError – If those clonotypes are incomplete, as a call that stopped before it finished leaves them.
- Return type:
- 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.
genotypesis avariant_genotypesartifact, such as one fromds.variants.genotypes, andsitesthe sites to draw, by label or position asds.variants.load_genotypestakes 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 ismissingthere.group_bynames cell metadata columns, one or several, such as the cell type, andgroupsa 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 bySiteand the grouping: the columns’ names, aNamedCellArtifactasgroupsby 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, asembedding(layout=...)draws them, colored by their call at the one site thatsitesnames 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
layoutis 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_bycolumn is missing or named twice, two groups get one name,sitesnames a site the genotypes do not hold, a layout is drawn for several sites, orlayoutis 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:
- cytearc.plotting.graph_qc(graph, theme='notebook', show=True)#
Plot node degree and edge weight distributions for a sparse graph.
- Return type:
- 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.
callsis aguide_callsartifact, such as one fromds.perturbation.call_guidesords.perturbation.import_guide_calls. The first panel counts cells by their number of called guides; its last bar gathers the cells withmax_guides_per_cellor 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:
- 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.
thresholdsis guide calls ofds.perturbation.call_guideswithmethod="poisson_gaussian"or"gaussian", or theirguide_thresholdsartifact, asds.perturbation.load_guide_thresholdsreads them.With
guides, any collection of guide IDs such as theguidesindex 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 thatmin_umiset 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.sampleskeeps the panels or points of those sample labels. Whenguidesandsamplesselect more thanmax_panelspanels, 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, withguides,"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:
- 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.
colormapscolors the features not selected and the selected ones by the number of cells that express them, each a Matplotlib colormap name or a registeredColormap, 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_sizesholds the two groups’ marker areas in points squared,label_sizethe size in points of the axis labels and ticks, andfigsizethe 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:
- 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
embedCurvesdoes.ds.trajectory.curves_in_layoutreturns the points drawn, without a figure.dfoverrides the curves’ degrees of freedom for this smoothing; like theirs, it lies between 2 and the size of their spline basis, 32 by default.layoutmust 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 raisesValueError. The lineages take their colors as inlineage_trends.- Return type:
- 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
vmintovmax. 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_featureslabels rows beside the last panel. A name matches the retained features case-insensitively and keeps the caller’s spelling, and aFeatureReffinds a feature by name, ID, or index and shows itslabel, or its name, followed by its ID where another row has that name. A name that several retained features share raisesValueErrornaming their IDs; pick one withFeatureRef(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_trendscolors lineages, and more than 12 modules take evenly spaced hues, with a warning; aclusterbar_cmapis sampled at evenly spaced positions instead.heatmap_cmapandpseudotime_cmapcolor the profiles and the pseudotime strips. Each colormap argument takes a Matplotlib colormap name or a registeredColormap.- Return type:
- 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 inleaf_color, and the other clusters are circles innode_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.layoutmust 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 raisesValueError.- Return type:
- cytearc.plotting.lineage_trends(store, *, aggregation, features, lineages=None, axis='progress', lineage_cmap=None, line_width=2.0, n_columns=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
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; withaxis="pseudotime"they sit at their mean pseudotime, where bins inside an endpoint crowd together.featuresnames retained features of the aggregation. A name matches case-insensitively and titles its panel in the caller’s spelling. AFeatureReffinds a feature by name, ID, or index, and its panel takes itslabel, or the feature’s name, followed by its ID where another retained feature has that name. A name that several retained features share raisesValueErrornaming their IDs; draw one of them withFeatureRef(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_cmaptakes a Matplotlib colormap, by name or as a registeredColormap, to sample at evenly spaced positions from 0 to 1, and a single lineage then takes the colormap’s first color.- Return type:
- 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.
transferis alabel_transferartifact fromds.mapping.transfer_labels, andknown_labelsthe 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 onmetricis 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_fractionforvoteFractionandmax_distancefornearestDistance, and every other saved rule still applies. Any other metric is therefore calibrated among the cells that the transfer labeled.chosen_thresholdis 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 explicitthresholdsit is marked only when it is one of them.- Return type:
- 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.
transferis alabel_transferartifact fromds.mapping.transfer_labels.known_labelsholds 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 theabstention_labelcolumn, which must differ from every known and transferred label.- Return type:
- 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.
transferis alabel_transferartifact fromds.mapping.transfer_labels. The plot reads its saved evidence, so it shows exactly the votes and distances that decided the saved labels.target_groupsnames 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:
- 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_groupsnames 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 byreference_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:
- 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.
cmaptakes a Matplotlib colormap name, a registeredColormapor a list of colors, and acolor_scalethat names a colormap replaces it.- Return type:
- 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 showcategorical_scale.labelsor the stored display labels.value="mean"colors by average expression;value="fraction"colors by the share of measured cells aboveexpression_cutoff.standardize="feature"applies only to means.sample_byhas the same equal-sample weighting behavior asdotplot(), 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 byfeature_groupandfeature. Grouped rows keep their groups, so they cannot be clustered.group_byandgroupstake whatdotplot()takes, and title the group axis asdotplot()does.- Return type:
- 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.
classesis amixscape_classesartifact ofds.perturbation.mixscape, asds.perturbation.load_mixscapereads it. Among the cells that carry one target, Mixscape calls each cell knocked out (KO, or theperturbation_typeof 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, withtarget,n_cells,n_ko,n_npandko_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, withtarget,split,score,global_classandposterior, in panel order.targetskeeps those targets in that order. Otherwise the plot keeps themax_targetstargets with the most cells, fitted targets forpanel="scores", ties broken by name, in the order of the bars, and the title says when it leaves any out. Whentargetsnames more thanmax_targetstargets, 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:
- 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.
layoutmust hold the graph’s cells, whichever operation made its cell selection; a layout of other cells raisesValueError.cmaptakes a Matplotlib colormap name or a registeredColormap.- Return type:
- 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.
clustersis aperturbation_clustersartifact ofds.perturbation.cluster, asds.perturbation.load_clustersreads 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;perturbationsorcluster_idsthen 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’sn_perturbations, therowof its number and whether it isnumbered.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.labelnames 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’sn_perturbationsand the medianxandyof 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.
perturbationskeeps those perturbations, andcluster_idskeeps 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 whenlabelnames a perturbation that the plot does not draw or comes withpanel="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=Falseleaves 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:
- 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_leaveswedges.clonesare clones cut from a phylogeny byds.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 untilmax_leaveswedges 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 thanmax_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_leavesdraws its largest trees and the others as one gray wedge that says how many trees it holds;treedraws 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’snodestable 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,cloneandlabel(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), andy,lowandhigh, its middle and extent in cells from the top.- Raises:
TypeError – If
clonesis not an ArtifactRef,treeis not text,max_leavesis not an integer, another argument has the wrong type, or the store does not draw phylogenies.ValueError – If
cloneswere not cut from a phylogeny,max_leavesis below 1, ortreenames 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:
- 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_featureslabels rows of the heatmap. A name matches the retained features case-insensitively and keeps the caller’s spelling, and aFeatureReffinds a feature by name, ID, or index and shows itslabel, or its name, followed by its ID where another row has that name. A name that several retained features share raisesValueErrornaming their IDs; pick one withFeatureRef(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, aslineage_heatmapdoes, and more than 12 modules take evenly spaced hues, with a warning; aclusterbar_cmapis sampled at evenly spaced positions instead.heatmap_cmapcolors the profiles, coolwarm by default, andpseudotime_cmapthe pseudotime strip, viridis by default, unlesscolor_scaleorpseudotime_scalenames a colormap. Each colormap argument takes a Matplotlib colormap name or a registeredColormap.- Return type:
- 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_pointscells, each panel draws the points it shows withseed, a seed of NumPy’sRandomStatefrom 0 to 2**32 - 1. The groups take the colors ofcmap, a palette that seaborn’scolor_palettereads: the name of a seaborn palette or a Matplotlib colormap, or a list of colors.group_titlenames what the groups of thegroupscolumn are, such as “Sample”: it titles each panel’s axis of the groups and the legend thatPlotResult.legendsreports. Without it the axis is left blank and the legend is reported asgroups, the column’s name; a panel of one group draws no axis of groups to title.datais a pandas DataFrame with agroupscolumn and one numeric column per metric. The groups of an orderedCategoricalfollow 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, asNA; other groups take natural order.- Return type:
- 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.
receptorsis animmune_receptorsartifact, such as one fromds.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_bynames cell metadata columns, one or several, such as the sample, andgroupsa 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, aNamedCellArtifactasgroupsby its name, or else the title of the artifact’s record. A label artifact may hold fewer cells than the receptors.Tables:
receptor_typeandchain_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; andchains_per_cell(cells per number of chains of each arm, indexed byn_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
receptorsis not animmune_receptorsartifact, agroup_bycolumn 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:
- 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.
allelesis alineage_allelesartifact, such as one fromds.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 thanmax_sites, 40 by default, the most sites an axis names, themax_sitessites 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’ssite_states()with each share.- Raises:
TypeError – If an argument has the wrong type, or the store does not load lineage alleles.
ValueError – If
allelesis not alineage_allelesartifact, 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:
- 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 throughtargets, 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 itsoutput_filename, oroutputFilenamein 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_errorrecords the error under the step’s name infailuresand 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 withcontinue_on_erroris recorded infailures, andoutputsleaves those steps out.- Return type:
- 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.
spectratypeis the result ofds.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. Withcount="clonotypes"the fractions count clonotypes, or clonotype clusters for clonotypes that a distance metric linked. The plot raisesValueErrorwhen no chain has a junction.groups, aNamedCellArtifactof 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
spectratypeis not aSpectratyperecord, 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
spectratypecounts.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:
- 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()orplt.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.
countsis avariant_countsartifact, such as one fromds.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_bynames cell metadata columns, one or several, such as the sample, andgroupsa 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 aNamedCellArtifactasgroupstitles 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) andcells(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_bycolumn 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:
- 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.
variantsis avariant_selectionartifact fromds.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
variantsis not avariant_selectionartifact, or no variant has a value on the x axis.
- Return type:
- class cytearc.plotting.PlotResult(figure, axes, tables, legends, scales, provenance, owns_figure, theme='notebook')#
Return value from cytearc.plotting functions.
figureis the matplotlib figure.axesmaps panel keys to axes.tablesholds any summary data used to build the plot.owns_figureis 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, asplt.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 withtarget=or composed withcompose_results()included. Outside IPython,show()hands an interactive canvas toplt.show()and closes only an owned figure. A closed figure can still be saved or drawn on. In Jupyter,result.show()anddisplayof the figure,result.figure, show it with everything drawn on it, andplt.show()does not. A plot drawn into the axes of a SubFigure keeps the subfigure asfigure:show(),close(),save()andsave_provenance()act on the whole figure that holds it,result.figure.figure, which is the figure todisplay.- 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=Truewhen the destination supplies its own background.exact_size=Truekeeps 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=Truewrites a sibling JSON file with the plot metadata, and a path writes it there.- Raises:
TypeError – If
transparentorexact_sizeis not a boolean, orprovenance_sidecaris neither a boolean nor a path.ValueError – If the path has no extension or a format the canvas cannot write,
dpiis 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 (seeby).assay (
str|None) – Assay name. Defaults to the store default assay when omitted.by (
Literal['name','id','index']) – How to look upvalue:name,id, orindex.label (
str|None) – Optional display label.reduction (
Optional[Literal['mean','sum']]) – Required when multiple features match;meanorsum.
- class cytearc.plotting.CellField(key, kind='auto', label=None)#
Point
color_byor 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
namein panels, axes and legends, asCellField.labeltitles 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_byis the column that identifies biological samples.condition_byis the experimental condition (for example treatment). For paired composition plots, also setsubject_byorpair_byso 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. Withsource="assay"it needs a normalizer that supportslog_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/vmaxfor fixed limits, orquantiles=(low, high)to ignore extreme tails (for example(0.0, 0.99)clips the top 1%).vcenteris for diverging maps such as scaled fold changes.scopecontrols whether limits are computed per feature (default), per panel, or shared across every continuous panel in the figure.cmapnames a colormap thatmatplotlib.colormapsholds, or leaves the plot’s default; aColormapof your own serves oncematplotlib.colormaps.registerholds it under a name of its own. A plot refuses any othercmapbefore 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.
ordersets legend and axis order; a category that a plot shows andorderleaves out raises an error.palettemaps each category to a color string; a category that a plot shows andpaletteleaves out raises an error, so pass a complete map when you customize colors.labelsmaps categories to the text that ticks and legends show.palette_namepicks the generated colors,"default"or"colorblind".missing_colorandmissing_labeldraw 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:
labelsalone renames categories in their stored order and colors,orderalone keeps the stored colors, andpalettealone keeps the stored order.labelsmerge with the stored labels category by category. Apalette_namereplaces 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_byandgroupsoptionally 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 thanmin_supporteffective support.max_hotspotscan retain only the strongest connected regions at the lowest contour level.cmapnames a Matplotlib colormap that colors the contour levels, as aColorScalenames one; without it every level takescolor.
- 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.