Build the figures of a single-cell analysis with ds.plots: a UMAP colored by cell type and by gene, marker summaries across cell types, distributions within each type, the cell-type composition of computed clusters, and composed panels saved for a manuscript. The data are 3,696 cells of the embryonic mouse pancreas Bastidas-Ponce et al., 2019 in eight published cell types, from Ductal cells through Ngn3 low and Ngn3 high endocrine progenitors (EP) and Pre-endocrine cells to the hormone-producing Alpha, Beta, Delta, and Epsilon cells. The figures show the glucagon, insulin, and somatostatin genes each concentrated in its own endocrine type, where it is detected in 61% to 87% of the cells, and each hormone-producing type gathered in one computed cluster of the saved analysis.
Open the example data¶
The store holds a saved RNA analysis: a pipeline run labeled rna that records the cells, UMAP, and clusters that ds.pipeline.rna computed. ds.pipeline.open reopens the run without recomputing it, and run["umap"] returns its UMAP as an artifact reference, the handle that plots take as layout. The store’s cell metadata column clusters holds the published cell types, not the run’s computed clusters. A CellField points plots at a metadata column and gives it a label for legends, axes, and titles: “Cell type” for clusters, and “Counts per cell” and “Genes per cell” for each cell’s total counts and detected genes.
# Use CyteArc for the data and figures, Matplotlib for custom panels, and pandas for tables.
from pathlib import Path
import matplotlib.pyplot as plt
import pandas as pd
import cytearc
import cytearc.plotting as splt
# Keep routine logs and progress bars out of the outputs.
cytearc.configure_output(level="WARNING", progress=False)
# Download the prepared pancreas store, which holds a saved RNA analysis.
dataset = cytearc.datasets.connect("cytearc_docs").download_dataset(
"bastidas-ponce_4K_pancreas-d15_rnaseq",
destination="cytearc_datasets",
zarr=True,
)
# Open the store and its saved run, and keep the run's UMAP for every embedding.
ds = cytearc.DataStore(f"{dataset}/data.zarr", nthreads=4)
run = ds.pipeline.open(label="rna")
layout = run["umap"]
# Name the metadata columns that the figures show, with readable labels.
cell_types = splt.CellField("clusters", label="Cell type")
depth = splt.CellField("RNA_nCounts", label="Counts per cell")
detected_genes = splt.CellField("RNA_nFeatures", label="Genes per cell")
# Show the store's cells, assays, and metadata columns.
dsDataStore has 3696 (3696) cells with 1 assays: RNA
Cell metadata:
'I', 'ids', 'names', 'G2M_score', 'RNA_UMAP1',
'RNA_UMAP2', 'RNA_clusters', 'RNA_leiden_cluster', 'RNA_nCounts', 'RNA_nFeatures',
'RNA_percentMito', 'RNA_percentRibo', 'S_score', 'clusters', 'clusters_coarse'
RNA assay has 27998 features and following metadata:
'I', 'ids', 'names', 'dropOuts', 'highly_variable_genes',
'nCells'Started: 2026-11-23T22:59:36.304279Z | Wall time: 7.279 s
Color an embedding¶
ds.plots.embedding draws the cells of a layout colored by what color_by names: a metadata column, a CellField, or a gene. A categorical column gives each category a color and a legend:
# Color the run's UMAP by the published cell types.
ds.plots.embedding(layout=layout, color_by=cell_types)
Started: 2026-11-23T22:59:43.584737Z | Wall time: 0.199 s
The UMAP lays out the differentiation path: Ductal cells mixed with Ngn3 low EP cells on the right, an arc of Ngn3 high EP cells across the top, and Pre-endocrine cells on the left. The hormone-producing types sit at the lower left: Beta cells at the bottom, Alpha cells beside them, and the small Delta and Epsilon populations above the Alpha cells.
A gene name colors cells by the gene’s expression, and a list of genes draws one panel per gene. Expression is in counts per 1,000 counts of the cell, the scale that the RNA assay’s size factor ds.RNA.sf sets. Gcg, Ins2, and Sst encode glucagon, insulin, and somatostatin, the hormones of Alpha, Beta, and Delta cells:
# Draw one panel per hormone gene, each on its own color scale.
ds.plots.embedding(layout=layout, color_by=["Gcg", "Ins2", "Sst"])
Started: 2026-11-23T22:59:43.784798Z | Wall time: 0.427 s
Each hormone marks the region of its cell type: Gcg the Alpha cells, Ins2 the lower tip of the Beta lobe, and Sst the Delta cluster. Each panel’s color scale runs to its brightest cells, so Beta cells with modest Ins2 look as dark as cells without it.
Make expression easier to see¶
Two display settings bring out cells near the bottom of a scale:
NormalizationSpec(transform="log1p")plots log(1 + x), which compresses the highest values.ColorScale(quantiles=(0.0, 0.99))ends the color range at the 99th percentile, so the top 1% of cells share the top color.
# Log-transform Ins2 and cap its color range at the 99th percentile.
ds.plots.embedding(
layout=layout,
color_by="Ins2",
normalization=splt.NormalizationSpec(transform="log1p"),
color_scale=splt.ColorScale(quantiles=(0.0, 0.99)),
)
Started: 2026-11-23T22:59:44.213457Z | Wall time: 0.209 s
On the compressed and capped scale, Ins2 rises along the Beta lobe, from low values next to the Pre-endocrine cells to the cap at the lower tip. Both settings change only the colors, not the stored values, so state them in the figure legend when you publish.
Choose which cells are drawn on top¶
Where cells overlap, the cell drawn last hides the cells beneath it. Gene colors draw the highest values last, so a sparse marker stays visible above the cells that lack it. Cell types and other metadata columns draw in a random order fixed by seed (0 by default), so that the cells stored last, such as the last sample of a merged store, do not cover the others. seed=None keeps the stored order, and sort_values=True draws the highest values last for any continuous color.
To compare the two orders, the code below draws count depth, each cell’s total counts, into the two panels of one Matplotlib figure: target names the axis that each plot draws into, and show=False stops each call from displaying the figure before both panels are drawn:
# Draw count depth in the default shuffled order and with the highest values last.
figure, axes = plt.subplots(1, 2, figsize=(8, 4), layout="constrained")
for axis, sort_values, title in zip(
axes, (None, True), ("Shuffled order (default)", "Highest values last"), strict=True
):
ds.plots.embedding(
layout=layout,
color_by=depth,
sort_values=sort_values,
target=axis,
show_titles=False,
show=False,
)
axis.set_title(title)
plt.show()
Started: 2026-11-23T22:59:44.423303Z | Wall time: 0.268 s
With the highest values last, the deepest cells cover their neighbors, so dense regions look deeper than most of their cells, most visibly the Ductal region on the right. In the shuffled order, the cell on top at each point is a random one, so the colors show the typical depth there.
Summarize markers across groups¶
A dot plot summarizes each gene in each group twice: color shows the mean expression, which counts cells without the gene as zeros, and dot size shows the fraction of cells whose expression exceeds expression_cutoff, zero by default. A large dark dot means widespread low expression; a small bright dot means strong expression in a few cells. The returned PlotResult keeps both values in tables["aggregate"]:
# Compare hormone expression and detection across the published cell types.
markers = ds.plots.dotplot(features=["Gcg", "Ins2", "Sst"], group_by="clusters")
# Tabulate the detected fraction and the mean expression behind each dot, with the unit of the mean.
markers.tables["aggregate"].pivot(
index="group", columns="feature", values=["fraction", "mean"]
).rename(columns={"mean": f"mean per {ds.RNA.sf:,} counts"}, level=0).round(2)
| fraction | mean per 1,000 counts | |||||
|---|---|---|---|---|---|---|
| feature | Gcg | Ins2 | Sst | Gcg | Ins2 | Sst |
| group | ||||||
| Alpha | 0.66 | 0.09 | 0.03 | 23.17 | 0.03 | 0.01 |
| Beta | 0.18 | 0.61 | 0.10 | 0.09 | 4.91 | 0.28 |
| Delta | 0.17 | 0.09 | 0.87 | 0.03 | 0.02 | 37.08 |
| Ductal | 0.17 | 0.03 | 0.06 | 0.02 | 0.00 | 0.01 |
| Epsilon | 0.34 | 0.04 | 0.02 | 1.97 | 0.01 | 0.03 |
| Ngn3 high EP | 0.12 | 0.03 | 0.03 | 0.02 | 0.01 | 0.01 |
| Ngn3 low EP | 0.18 | 0.03 | 0.06 | 0.02 | 0.00 | 0.01 |
| Pre-endocrine | 0.12 | 0.04 | 0.04 | 0.03 | 0.01 | 0.08 |
Started: 2026-11-23T22:59:44.692567Z | Wall time: 0.261 s
Each hormone is detected in most cells of its own type, at a mean far above any other type: Gcg in 66% of Alpha cells at 23 counts per 1,000, Ins2 in 61% of Beta cells at 4.9, and Sst in 87% of Delta cells at 37. Gcg is also detected in 12% to 18% of the Ductal, EP, and Pre-endocrine cells, at means of 0.03 or less, and in 34% of Epsilon cells at 2.0, so its mean separates Alpha cells more sharply than its detected fraction does.
A matrix plot draws the means as a heatmap. In the dot plot, Sst in Delta cells set the top of the shared color scale and left Ins2 in Beta cells dark; standardize="feature" converts each gene’s means into z-scores across the cell types, so every gene spans the scale. categorical_scale adds the marker names to the labels of the hormone-producing types. A scale that sets only labels keeps the order and colors that the store records for the cell types, the order of the dot plot:
# Label the hormone-producing types with their genes; the cell types keep their stored order.
cell_type_scale = splt.CategoricalScale(
labels={"Alpha": "Alpha (Gcg)", "Beta": "Beta (Ins2)", "Delta": "Delta (Sst)"},
)
# Scale each gene's means across cell types, so every gene spans the color range.
ds.plots.matrixplot(
features=["Gcg", "Ins2", "Sst"],
group_by="clusters",
standardize="feature",
categorical_scale=cell_type_scale,
)
Started: 2026-11-23T22:59:44.954600Z | Wall time: 0.263 s
On the standardized scale, Gcg in Alpha, Ins2 in Beta, and Sst in Delta cells all reach the top of the color range, and the only other entry above the dark background is Gcg in Epsilon cells. value="fraction" colors the matrix by detected fraction instead, and cluster_groups=True orders the groups by similarity under a dendrogram; the plotting API reference describes every option.
Inspect distributions¶
A mean hides how values spread within a group. Violins show the spread of count depth and detected genes in each cell type. max_points caps the cells drawn as points and max_density_points the values that estimate each violin, which keeps the plot fast on large datasets. The returned tables hold every cell’s value, for summaries such as medians:
# Compare count depth and detected genes within each cell type.
distributions = ds.plots.distribution(
keys=[depth, detected_genes],
grouping=cell_types,
max_points=250,
max_density_points=500,
seed=7,
)
# Check whether the plot sampled cells for its points or densities.
print(distributions.provenance.notes)
# Summarize each cell type by its number of cells and its median depth and genes.
depth_values = distributions.tables[depth.label].groupby("group")["value"]
gene_values = distributions.tables[detected_genes.label].groupby("group")["value"]
pd.DataFrame(
{
"cells": depth_values.size(),
"median counts": depth_values.median(),
"median genes": gene_values.median(),
}
).round().astype(int)
('distribution', 'violin', 'subsampled_display', 'subsampled_density')
| cells | median counts | median genes | |
|---|---|---|---|
| group | |||
| Alpha | 481 | 5576 | 2343 |
| Beta | 591 | 6172 | 2528 |
| Delta | 70 | 5624 | 2257 |
| Ductal | 916 | 8044 | 2840 |
| Epsilon | 142 | 6522 | 2528 |
| Ngn3 high EP | 642 | 5899 | 2266 |
| Ngn3 low EP | 262 | 7360 | 2696 |
| Pre-endocrine | 592 | 4876 | 2170 |
Started: 2026-11-23T22:59:45.218918Z | Wall time: 0.224 s
Ductal cells have the deepest libraries, with medians of 8,044 counts and 2,840 genes and the longest upper tails, and Pre-endocrine cells the shallowest, at 4,876 counts and 2,170 genes. One threshold across the dataset would therefore remove more cells of some types than of others; Quality control and doublet detection shows how to check which populations a threshold removes.
The subsampled_display and subsampled_density notes flag that the figure was drawn from samples of the cells, and provenance.extras keeps the limits and the seed that drew them; the table’s medians use every cell. kind="box", kind="hist", and kind="ecdf" show the same values in other forms.
Stacked violins compare several genes across chosen groups: grouping names the labels that divide the cells, and groups keeps the listed ones:
# Compare the three hormone genes in their three cell types with stacked violins.
ds.plots.distribution(
keys=["Gcg", "Ins2", "Sst"],
grouping=cell_types,
groups=["Alpha", "Beta", "Delta"],
kind="stacked_violin",
)
Started: 2026-11-23T22:59:45.443779Z | Wall time: 0.376 s
Gcg and Ins2 pile up near zero within their types, because they are detected in only 66% of Alpha cells and 61% of Beta cells, while Sst, detected in 87% of Delta cells, spreads over a wide range.
A violin of one gene across all eight cell types shows where else the gene is expressed:
# Compare Sst across all eight cell types.
ds.plots.distribution(keys=["Sst"], grouping=cell_types, kind="violin")
Started: 2026-11-23T22:59:45.821099Z | Wall time: 0.211 s
Outside the Delta cells, Beta cells have the longest Sst tail: Sst is detected in 10% of them, at a mean of 0.28 counts per 1,000.
Save a figure¶
The PlotResult that a plot returns writes the figure with save and releases its memory with close; with show=False, the figure is saved without being displayed:
# Draw the cell-type UMAP without displaying it, save it as a PNG, and close it.
output_directory = Path("figures")
result = ds.plots.embedding(layout=layout, color_by=cell_types, show=False)
figure_path = result.save(output_directory / "pancreas_cell_types.png")
result.close()
# Confirm the file and its size in bytes.
{"file": str(figure_path), "bytes": figure_path.stat().st_size}{'file': 'figures/pancreas_cell_types.png', 'bytes': 181749}Started: 2026-11-23T22:59:46.033044Z | Wall time: 0.112 s
The file extension sets the format, such as PNG, PDF, SVG, or TIFF, and dpi=300 sets the resolution of a raster format. exact_size=True, the default, keeps the figure’s size in inches, and exact_size=False crops it to its contents. provenance_sidecar=True also writes a JSON record of the plot’s cell count, scales, legends, and settings beside the file.
Focus on selected groups¶
facet_by splits the cells into one panel per group of a metadata column, and groups keeps the listed groups. The panels share one color scale, so their colors compare directly:
# Show Ins2 in Alpha, Beta, and Delta cells on separate panels with one shared scale.
ds.plots.embedding(
layout=layout,
color_by="Ins2",
facet_by=cell_types.key,
groups=["Alpha", "Beta", "Delta"],
)
Started: 2026-11-23T22:59:46.145651Z | Wall time: 0.284 s
On the shared scale, the Alpha and Delta panels stay dark: Ins2 is detected in 9% of each, at means of 0.03 and 0.02.
A highlight draws one group in color over the faded other cells, which keeps the whole layout as context:
# Highlight Beta cells and fade the other cells into context.
ds.plots.embedding(
layout=layout,
color_by=None,
highlight=splt.Highlight(by=cell_types.key, groups=("Beta",)),
show_titles=False,
)
Started: 2026-11-23T22:59:46.430974Z | Wall time: 0.070 s
The 591 Beta cells fill the whole lobe, including its upper part next to the Pre-endocrine cells, where Ins2 is lowest within the lobe.
Compare composition across groups¶
ds.plots.composition stacks the fractions of each category within each group. Here the categories are the published cell types and the groups are the clusters that the saved run computed, passed as the run’s clusters artifact. Drawing into your own axis lets you name the axes and the legend:
# Stack the published cell types within each computed cluster of the saved run.
figure, axis = plt.subplots(figsize=(7, 3.5), layout="constrained")
composition = ds.plots.composition(
category_by="clusters", grouping=run["clusters"], target=axis, show=False
)
# Name the axes and the legend for this comparison.
axis.set(xlabel="Computed cluster", ylabel="Fraction of cells")
axis.get_legend().set_title("Cell type")
plt.show()
Started: 2026-11-23T22:59:46.502118Z | Wall time: 0.095 s
# Name the largest published cell type in each computed cluster.
shares = composition.tables["per_group"]
largest = shares.loc[shares.groupby("sample")["n_cells"].idxmax()]
largest.set_index("sample").rename_axis("cluster").round(2)| category | proportion | n_cells | |
|---|---|---|---|
| cluster | |||
| 1 | Beta | 0.97 | 534 |
| 2 | Ductal | 0.77 | 420 |
| 3 | Alpha | 0.94 | 421 |
| 4 | Ngn3 high EP | 1.00 | 385 |
| 5 | Pre-endocrine | 0.84 | 310 |
| 6 | Pre-endocrine | 0.62 | 215 |
| 7 | Ductal | 0.67 | 153 |
| 8 | Ductal | 0.96 | 205 |
| 9 | Epsilon | 0.70 | 135 |
| 10 | Ngn3 high EP | 0.58 | 102 |
| 11 | Ductal | 0.83 | 120 |
| 12 | Delta | 0.72 | 69 |
Started: 2026-11-23T22:59:46.598310Z | Wall time: 0.006 s
Each hormone-producing type gathers in one computed cluster: cluster 1 is 97% Beta and holds 534 of the 591 Beta cells, cluster 3 is 94% Alpha and holds 421 of the 481 Alpha cells, cluster 9 is 70% Epsilon and holds 135 of the 142 Epsilon cells, and cluster 12 is 72% Delta and holds 69 of the 70 Delta cells, with Pre-endocrine cells making up most of the rest of clusters 9 and 12. The other eight clusters are mostly Ductal, EP, and Pre-endocrine cells: Ductal cells make up most of clusters 2, 7, 8, and 11, Ngn3 high EP cells fill cluster 4 and make up most of cluster 10, and Pre-endocrine cells make up most of clusters 5 and 6.
With sample_by, the same plot draws one bar per sample instead. For matched donors, kind="per_sample" takes the StudyDesign that the donor-level comparisons tutorial builds and connects each donor’s proportions across conditions.
Compose panels and choose a style¶
A figure of your own can hold several CyteArc plots, here the cell types beside Ins2 expression:
# Place the cell types and Ins2 expression side by side in a figure of your own.
figure, axes = plt.subplots(1, 2, figsize=(8, 4), layout="constrained")
for axis, field, title in zip(
axes, (cell_types, "Ins2"), ("Cell types", "Ins2"), strict=True
):
ds.plots.embedding(
layout=layout,
color_by=field,
target=axis,
show_titles=False,
show=False,
)
axis.set_title(title)
plt.show()
Started: 2026-11-23T22:59:46.605136Z | Wall time: 0.309 s
cytearc.plotting.compose_results merges the results of such panels into one PlotResult, adds panel letters, and draws a legend that several panels share only once. Save a figure of your own with Matplotlib’s figure.savefig and close it with plt.close:
# Save the composed figure as a PDF and close it.
panel_path = output_directory / "pancreas_panels.pdf"
figure.savefig(panel_path)
plt.close(figure)
# Confirm the file and its size in bytes.
{"file": str(panel_path), "bytes": panel_path.stat().st_size}{'file': 'figures/pancreas_panels.pdf', 'bytes': 1296620}Started: 2026-11-23T22:59:46.914715Z | Wall time: 1.255 s
theme="paper" uses smaller text for print, and theme="dark" draws light text and lines for dark notebook themes, on a transparent background that save fills with charcoal; the default is theme="notebook". By default, point size shrinks as the number of cells grows, and a plot with few categories, like these eight, gets a side legend. legend_loc="on_data" writes each category’s name on its cells instead:
# Place each cell-type name on its population instead of in a legend.
ds.plots.embedding(layout=layout, color_by=cell_types, legend_loc="on_data")
Started: 2026-11-23T22:59:48.170260Z | Wall time: 0.091 s
Names on the data suit a few separate populations. Where populations overlap, a name can land among another type’s cells, as Ngn3 low EP does among the Ductal cells.
Plot large datasets as pixels¶
embedding_raster averages a continuous metadata column, not a gene, over a grid of pixels. It reads the column in blocks rather than whole, so memory stays bounded, and it draws one value per pixel instead of overlapping points, for datasets too large to scatter quickly:
# Average count depth over a grid of 60 by 60 pixels; the default grid of 400 pixels
# per side suits larger datasets.
ds.plots.embedding_raster(layout=layout, color_by=depth, pixels=60)
Started: 2026-11-23T22:59:48.262072Z | Wall time: 0.079 s
The highest means lie along the lower edge of the Ductal region, where the Ductal cells with the deepest libraries sit, and the Pre-endocrine and endocrine regions on the left stay low.
Find the diagnostic plots¶
Diagnostic plots appear on the page of the analysis step they check:
Highly variable genes: the mean-variance plot of the genes that enter the analysis.
Choose PCA dimensions and compare layouts: PCA components and layout choices.
Build a neighbor graph stage by stage: the degree and edge weights of the neighbor graph.
Compare clusterings and check the clusters: membership strength and the relationships between clusters.
Annotate cell types and states: marker heatmaps and the evidence behind each cell-type label.
- Bastidas-Ponce, A., Tritschler, S., Dony, L., Scheibner, K., Tarquis-Medina, M., Salinno, C., Schirge, S., Burtscher, I., Böttcher, A., Theis, F. J., Lickert, H., & Bakhti, M. (2019). Comprehensive single cell mRNA profiling reveals a detailed roadmap for pancreatic endocrinogenesis. Development, 146(12), dev173849. 10.1242/dev.173849