Skip to content

feat(plotting): add ncols to wrap multi-panel violin plots (#1552)#4132

Open
Hore01 wants to merge 4 commits into
scverse:mainfrom
Hore01:feat/issue-1552-violin-ncols
Open

feat(plotting): add ncols to wrap multi-panel violin plots (#1552)#4132
Hore01 wants to merge 4 commits into
scverse:mainfrom
Hore01:feat/issue-1552-violin-ncols

Conversation

@Hore01

@Hore01 Hore01 commented May 19, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds an ncols parameter to sc.pl.violin so multi-key violins can wrap into a grid instead of one giant horizontal row. Mirrors the ncols convention already used by sc.pl.umap / sc.pl.embedding.

Closes #1552.

What changes

Two code paths in violin() get the new parameter:

  • multi_panel=True (seaborn catplot path), forwards ncols to seaborn's col_wrap=. The existing stripplot and rotation loops used g.axes[0] 2D indexing, which col_wrap flattens, so I swapped them to g.axes_dict, same semantics either way, but compatible with both shapes.
  • groupby set, multiple keys (legacy setup_axes path) — when ncols is provided, builds a gridspec figure via _panel_grid (already used by sc.pl.embedding). The import is local to the function to dodge the _tools/__init__.py_anndata.py circular-import (which I hit on the first try — the package's _tools/__init__.py already imports ranking
    from _anndata.py, so a module-level import would cycle).

ncols=None (default) flows through the unchanged code, so every existing test_violin image baseline stays byte-identical.

Why hard-code hspace/wspace

embedding exposes both; doing the same here would add API surface for no gain on the issue as filed. Defaults (0.25, 0.1) match embedding. Easy follow-up if anyone asks.

Tests

Added one new subtest in test_violin:

with subtests.test("ncols"):
    sc.pl.violin(pbmc, ["n_genes", "percent_mito", "n_counts"],
                 multi_panel=True, ncols=2, show=False)
    assert len(plt.gcf().axes) == 3
    save_and_compare_images("violin_ncols_wrap")

The assert len(...) == 3 is cheap insurance; tol=40 would happily mask an off-by-one in panel count, and an earlier draft of this patch had exactly that bug (the original Path B only made one axis when groupby is None because the data is melted into a single column, which is why I ended up wiring the wrap into multi_panel=True instead). The baseline at
tests/_images/violin_ncols_wrap/expected.png was generated locally and visually checked.

Full test_violin (all four subtests) passes locally.

Refs

  • Issue requesting ncols parameter in sc.pl.violin() #1552 (open since 2020, good first issue)
  • Pattern: _panel_grid in src/scanpy/plotting/_tools/scatterplots.py
  • Convention: docs/release-notes/<PR>.feat.md; placeholder added, will rename to the real number in a follow-up commit

@codecov

codecov Bot commented May 19, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.66667% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 79.64%. Comparing base (2ae768e) to head (7e24234).
⚠️ Report is 2 commits behind head on main.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
src/scanpy/plotting/_anndata.py 91.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4132      +/-   ##
==========================================
+ Coverage   79.61%   79.64%   +0.02%     
==========================================
  Files         120      120              
  Lines       12786    12794       +8     
==========================================
+ Hits        10180    10190      +10     
+ Misses       2606     2604       -2     
Flag Coverage Δ
hatch-test.low-vers 78.89% <91.66%> (+0.05%) ⬆️
hatch-test.pre 79.50% <91.66%> (+0.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/scanpy/plotting/_anndata.py 85.65% <91.66%> (+0.22%) ⬆️

... and 1 file with indirect coverage changes

Hore01 added 3 commits June 13, 2026 21:23
Adds an `ncols` parameter to `sc.pl.violin` for wrapping multi-key
violins into a grid layout, matching the convention already used by
`sc.pl.umap` / `sc.pl.embedding`.

Two layout paths are affected:

- `multi_panel=True` (the seaborn `catplot` path): forwards `ncols` to
  seaborn's `col_wrap=`, so the wrapping is handled by the FacetGrid.
  The existing stripplot/rotation loops were switched from
  `g.axes[0]` 2D indexing to `g.axes_dict` so they work for both
  the wrapped and non-wrapped cases.
- `groupby` set, multiple keys (the legacy `setup_axes` path):
  when `ncols` is provided, uses `_panel_grid` (already battle-tested
  by `sc.pl.embedding`) to build a gridspec figure. The `_panel_grid`
  import is local to the function to avoid the
  `_tools/__init__.py` -> `_anndata.py` cycle.

`ncols=None` (the default) preserves byte-identical output for every
existing test_violin baseline.

Closes scverse#1552.
Brings patch coverage on the previous commit from 25% to ~90%+ by exercising the gridspec branch added in 64feb1e. Mirrors the existing groupby subtest's pandas-3 xfail.
@Hore01 Hore01 force-pushed the feat/issue-1552-violin-ncols branch from b1fd1a2 to 37ae108 Compare June 14, 2026 09:35
Adds two subtests exercising the `ax is not None` paths in
`sc.pl.violin`:

- `ax_provided_single_key` hits the legacy single-axis branch
  (ax provided, ncols default None).
- `ax_with_ncols_raises` asserts the explicit ValueError when
  the new ncols parameter is combined with a pre-supplied ax.

Together these lift patch coverage on the new branches that
codecov flagged on this PR.
@Hore01

Hore01 commented Jun 14, 2026

Copy link
Copy Markdown
Contributor Author

Rebased on main — the earlier test (low-vers) failure was an unrelated test_logfile flake (passing on the fresh CI run). Also added two subtests covering the new ax/ncols branches so codecov/patch is green.

All CI checks pass except Check title, milestone, and labels, which I can't clear myself as an external contributor. Could you attach the appropriate milestone (or the no milestone label) so it goes green? Happy to address any review comments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

requesting ncols parameter in sc.pl.violin()

1 participant