Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `tests/test_multimodal_tutorial.py` keeps the two scripts' label lists equal,
and the smoke suite checks the figure's layout at the width the paper uses.

- **Plots follow a categorical column's order, so a lineage-ordered `dot_plot` is
possible, and `reorder_ident` has an effect (#143).** In Seurat the order of a
factor's levels decides the order of the groups in `DotPlot` and `VlnPlot`.
`dot_plot`, `vln_plot`, `dim_plot`, `feature_scatter`, `do_heatmap` and
`ridge_plot` sorted the groups themselves, whatever the categories said, so after
`obj.reorder_ident("score")` they still drew Alpha, Mu, Zeta.
- A categorical column, or the active identity, is drawn in its category order. The
colours follow, as `hue_pal` is assigned in that order in R.
- Categories nobody chose are not an order, so they are not followed.
`pd.Categorical(values)` and `rename_idents` leave the string-sorted categories
"1", "10", "2", and those still sort numbers first, then names, as before.
- Categories with no cells are not drawn, and a missing value is still last.
- Nothing changes for an existing workflow: `find_clusters` already orders its
categories numbers then names, and no tutorial sets a category order.
- `image_dim_plot` and `spatial_dim_plot` still sort alphabetically, which
`ROADMAP.md` now lists.

- **`dim_heatmap`, the plots that take `layer=`, and `add_module_score` read the wrong
rows of `scale.data` (#140).** `scale_data()` scales only the variable features
unless it is given others, so row *i* of `scale.data` is not feature *i* of the
Expand Down
15 changes: 9 additions & 6 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -1432,12 +1432,15 @@ Candidates, not commitments. Each says why it is open.
`run_umap` (umap-learn) raise a bare `ModuleNotFoundError` rather than naming the
extra to install. It has been this way since 1.2.0 at least. A package change, so
it ships with the next release.
- **`vln_plot` group order and median bar.** Seurat's `VlnPlot` orders groups by
factor level; `vln_plot` sorts them with `ident_sort_key` and ignores a
categorical order, and it always draws a median bar, which Seurat does not.
Following Seurat would change existing plots, so it waits for a release that can
say so, if it happens at all. The CITE-seq tutorial works around it with a fixed
list (#138).
- **`vln_plot`'s median bar.** It always draws one, which Seurat's `VlnPlot` does
not. Dropping it would change existing plots, so it waits for a release that can
say so, if it happens at all. The CITE-seq tutorial's R panel draws the bar to
match (#138). Group order is no longer part of this: the plots follow a categorical
column's categories since the fix for #143.
- **Spatial plots still sort groups alphabetically.** `image_dim_plot` and
`spatial_dim_plot` use a plain `sorted()`, so they ignore a categorical's order and
put "10" before "2", unlike the other group plots. Changing it would move committed
spatial figures.
- **Seurat's next release.** Seurat's `main` has fixes that are not in 5.5.1, the
version every R reference here was taken on, to functions the tutorials compare
against: `Radius()` on a `VisiumV2` (#10454), `FindSpatiallyVariableFeatures` and
Expand Down
152 changes: 152 additions & 0 deletions tests/test_plot_group_order.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
``DimPlot`` and friends draw such identities without complaint.
"""
import numpy as np
import pandas as pd
import pytest
import scipy.sparse as sp

Expand Down Expand Up @@ -97,3 +98,154 @@ def test_split_by_a_column_of_numbers_and_names(mixed):
assert titles == ["9", "10", "B"]
finally:
plt.close(fig)


# ---------------------------------------------------------------------------
# A categorical's own order
# ---------------------------------------------------------------------------
# R draws a factor's levels in the order they are declared, so a lineage-ordered
# DotPlot is a matter of setting the levels, and ReorderIdent changes the plots by
# changing them. dot_plot and vln_plot sorted the groups instead, whatever the
# categories said, and so did the four other plots that colour or lay out by group.

DECLARED = ["Zeta", "Mu", "Alpha"] # deliberately not alphabetical


@pytest.fixture(scope="module")
def declared():
pytest.importorskip("matplotlib")
rng = np.random.default_rng(1)
n_genes, n_cells = 20, 90
o = tc.create_truecell_object(
counts=sp.csc_matrix(rng.poisson(2.0, size=(n_genes, n_cells)).astype(float)),
feature_names=[f"G{i:02d}" for i in range(n_genes)],
cell_names=[f"C{i:03d}" for i in range(n_cells)], project="declared",
)
tc.normalize_data(o)
tc.find_variable_features(o, nfeatures=15)
tc.scale_data(o, features=o.assays["RNA"]._all_feature_names)
tc.run_pca(o, n_pcs=6)
tc.run_umap(o, dims=range(5), seed=42)
labels = rng.choice(DECLARED, n_cells)
# An unordered categorical with its categories set, which is how Scanpy users do it.
o.meta_data["ct"] = pd.Categorical(labels, categories=DECLARED)
o.idents = pd.Categorical(labels, categories=DECLARED)
return o


PLOTS = [
("dim_plot", lambda o, g: tc.dim_plot(o, group_by=g, label=False), lambda f: _legend(f.axes[0])),
("vln_plot", lambda o, g: tc.vln_plot(o, features=["G00"], group_by=g), lambda f: _xticks(f.axes[0])),
("feature_scatter", lambda o, g: tc.feature_scatter(o, "G00", "G01", group_by=g),
lambda f: _legend(f.axes[0])),
("do_heatmap", lambda o, g: tc.do_heatmap(o, features=["G00", "G01"], group_by=g),
lambda f: [t.get_text() for t in f.axes[0].texts]),
("ridge_plot", lambda o, g: tc.ridge_plot(o, features=["G00"], group_by=g),
lambda f: _yticks(f.axes[0])[::-1]),
("dot_plot", lambda o, g: tc.dot_plot(o, features=["G00", "G01"], group_by=g),
lambda f: _yticks(f.axes[0])),
]


@pytest.mark.parametrize("group_by", [None, "ct"], ids=["active identity", "metadata column"])
@pytest.mark.parametrize("name,call,read", PLOTS, ids=[p[0] for p in PLOTS])
def test_groups_are_drawn_in_their_categories_order(declared, name, call, read, group_by):
plt = pytest.importorskip("matplotlib.pyplot")
fig = call(declared, group_by)
try:
assert read(fig) == DECLARED, name
finally:
plt.close(fig)


@pytest.mark.parametrize("name,call,read", [PLOTS[1], PLOTS[5]], ids=["vln_plot", "dot_plot"])
def test_reorder_ident_changes_the_plots(name, call, read):
"""ReorderIdent sorts the levels by a per-identity summary, so the plots move with it."""
plt = pytest.importorskip("matplotlib.pyplot")
rng = np.random.default_rng(2)
o = tc.create_truecell_object(
counts=sp.csc_matrix(rng.poisson(2.0, size=(20, 60)).astype(float)),
feature_names=[f"G{i:02d}" for i in range(20)], cell_names=[f"C{i:03d}" for i in range(60)])
tc.normalize_data(o)
labels = np.array(["Alpha", "Mu", "Zeta"] * 20)
o.idents = pd.Categorical(labels)
o.meta_data["score"] = pd.Series(labels).map({"Zeta": 0.0, "Mu": 1.0, "Alpha": 2.0}).to_numpy() \
+ rng.normal(scale=0.1, size=60)
fig = call(o, None)
try:
assert read(fig) == ["Alpha", "Mu", "Zeta"] # before: the sorted default
finally:
plt.close(fig)
o.reorder_ident("score")
assert list(o.idents.categories) == DECLARED
fig = call(o, None)
try:
assert read(fig) == DECLARED
finally:
plt.close(fig)


def _levels(values, categories=None, ordered=False, column=True):
"""`_group_levels` on a one-column object, with a categorical meta_data column or idents."""
from truecell.plotting import _group_levels

class Obj:
pass

obj = Obj()
col = pd.Categorical(values, categories=categories, ordered=ordered)
obj.meta_data = pd.DataFrame({"g": col})
obj.idents = col
groups = np.array([str(v) for v in values])
return (_group_levels(obj, "g", groups), _group_levels(obj, None, groups))


@pytest.mark.parametrize("categories,expected", [
(["B", "A", "C"], ["B", "A", "C"]),
# numeric-looking labels in a deliberate numeric order, as find_clusters leaves them
(["0", "1", "2", "10", "11"], ["0", "1", "2", "10", "11"]),
(["10", "2", "1"], ["10", "2", "1"]), # a deliberate reverse, not the default
])
def test_a_declared_order_is_followed(categories, expected):
values = list(categories) * 2
assert _levels(values, categories) == (expected, expected)


def test_the_default_sorted_categories_say_nothing_about_the_order_wanted():
"""`pd.Categorical(["10", "2", "1"])` and `rename_idents` leave string-sorted categories:
"1", "10", "2". Those are not an order anyone chose, so numbers sort as numbers."""
for values in (["10", "2", "1", "B", "T cell"], ["2", "10", "1"]):
cat = pd.Categorical(values)
assert list(cat.categories) == sorted(cat.categories) # the premise
by_column, by_ident = _levels(values)
assert by_column == by_ident == sorted(values, key=ident_sort_key)
assert _levels(["10", "2", "1"])[0] == ["1", "2", "10"]


def test_a_category_no_cell_has_is_not_drawn():
assert _levels(["B", "B", "A"], categories=["C", "B", "A"]) == (["B", "A"], ["B", "A"])


def test_a_missing_value_is_still_a_group_and_comes_last():
from truecell.plotting import _group_levels

class Obj:
pass

obj = Obj()
obj.meta_data = pd.DataFrame({"g": pd.Categorical(["B", None, "A"], categories=["B", "A"])})
groups = obj.meta_data["g"].astype(str).to_numpy()
levels = _group_levels(obj, "g", groups)
# `astype(str)` leaves the missing value "nan" on pandas 2 and NaN on pandas 3.
assert levels[:2] == ["B", "A"] and len(levels) == 3 and str(levels[2]) == "nan"


def test_a_plain_column_is_still_sorted_numbers_first():
from truecell.plotting import _group_levels

class Obj:
pass

obj = Obj()
obj.meta_data = pd.DataFrame({"g": ["10", "B", "2", "1"]})
assert _group_levels(obj, "g", obj.meta_data["g"].to_numpy()) == ["1", "2", "10", "B"]
57 changes: 46 additions & 11 deletions truecell/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,36 @@ def _get_groups(obj, group_by: Optional[str]) -> np.ndarray:
raise KeyError(f"group_by column '{group_by}' not found in meta_data.")


def _group_levels(obj, group_by: str | None, groups: np.ndarray) -> list[str]:
"""The groups to draw, in the order to draw them.

R draws a factor's levels in the order they are declared, so ``DotPlot`` and
``VlnPlot`` follow ``factor(x, levels = ...)``, and ``ReorderIdent`` changes the
plots by changing the levels. A categorical's own order is followed here too.

The one exception is categories that are only the sorted order every categorical
starts with, which is what ``pd.Categorical(values)`` and ``rename_idents`` leave.
That order says nothing about the order wanted, and string order puts "10" before
"2", so those are sorted as any other column is: numbers numerically, then names.
Groups no cell belongs to are not drawn, as ggplot drops unused levels.
"""
present = set(groups)
column = obj.idents if group_by is None else obj.meta_data[group_by]
categories = None
if isinstance(column, pd.Categorical):
categories = column.categories
elif isinstance(column.dtype, pd.CategoricalDtype):
categories = column.cat.categories
if categories is not None:
declared = [str(c) for c in categories]
if declared != sorted(declared):
# A missing value comes through `astype(str)` as "nan" or as NaN, by pandas
# version, and no category names it: it goes last, as it always has.
return ([g for g in declared if g in present]
+ sorted(present - set(declared), key=ident_sort_key))
return sorted(present, key=ident_sort_key)


def _strip_axes(ax):
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
Expand Down Expand Up @@ -617,7 +647,8 @@ def vln_plot(
----------
obj : Truecell object
features : gene name(s) or metadata column(s)
group_by : metadata column used for grouping (default: active idents)
group_by : metadata column used for grouping (default: active idents). A categorical
column is drawn in its category order, as R draws a factor's levels.
pt_size : marker area for the jittered points, in matplotlib's units.
``None`` (default) follows Seurat's ``AutoPointSize``, which
shows points and shrinks them as the cell count grows; ``0``
Expand All @@ -643,7 +674,7 @@ def vln_plot(
features = [features]

groups = _get_groups(obj, group_by)
unique = sorted(set(groups), key=ident_sort_key)
unique = _group_levels(obj, group_by, groups)
if pt_size is None:
pt_size = _auto_point_size(len(groups))

Expand Down Expand Up @@ -910,7 +941,8 @@ def dim_plot(
Parameters
----------
reduction : which reduction to use ("umap", "pca", …)
group_by : metadata column for colouring (default: active idents)
group_by : metadata column for colouring (default: active idents). A categorical
column is drawn in its category order, as R draws a factor's levels.
label : label each group at the median of its cells' coordinates, in
each panel, as Seurat's ``LabelClusters`` does
label_size: font size for the group labels (default: scales with the theme)
Expand Down Expand Up @@ -938,7 +970,7 @@ def dim_plot(
plt = _mpl()
emb = _get_embedding(obj, reduction)
groups = _get_groups(obj, group_by)
unique = sorted(set(groups), key=ident_sort_key)
unique = _group_levels(obj, group_by, groups)
colors = palette or _palette(len(unique))
# On the whole embedding, not the per-group slice: the decision is about the
# figure's total path count, and a 200k-cell object split across 20 clusters
Expand Down Expand Up @@ -1091,15 +1123,16 @@ def feature_scatter(
Parameters
----------
feature1 / feature2 : gene names or metadata columns
group_by : column for colouring; default: active idents
group_by : column for colouring; default: active idents. A categorical column is
coloured in its category order, as R colours a factor's levels.
raster : draw the cells as a raster layer instead of vector paths.
``None`` (default) rasterises above 100,000 cells.
"""
plt = _mpl()
x = _get_expression(obj, feature1, assay, layer)
y = _get_expression(obj, feature2, assay, layer)
groups = _get_groups(obj, group_by)
unique = sorted(set(groups), key=ident_sort_key)
unique = _group_levels(obj, group_by, groups)
colors = palette or _palette(len(unique))
rast = _should_raster(raster, len(x))

Expand Down Expand Up @@ -1475,7 +1508,8 @@ def do_heatmap(
Parameters
----------
features : list of gene names to show as rows
group_by : column used to sort and colour cells (default: active idents)
group_by : column used to sort and colour cells (default: active idents). A
categorical column is ordered by its categories, as R orders a factor's levels.
layer : which data layer to use (default: "scale.data")
label : annotate cluster boundaries with group names
cells : restrict to these cells *and* show them in this exact order,
Expand All @@ -1490,7 +1524,7 @@ def do_heatmap(
mat, all_feats = _resolve_layer(assay_obj, layer)

groups = _get_groups(obj, group_by)
unique = sorted(set(groups), key=ident_sort_key)
unique = _group_levels(obj, group_by, groups)
colors = palette or _palette(len(unique))

if cells is None:
Expand Down Expand Up @@ -1602,7 +1636,7 @@ def ridge_plot(
features = [features]

groups = _get_groups(obj, group_by)
unique = sorted(set(groups), key=ident_sort_key)[::-1]
unique = _group_levels(obj, group_by, groups)[::-1]
colors = palette or _palette(len(unique))

nrow, nc = _subplot_grid(len(features), ncol)
Expand Down Expand Up @@ -1734,7 +1768,8 @@ def dot_plot(
Parameters
----------
features : gene name(s) to plot (x-axis).
group_by : metadata column for grouping (default: active idents, y-axis).
group_by : metadata column for grouping (default: active idents, y-axis). A
categorical column is drawn in its category order, as R draws a factor's levels.
scale : z-score each feature's average expression across groups.
col_min/col_max : colour scale limits for the scaled average expression.
dot_min : minimum fraction-expressing to draw a dot.
Expand All @@ -1747,7 +1782,7 @@ def dot_plot(
features = [features]

groups = _get_groups(obj, group_by)
unique = sorted(set(groups), key=ident_sort_key)
unique = _group_levels(obj, group_by, groups)

# Per (feature, group): average expression and fraction expressing.
avg = np.zeros((len(features), len(unique)))
Expand Down
Loading