Cluster 3,948 human peripheral blood mononuclear cells (PBMCs) from the 10x Genomics 5k PBMC dataset on 10 and 30 principal components (PCs), compare the clusters with the 15-PC clusters of the PBMC analysis, and draw the 15-PC neighbor graph with three layout methods. On 10 PCs, Leiden clustering still finds 12 clusters, but two small populations lose theirs: the 25 CD16 monocytes join half of the CD14 monocytes, and a group of 29 NK cells joins a T-cell cluster. On 30 PCs, the CD16 monocytes keep their own cluster, the 29 NK cells join the other NK cluster, and most other changes move cells between T-cell clusters. Against the 15-PC clusters, the adjusted Rand index is 0.82 on 30 PCs and 0.62 on 10 PCs. UMAP, densMAP and t-SNE arrange the large clusters alike but differ in how densely they pack them and where they put the small ones.
CyteArc connects each cell to its nearest neighbors in PC space and clusters the resulting graph, so the number of PCs changes the neighbors, the graph and the clusters. A layout method such as UMAP only draws that graph in two dimensions, so its settings change the picture and leave the clusters as they are.
Open the prepared analysis¶
# Load the tools that tabulate and draw the comparisons.
from itertools import combinations
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.colors import to_hex
import cytearc
from cytearc.plotting import CategoricalScale
# Keep routine logs and progress bars out of the page.
cytearc.configure_output(level="WARNING", progress=False)
# Download the prepared PBMC store with its saved analysis.
dataset = cytearc.datasets.connect("cytearc_docs").download_dataset(
"tenx_5K_pbmc_rnaseq", destination="cytearc_datasets", zarr=True
)Started: 2026-11-14T15:42:33.643534Z | Wall time: 10.313 s
Open the store and its saved analysis, a PipelineRun labeled rna. The run maps each output name, such as normalized or umap, to an ArtifactRef, a reference to a saved result. Later calls take these references as input, and a call whose inputs and settings match a saved result reuses it. The run’s report records the settings that the run was called with:
# Open the store and its saved analysis.
ds = cytearc.DataStore(f"{dataset}/data.zarr", nthreads=4)
baseline = ds.pipeline.open(label="rna")
# Reuse the saved normalized values for new PCA fits and the saved UMAP for drawing.
normalized = baseline["normalized"]
umap = baseline["umap"]
# Show the saved settings that the comparisons keep or change.
stages = baseline.report()["run"]["config"]["stages"]
pd.Series(
{
"cells": len(baseline.cells.fetch("clusters")),
"variable genes": stages["hvg"]["top_n"],
"principal components": stages["pca"]["dims"],
"neighbors per cell": stages["neighbors"]["k"],
"Leiden resolution": stages["leiden"]["partitions"][0],
},
name="saved run",
dtype=object,
)cells 3948
variable genes 500
principal components 15
neighbors per cell 11
Leiden resolution 0.5
Name: saved run, dtype: objectStarted: 2026-11-14T15:42:43.958960Z | Wall time: 2.792 s
The saved run uses 15 PCs, fewer than the dims=21 default of ds.reduction.pca and ds.pipeline.rna. The comparisons below keep the run’s cells, genes and normalization and change one setting at a time. Draw the saved clusters on the saved UMAP:
# Draw the saved clusters on the saved UMAP, with each cluster's number on the data.
ds.plots.embedding(
layout=umap,
color_by=baseline["clusters"],
legend_loc="on_data",
show_titles=False,
figsize=(5, 4.5),
)
Started: 2026-11-14T15:42:46.752857Z | Wall time: 0.374 s
The PBMC analysis names the clusters from marker genes: T cells in clusters 1, 3, 4 and 8, CD14 monocytes in 2, NK cells in 5 and 9, B cells in 6 and 7, CD16 monocytes in 10, pDC-like cells in 11 and platelets in 12. On the UMAP, NK cluster 9 sits beside the lower end of T-cell cluster 3, and cluster 10 at the tip of the CD14 monocytes.
Fit PCA with 10 and 30 components¶
Build two more clusterings from the saved normalized values, one on 10 PCs and one on 30. Each build fits PCA, indexes the PCA coordinates for an approximate nearest-neighbor search, connects each cell to its 11 nearest neighbors in a weighted graph, and clusters the graph with Leiden Traag et al., 2019 at resolution 0.5, as the saved run did. The 15-PC fit and clusters come from the saved run, so the three clusterings differ only in their number of components. show_elbow_plot=True plots the share of the variance that each of the 30 components explains and marks the elbow, where the curve flattens:
# Compare 10, 15 and 30 PCs; the saved run supplies the 15-PC fit and its Leiden clusters at 0.5.
dimension_counts = (10, 15, 30)
pca_refs = {15: baseline["pca"]}
cluster_refs = {
15: ds.artifacts.find(
"clusters", graph=baseline["connectivity_map"], method="leiden", resolution=0.5
)
}
# Fit PCA, build the graph and cluster it on 10 and 30 PCs, with the saved run's other settings.
for dimensions in (10, 30):
pca_refs[dimensions] = ds.reduction.pca(
normalized, dims=dimensions, show_elbow_plot=dimensions == 30
)
ann = ds.graph.ann_index(pca_refs[dimensions])
neighbors = ds.graph.neighbors(ann, k=11)
graph = ds.graph.connectivity(neighbors)
cluster_refs[dimensions] = ds.clusters.leiden(graph, resolution=0.5)
# Read the cluster labels; the three clusterings cover the same cells in the same order.
cluster_values = {
dimensions: ds.artifacts.load_values(ref, cell_ids=False).values
for dimensions, ref in cluster_refs.items()
}
Started: 2026-11-14T15:42:47.128922Z | Wall time: 70.990 s
The elbow stands at the fifth component, after which the curve flattens. PCA of 500 genes is exact (the methods page describes the solver for wider inputs), so the 30-component fit starts with the same components as the 10- and 15-component fits, and one table gives the variance shares of all three:
# Tabulate each component's share of the variance, and the running total.
variance_share = 100 * ds.artifacts.load(pca_refs[30])["variance_ratio"][:]
variance_table = pd.DataFrame(
{"% of variance": variance_share, "cumulative %": variance_share.cumsum()},
index=pd.RangeIndex(1, len(variance_share) + 1, name="component"),
)
variance_table.loc[[1, 2, 3, 4, 5, 10, 15, 30]].round(1)| % of variance | cumulative % | |
|---|---|---|
| component | ||
| 1 | 13.6 | 13.6 |
| 2 | 7.8 | 21.4 |
| 3 | 5.8 | 27.3 |
| 4 | 4.0 | 31.3 |
| 5 | 1.5 | 32.7 |
| 10 | 0.7 | 37.5 |
| 15 | 0.4 | 39.9 |
| 30 | 0.3 | 45.1 |
Started: 2026-11-14T15:43:58.121459Z | Wall time: 0.018 s
The first four components explain 31.3% of the variance of the 500 scaled genes, and each later component adds 1.5% or less: the bend that the elbow marks. Whether the small populations need the components after the elbow shows only in the clusterings.
Measure how much the clusterings agree¶
The adjusted Rand index compares two clusterings of the same cells regardless of how their clusters are numbered. It is 1 for identical clusterings and near 0 for clusterings that agree no more than chance:
# Compare each pair of clusterings with the adjusted Rand index.
pd.Series(
{
f"{first} vs {second} PCs": ds.clusters.compute_concordance(
cluster_refs[first], cluster_refs[second]
)
for first, second in combinations(dimension_counts, 2)
},
name="adjusted Rand index",
).round(2)10 vs 15 PCs 0.62
10 vs 30 PCs 0.63
15 vs 30 PCs 0.82
Name: adjusted Rand index, dtype: float64Started: 2026-11-14T15:43:58.140719Z | Wall time: 0.070 s
Raising the number of PCs from 15 to 30 changes the clusters less (0.82) than lowering it to 10 (0.62), and the 10- and 30-PC clusterings agree at 0.63. To see which cells move, ds.clusters.relabel_by_overlap names each cluster after the 15-PC cluster that contributes most of its cells; the saved clusters, named after themselves, become 1a, 2a and so on. A letter tells apart clusters with the same main source, such as 1a and 1b. A 15-PC cluster that is the main source of no cluster appears after a hyphen, in the name of the cluster that takes most of its cells: 3-9a comes mostly from cluster 3 and takes most of cluster 9. Each clustering is named on its own, so 1b on 10 PCs and 1b on 30 PCs are different clusters. Count how the cells of each 15-PC cluster spread over the 10-PC clusters:
# Name each cluster after the 15-PC cluster that contributes most of its cells.
matched_refs = {
dimensions: ds.clusters.relabel_by_overlap(
cluster_refs[dimensions], cluster_refs[15]
)
for dimensions in dimension_counts
}
matched_names = {
dimensions: ds.artifacts.load_values(ref, cell_ids=False).values
for dimensions, ref in matched_refs.items()
}
# Count how the cells of each 15-PC cluster spread over another clustering's clusters.
def overlap_table(dimensions):
counts = pd.crosstab(
cluster_values[15],
matched_names[dimensions],
rownames=["15 PCs"],
colnames=[f"{dimensions} PCs"],
)
# Order the clusters by their main source and leave empty pairs blank.
return counts[counts.idxmax().sort_values(kind="stable").index].replace(0, "")
overlap_table(10)| 10 PCs | 1a | 1b | 2-10b | 2a | 3-9a | 4a | 5a | 6a | 7a | 8a | 11a | 12a |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 15 PCs | ||||||||||||
| 1 | 693 | 511 | 5 | 8 | ||||||||
| 2 | 343 | 361 | ||||||||||
| 3 | 332 | 180 | 16 | |||||||||
| 4 | 10 | 39 | 425 | |||||||||
| 5 | 1 | 282 | ||||||||||
| 6 | 1 | 244 | 11 | |||||||||
| 7 | 1 | 238 | ||||||||||
| 8 | 27 | 139 | ||||||||||
| 9 | 29 | |||||||||||
| 10 | 25 | |||||||||||
| 11 | 15 | |||||||||||
| 12 | 12 |
Started: 2026-11-14T15:43:58.212862Z | Wall time: 0.192 s
Leiden finds 12 clusters on 10 PCs too, but not the same 12. The 10-PC clustering splits T-cell cluster 1 between 1a (693 of its cells) and 1b (511), and the CD14 monocytes of cluster 2 between 2a (361) and 2-10b (343). Two small populations lose their clusters: all 25 CD16 monocytes of cluster 10 join 2-10b, and all 29 NK cells of cluster 9 join 332 cells of T-cell cluster 3 in 3-9a, while 180 other cells of cluster 3 join cluster 4 in 4a. Size alone does not decide which populations keep a cluster: the 15 pDC-like cells and 12 platelets, smaller still, keep theirs. B-cell clusters 6 and 7 and NK cluster 5 also keep nearly all their cells. Count the cells again for 30 PCs:
# Count how the cells of each 15-PC cluster spread over the 30-PC clusters.
overlap_table(30)| 30 PCs | 1a | 1b | 2a | 3a | 4a | 5-9a | 6a | 7a | 8a | 10a | 11a | 12a |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 15 PCs | ||||||||||||
| 1 | 1169 | 17 | 14 | 12 | 5 | |||||||
| 2 | 702 | 2 | ||||||||||
| 3 | 1 | 338 | 181 | 8 | ||||||||
| 4 | 103 | 370 | 1 | |||||||||
| 5 | 2 | 281 | ||||||||||
| 6 | 256 | |||||||||||
| 7 | 2 | 237 | ||||||||||
| 8 | 27 | 1 | 138 | |||||||||
| 9 | 29 | |||||||||||
| 10 | 2 | 23 | ||||||||||
| 11 | 15 | |||||||||||
| 12 | 12 |
Started: 2026-11-14T15:43:58.406465Z | Wall time: 0.018 s
On 30 PCs, 23 of the 25 CD16 monocytes keep a cluster of their own, 10a, and the 29 cells of cluster 9 join the other NK cluster in 5-9a. Most other changes fall among the T cells: 181 cells of cluster 3 join cluster 4 in 4a, as 180 did on 10 PCs; 103 cells of cluster 4 and 27 of cluster 8 join cluster 1; and 17 cells of cluster 1 form a cluster of their own, 1b. Going from 10 to 15 components adds little variance, from 37.5% to 39.9%, yet it separates the CD16 monocytes and the NK cells of cluster 9 from the clusters they join on 10 PCs: components 11 to 15, well past the elbow, carry what sets these two populations apart.
Compare the clusterings on the saved UMAP¶
Draw the three clusterings on the saved UMAP, so that only the cluster labels change between panels. Clusters named 1a to 12a keep the colors of saved clusters 1 to 12 from the other figures, and 1b, 2-10b, 3-9a and 5-9a get new colors:
# Keep each saved cluster's default color, and give the new clusters unused colors from the same palette.
colors = [to_hex(color) for color in matplotlib.colormaps["tab20"].colors]
saved_names = [
name for _, name in sorted(set(zip(cluster_values[15], matched_names[15])))
]
new_names = sorted(set().union(*matched_names.values()) - set(saved_names))
cluster_scale = CategoricalScale(
palette=dict(zip(saved_names, colors)) | dict(zip(new_names, colors[12::2]))
)
# Draw the three clusterings on the saved UMAP with their matched names.
figure, axes = plt.subplots(1, 3, figsize=(12, 4.2))
for axis, dimensions in zip(axes, dimension_counts, strict=True):
ds.plots.embedding(
layout=umap,
color_by=matched_refs[dimensions],
categorical_scale=cluster_scale,
legend_loc="on_data",
target=axis,
show_titles=False,
show=False,
)
axis.set_title(f"Leiden on {dimensions} PCs")
figure.tight_layout()
plt.show()
Started: 2026-11-14T15:43:58.425916Z | Wall time: 0.990 s
On the saved UMAP, the 10-PC clusters cut cluster 1 into an upper part, 1a, and a lower part, 1b, and the monocyte island into a lower part, 2a, and an upper part, 2-10b, that includes cluster 10’s tip. On both 10 and 30 PCs, the cells of cluster 3 that join 4a are its upper part, next to cluster 4. The 17 cells of the 30-PC cluster 1b lie scattered through the left half of cluster 1 rather than in one patch.
Change how tightly UMAP packs cells¶
UMAP places cells so that neighbors in the graph lie close together. min_dist sets how close the layout lets cells sit, relative to spread, which sets the overall scale of distances. Every layout from here on draws the saved 15-PC graph from the saved starting positions. Read the saved settings from the UMAP artifact, which records the parameters that made it, then lay out the graph with min_dist=0.1:
# Read the packing settings that the saved UMAP artifact records.
saved_umap = ds.artifacts.inspect(umap).parameters
print(f"Saved UMAP: min_dist={saved_umap['min_dist']}, spread={saved_umap['spread']}")
# Lay out the saved graph again from the saved starting positions, with min_dist=0.1.
graph_15 = baseline["connectivity_map"]
initialization_15 = baseline["embedding_initialization"]
umap_tight = ds.embeddings.umap(graph_15, initialization_15, min_dist=0.1)Saved UMAP: min_dist=1.0, spread=2.0
Started: 2026-11-14T15:43:59.418473Z | Wall time: 5.225 s
# Draw both packings with the saved clusters.
figure, axes = plt.subplots(1, 2, figsize=(9, 4.2))
for axis, layout, title in zip(
axes, (umap, umap_tight), ("min_dist=1", "min_dist=0.1"), strict=True
):
ds.plots.embedding(
layout=layout,
color_by=cluster_refs[15],
legend_loc="on_data",
target=axis,
show_titles=False,
show=False,
)
# Label each panel with its min_dist value.
axis.set_title(title)
figure.tight_layout()
plt.show()
Started: 2026-11-14T15:44:04.645157Z | Wall time: 0.542 s
With min_dist=0.1 instead of the saved 1.0, every cluster contracts into a denser patch and the gaps between groups widen: cluster 8 detaches from cluster 1, B-cell clusters 6 and 7 separate, NK cluster 5 separates from T-cell cluster 3, and the small cluster 9 moves from beside cluster 3 to the edge of cluster 5. The graph and the clusters are the same in both panels, so the wider gaps make groups look more distinct without any change in how the cells are connected.
Compare UMAP, densMAP and t-SNE¶
densMAP adds a term to the UMAP objective that ties each cell’s spread in the layout to the distances to its neighbors in PCA space, so dense regions stay dense and cells with distant neighbors spread out.
# Lay out the graph with densMAP.
densmap = ds.embeddings.umap(graph_15, initialization_15, use_density_map=True)Started: 2026-11-14T15:44:05.188762Z | Wall time: 6.790 s
CyteArc’s t-SNE lays out the same connectivity graph, rather than computing neighbors of its own from the PCA coordinates. Computing a new t-SNE layout needs the optional sgtsnepi package from the tsne extra (Optional t-SNE); reopening a saved one does not.
# Lay out the graph with t-SNE, without its log.
tsne = ds.embeddings.tsne(graph_15, initialization_15, verbose=False)Started: 2026-11-14T15:44:11.981101Z | Wall time: 1.277 s
Draw the three layouts with the saved clusters:
# Draw the three layouts of the 15-PC graph with the saved clusters.
figure, axes = plt.subplots(1, 3, figsize=(12, 4.2))
layouts = {"UMAP": umap, "densMAP": densmap, "t-SNE": tsne}
for axis, (method, layout) in zip(axes, layouts.items(), strict=True):
ds.plots.embedding(
layout=layout,
color_by=cluster_refs[15],
legend_loc="on_data",
target=axis,
show_titles=False,
show=False,
)
# Label each panel with its layout method.
axis.set_title(method)
figure.tight_layout()
plt.show()
Started: 2026-11-14T15:44:13.260444Z | Wall time: 0.905 s
All three layouts arrange the large clusters alike: T-cell clusters 1, 4 and 3 border each other with cluster 8 at the edge of cluster 1, NK cluster 5 lies below cluster 3, B-cell clusters 6 and 7 sit together, and the CD14 monocytes form a group of their own. The layouts differ in density and in where the small clusters go. densMAP packs the large clusters tightly and spreads cells whose neighbors are far away in PCA space: the platelets of cluster 12 scatter across the empty part of the panel. t-SNE spreads the large clusters into evenly filled areas and shrinks the small clusters to dots. Cluster 9 moves between the same two populations in the layouts as in the clusterings: it joins T-cell cluster 3 on 10 PCs and NK cluster 5 on 30 PCs, and it sits beside cluster 3 in UMAP and densMAP but at the edge of cluster 5 in t-SNE and in UMAP with min_dist=0.1. A small cluster’s place in one layout can therefore show only one of the populations it resembles.
Continue with the graph and the clusters¶
Build the neighbor graph one stage at a time to check it and compare neighbor counts, then compare Leiden resolutions and the Paris hierarchy on the same cells.
- Traag, V. A., Waltman, L., & van Eck, N. J. (2019). From Louvain to Leiden: guaranteeing well-connected communities. Scientific Reports, 9(1). 10.1038/s41598-019-41695-z