From edca55aa285c166e736d23ccfc65f3e041837d7e Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sat, 21 Nov 2026 23:25:59 -0500 Subject: [PATCH 01/58] release: 1.1.1 release form; seed two gallery examples README images pinned to the v1.1.1 tag (13 URLs). The k-means panel of plot_colorbar.py and the UMAP panel of plot_digits.py came out different on every docs build; both now pass random_state=0, so the gallery is the same from build to build apart from examples that read live data. Changelog entry, release notes draft and session notes. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- CHANGELOG.md | 9 ++++- examples/plot_colorbar.py | 4 ++- examples/plot_digits.py | 5 ++- notes/release_notes_v1.1.1_draft.md | 37 ++++++++++++++++++++ notes/session_2026-11-21_release-1.1.1.md | 41 +++++++++++++++++++++++ readme.md | 26 +++++++------- 6 files changed, 106 insertions(+), 16 deletions(-) create mode 100644 notes/release_notes_v1.1.1_draft.md diff --git a/CHANGELOG.md b/CHANGELOG.md index e6879ec6a..36ee21338 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -75,13 +75,20 @@ draws into a figure the caller built, found by executing notebooks with same glyphs are still reached through 'Hiragino Sans'); a font named with `font=`, and a font found to be the only one covering the text, are kept regardless. - - **A Yahoo Finance rate limit is reported as one.** When Yahoo throttles an address it answers HTTP 429 with a plain-text body, which `hyp.load('yahoo:')` reported as "returned a non-JSON response (HTTP 429) ... JSONDecodeError". The error now says that Yahoo is rate-limiting the address and to try again later. +### Documentation + +- **Two gallery examples are now seeded.** The k-means panel of + `plot_colorbar.py` and the UMAP panel of `plot_digits.py` came out + different on every docs build (cluster colors permuted; a different UMAP + layout). Both now pass `random_state=0`, so every gallery figure that + does not read live data is the same from build to build. + ### Documented limitations - **Some text can still log under matplotlib 3.11.** The line above is diff --git a/examples/plot_colorbar.py b/examples/plot_colorbar.py index e87ffd770..80cee79c5 100644 --- a/examples/plot_colorbar.py +++ b/examples/plot_colorbar.py @@ -30,6 +30,8 @@ # Discrete groups (here, k-means clusters) get a segmented colorbar with # one tick/block per group instead of a continuous gradient. A dict lets # you set a label or move the colorbar to another side of the figure. +# (k-means starts from random centers; ``random_state`` keeps the cluster +# numbering, and so the colors, the same from run to run.) -hyp.plot(data, '.', n_clusters=4, +hyp.plot(data, '.', n_clusters=4, random_state=0, colorbar={'label': 'cluster', 'location': 'right'}) diff --git a/examples/plot_digits.py b/examples/plot_digits.py index b34ceaa82..e29f6585f 100644 --- a/examples/plot_digits.py +++ b/examples/plot_digits.py @@ -38,4 +38,7 @@ # %% # ... and with UMAP, which is faster and keeps more of the global layout. -hyp.plot(data, '.', reduce='UMAP', hue=hue, ndims=2, legend=True) +# UMAP's layout is random unless it is seeded; ``random_state`` makes the +# figure the same on every run. +hyp.plot(data, '.', reduce='UMAP', random_state=0, hue=hue, ndims=2, + legend=True) diff --git a/notes/release_notes_v1.1.1_draft.md b/notes/release_notes_v1.1.1_draft.md new file mode 100644 index 000000000..6786d507e --- /dev/null +++ b/notes/release_notes_v1.1.1_draft.md @@ -0,0 +1,37 @@ +# HyperTools 1.1.1 + +A patch release with no API changes. It fixes noise and side effects met when `hyp.plot` draws into a figure the caller built (`ax=`), found by executing notebooks with `jupyter nbconvert` under matplotlib 3.11, and one misleading error message from the Yahoo Finance loader. + +Every change is listed in the [changelog](https://github.com/ContextLab/hypertools/blob/v1.1.1/CHANGELOG.md); these notes summarize it. + +## Install + +```bash +pip install --upgrade hypertools +``` + +Python 3.10 through 3.13. Extras are unchanged from 1.1.0. + +## Fixed + +- **The backend warning is issued once, and only when it applies ([#290](https://github.com/ContextLab/hypertools/issues/290)).** When hypertools cannot set up an interactive matplotlib backend at import (for example in a notebook kernel without `ipympl`), `hyp.plot` repeated the warning on every call, including static plots and calls that show no live figure. It is now issued only by a call that displays an animated or interactive plot that matplotlib renders, and once per session per message. +- **`hyp.plot(..., ax=ax)` leaves the layout of the caller's figure alone ([#291](https://github.com/ContextLab/hypertools/issues/291)).** Static plots ended with `plt.tight_layout()` even when the caller passed its own axes, which moved every axes of the figure, discarded `subplots_adjust` margins, replaced a `layout='constrained'` engine, and acted on pyplot's current figure rather than the one that owns `ax`. A figure the caller built is now left as the caller arranged it. Figures hypertools makes itself (its own figure, a `panels=` grid, a `hyp.subplots` grid) are laid out as before. +- **A legend or title added to the caller's axes is fitted automatically, inside that axes' own room.** Through 1.1.0 a `legend=` beside a caller's axes was fitted by widening the caller's figure, which stretched its other axes and switched off its layout engine. Now, when the figure is drawn, only the axes passed as `ax=` is narrowed just far enough that its legend ends before the canvas edge or the next panel, and lowered just far enough that its title stays on the canvas. No call is needed, and the fit follows a later `fig.tight_layout()`, `fig.subplots_adjust(...)`, resize or save. A legend with no room beside the axes is drawn inside it; one too large for its panel either way is left in place with a `UserWarning` naming the remedies. +- **No `findfont` log lines for ordinary text under matplotlib 3.11 ([#292](https://github.com/ContextLab/hypertools/issues/292)).** matplotlib 3.11 logs a line each time a family in the font list has no face at a text's exact weight; one of the fallback families hypertools listed has no regular face on macOS, so every figure logged the line several times. Fallback families with no regular-weight face are now left out of the list. +- **A Yahoo Finance rate limit is reported as one.** `hyp.load('yahoo:')` reported an HTTP 429 from Yahoo as a JSON decoding failure. The error now says that Yahoo is rate-limiting the address and to try again later. + +## Upgrading from 1.1.0 + +- **If you relied on the automatic `tight_layout`** of a figure made with `plt.subplots`, call `fig.tight_layout()` after plotting, create the figure with `layout='constrained'`, or build the grid with `hyp.subplots`. +- On an axes whose legend or title was fitted, `ax.get_position()` reports the position of the last draw (the fit is an axes locator, recomputed on each draw). + +## Known limitations + +- The automatic fit does not detect an inset or other axes placed by hand where the legend goes, or a legend over the tick labels of its own axes' twin. +- Bold or other non-regular text can still log `findfont` lines under matplotlib 3.11 when an installed fallback family ships a regular face only; see "Documented limitations" in the changelog. + +## Links + +- Documentation: https://hypertools.readthedocs.io/en/stable/ +- Changelog: https://github.com/ContextLab/hypertools/blob/v1.1.1/CHANGELOG.md +- PyPI: https://pypi.org/project/hypertools/1.1.1/ diff --git a/notes/session_2026-11-21_release-1.1.1.md b/notes/session_2026-11-21_release-1.1.1.md index f52c6f9c5..0894230ab 100644 --- a/notes/session_2026-11-21_release-1.1.1.md +++ b/notes/session_2026-11-21_release-1.1.1.md @@ -305,3 +305,44 @@ pass on matplotlib 3.10.8 and 3.11.2. - Sphinx `-b html -W -E -a` with every gallery example re-executed, at 49165c09: build succeeded. - `ruff check`: all checks passed. + +## Gallery rebuild and before/after review (2026-11-21, late evening) + +Request: rebuild the gallery, review before/after for ALL figures (own review +plus an independent one, ideally Codex), and build a draft release. Working +unattended; the user is on a phone. + +- PR #294 (automatic legend/title fit) merged as e3abb840 with all CI green. +- Built the gallery in release form from e3abb840 (51 of 51 examples + executed, sphinx exit 0, 32 min). Compared it with two baselines using + a scratch script (pixel statistics on every PNG, every GIF frame, every + MP4 frame, plotly payload hashes): the published 1.1.0 gallery + (`docs-gallery-v1.1.0`, 519b4af2) and the pre-fit 1.1.1 gallery (built + from 514a12cb). +- Result: 89 figures + 51 thumbnails. 87 of 89 byte-identical to the + pre-fit build; 85 of 89 to 1.1.0. The differences: + - `plot_colorbar_002.png`: k-means unseeded, cluster colors permuted on + every build (same points). Not from the code change. + - `plot_digits_003.png`: UMAP unseeded, new layout every build. + - `animate_market_sectors_001.gif/.mp4` (vs 1.1.0 only): live Yahoo data, + one more month (ends October 31, 2026 instead of September 30, 2026). +- No gallery example puts a legend on an axes the example made itself (five + use `ax=`, with titles only, which already fit), so the fit changing no + gallery figure is expected. My earlier guess that four examples would + render differently was wrong. +- Fix: both examples now pass `random_state=0` (the library's own argument; + passing UMAP's `random_state` through the `reduce` dict works too but + prints umap's n_jobs warning). Verified: two runs each give identical + figures, no warnings with `-W error::UserWarning`. +- Release form: README images flipped to `v1.1.1` (13 URLs), tutorial + install cells already correct (migrator: 76 of 76). NOTE: the migrator + must run on the `master` branch; on any other branch it retargets the + tutorials to that branch. +- Plan: commit on local `master` (not pushed to `master`; pushed as + `release/1.1.1` so nothing on `master` changes before the user's go), + rebuild the gallery from that commit, repeat the comparison, independent + review (Codex + fresh subagent), publish the pre-built gallery (keeping + the old commit c90dd87e reachable on a `docs-gallery-v1.1.1-prev` branch + because `master`'s docs build fetches it by id), record it, publish the + notebooks, build wheel + sdist, create a DRAFT GitHub release (no tag). + Tag, PyPI and the `master` push wait for the user's go. diff --git a/readme.md b/readme.md index e6b110f5f..c0bea7f7c 100644 --- a/readme.md +++ b/readme.md @@ -1,4 +1,4 @@ -![Hypertools logo](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.0/images/hypercube.png) +![Hypertools logo](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/hypercube.png) [![Tests](https://img.shields.io/github/actions/workflow/status/ContextLab/hypertools/test.yml?label=tests)](https://github.com/ContextLab/hypertools/actions/workflows/test.yml) [![Documentation Status](https://readthedocs.org/projects/hypertools/badge/?version=latest)](https://hypertools.readthedocs.io/en/latest/?badge=latest) @@ -7,7 +7,7 @@ "_To deal with hyper-planes in a 14 dimensional space, visualize a 3D space and say 'fourteen' very loudly. Everyone does it._" - Geoff Hinton -![Hypertools example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.0/images/story_trajectories.gif) +![Hypertools example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/story_trajectories.gif) ## Overview @@ -52,7 +52,7 @@ the link under a clip for the full code and the full-length animation. Six stock-market sectors, each reduced to 3-D on its own and then hyperaligned into a shared space, with a heavier path for the market as a whole. -![Market sectors example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.0/images/tour_market_sectors.gif) +![Market sectors example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/tour_market_sectors.gif) [Tutorial: market sectors](https://hypertools.readthedocs.io/en/latest/tutorials/market_sectors.html) @@ -62,7 +62,7 @@ Give `hyp.plot` a list of strings and it embeds them, projects them into 2-D or 3-D, and plots the result. Here a paragraph about each of five paintings becomes its own cloud, drawn in a color pulled from the canvas itself. -![Painting embeddings example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.0/images/tour_painting_embeddings.gif) +![Painting embeddings example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/tour_painting_embeddings.gif) [Tutorial: painting embeddings](https://hypertools.readthedocs.io/en/latest/tutorials/painting_embeddings.html) @@ -72,7 +72,7 @@ becomes its own cloud, drawn in a color pulled from the canvas itself. Tea-Party from *Alice's Adventures in Wonderland*: each segment is one turn of the conversation, colored by speaker and placed by what is being said. -![Conversation example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.0/images/tour_conversation_shape.gif) +![Conversation example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/tour_conversation_shape.gif) [Tutorial: the shape of a conversation](https://hypertools.readthedocs.io/en/latest/tutorials/conversation_shape.html) @@ -81,7 +81,7 @@ the conversation, colored by speaker and placed by what is being said. Monthly temperatures in 20 cities around the globe, from 1875 to 2013, drawn as a single path and colored by the average temperature that month. -![Weather example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.0/images/tour_weather_decades.gif) +![Weather example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/tour_weather_decades.gif) [Tutorial: weather across the decades](https://hypertools.readthedocs.io/en/latest/tutorials/weather_decades.html) @@ -97,7 +97,7 @@ shapes = [hyp.load(n) for n in names] hyp.plot(shapes, '.', color='k', animate='morph', title=names) ``` -![Morph example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.0/images/tour_morph_shapes_zoo.gif) +![Morph example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/tour_morph_shapes_zoo.gif) [Tutorial: morphing the shapes zoo](https://hypertools.readthedocs.io/en/latest/tutorials/morph_shapes_zoo.html) @@ -256,7 +256,7 @@ list_of_labels = ['A'] * 300 + ['B'] * 300 # one label per observation hyp.plot(list_of_arrays, animate=True, hue=list_of_labels) ``` -![Plot example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.0/images/plot.gif) +![Plot example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/plot.gif) ## Align @@ -275,11 +275,11 @@ hyp.plot(list_of_arrays, align='hyper') ### BEFORE -![Align before example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.0/images/align_before.gif) +![Align before example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/align_before.gif) ### AFTER -![Align after example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.0/images/align_after.gif) +![Align after example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/align_after.gif) ## Cluster @@ -299,7 +299,7 @@ array = np.vstack([rng.standard_normal((100, 3)) + offset hyp.plot(array, 'o', cluster='GaussianMixture', n_clusters=3) ``` -![Cluster Example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.0/images/cluster_example.png) +![Cluster Example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/cluster_example.png) ## Surfaces @@ -317,7 +317,7 @@ blob_b = rng.standard_normal((100, 3)) + [4, 0, 0] hyp.plot([blob_a, blob_b], '.', surface=True) ``` -![Surface Example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.0/images/surface_example.png) +![Surface Example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/surface_example.png) ## Describe @@ -332,4 +332,4 @@ list_of_arrays = [np.cumsum(rng.standard_normal((200, 20)), axis=0) hyp.describe(list_of_arrays, reduce='PCA', max_dims=14) ``` -![Describe Example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.0/images/describe_example.png) +![Describe Example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/describe_example.png) From a7193bb105e37283a013b6b4b94fe29e9f484318 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sat, 21 Nov 2026 23:29:41 -0500 Subject: [PATCH 02/58] fix: a UMAP seeded through the reduce dict no longer warns about n_jobs umap-learn forces n_jobs=1 when seeded and warns that it did. hypertools passed n_jobs=1 itself for the top-level random_state= on the bare-name form only; reduce={'model': 'UMAP', 'kwargs': {'random_state': 0}} (the form several gallery examples use) and the dict form with a top-level seed still drew the warning. An explicit n_jobs still gets umap's warning. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- CHANGELOG.md | 8 ++++++ hypertools/reduce/reduce.py | 32 +++++++++++++++++------ notes/session_2026-11-21_release-1.1.1.md | 9 +++++++ tests/test_reduce_third_party_warnings.py | 24 +++++++++++++++++ 4 files changed, 65 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 36ee21338..bfbecf686 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -80,6 +80,14 @@ draws into a figure the caller built, found by executing notebooks with `hyp.load('yahoo:')` reported as "returned a non-JSON response (HTTP 429) ... JSONDecodeError". The error now says that Yahoo is rate-limiting the address and to try again later. +- **A seeded UMAP no longer warns about `n_jobs`.** umap-learn runs + single-threaded whenever it is seeded and says so with "n_jobs value 1 + overridden to 1 by setting random_state". hypertools already kept that + warning away for the top-level `random_state=`; a seed passed in the + `reduce` dict (`reduce={'model': 'UMAP', 'kwargs': {'random_state': + 0}}`, as several gallery examples do) still drew it. Both forms are now + quiet and give the same embedding. A call that sets `n_jobs` itself + still gets umap's warning. ### Documentation diff --git a/hypertools/reduce/reduce.py b/hypertools/reduce/reduce.py index 09d735504..df4af78e7 100644 --- a/hypertools/reduce/reduce.py +++ b/hypertools/reduce/reduce.py @@ -328,6 +328,17 @@ def reduce(x, reduce='IncrementalPCA', ndims=None, return_model=False, and inspect.isclass(c_model) and 'random_state' in inspect.signature(c_model).parameters): c_kwargs['random_state'] = random_state + # a seeded UMAP runs single-threaded and warns "n_jobs value + # ... overridden to 1"; whoever set the seed (the user in + # 'kwargs', or the top-level random_state just injected) did + # not choose n_jobs, so pass the value umap will use anyway + # (see the same step for the bare-name form below) + if (inspect.isclass(c_model) + and getattr(c_model, '__name__', '') == 'UMAP' + and c_kwargs.get('random_state') is not None + and 'n_jobs' not in c_kwargs and len(c_args) == 0 + and 'n_jobs' in inspect.signature(c_model).parameters): + c_kwargs['n_jobs'] = 1 # construct immediately; the resulting instance flows through # the same already-constructed-instance handling below as a # bare instance passed directly as `reduce=`. An ALREADY- @@ -484,14 +495,19 @@ def reduce(x, reduce='IncrementalPCA', ndims=None, return_model=False, and 'random_state' not in model_params and 'random_state' in inspect.signature(model).parameters): model_params['random_state'] = random_state - # umap-learn forces n_jobs=1 whenever a random_state is set and - # warns that it did ("n_jobs value -1 overridden to 1 ..."), which - # would blame the user for a seed hypertools injected. Pass the - # n_jobs umap is going to use anyway, unless the user chose one. - if (getattr(model, '__name__', '') == 'UMAP' - and 'n_jobs' not in model_params - and 'n_jobs' in inspect.signature(model).parameters): - model_params['n_jobs'] = 1 + + # umap-learn forces n_jobs=1 whenever a random_state is set and warns + # that it did ("n_jobs value -1 overridden to 1 ..."). The user asked + # for a seed (top-level `random_state=`, or in the `reduce` dict's + # kwargs), not for a number of jobs, so the warning tells them nothing + # they chose: pass the n_jobs umap is going to use anyway. A user who + # set n_jobs themselves still gets umap's warning about it. + if (not model_is_instance + and getattr(model, '__name__', '') == 'UMAP' + and model_params.get('random_state') is not None + and 'n_jobs' not in model_params + and 'n_jobs' in inspect.signature(model).parameters): + model_params['n_jobs'] = 1 # sklearn TSNE's default perplexity (30) requires n_samples > 30, so # small datasets crashed on a parameter the user never set diff --git a/notes/session_2026-11-21_release-1.1.1.md b/notes/session_2026-11-21_release-1.1.1.md index 0894230ab..efc8bf1ca 100644 --- a/notes/session_2026-11-21_release-1.1.1.md +++ b/notes/session_2026-11-21_release-1.1.1.md @@ -346,3 +346,12 @@ unattended; the user is on a phone. because `master`'s docs build fetches it by id), record it, publish the notebooks, build wheel + sdist, create a DRAFT GitHub release (no tag). Tag, PyPI and the `master` push wait for the user's go. +- Found while running the examples gate: `animate_painting_embeddings.py` + and `animate_conversation.py` seed UMAP through the `reduce` dict, which + drew umap's "n_jobs value 1 overridden to 1 by setting random_state" + warning (not shown on the docs pages, but shown to anyone running the + example). Fixed in `hypertools/reduce/reduce.py`: the dict form now passes + `n_jobs=1` when the model is seeded and the caller named no `n_jobs` + (same as the bare-name form already did). Regression test in + `tests/test_reduce_third_party_warnings.py`; changelog entry. The first + gallery build from the release commit was stopped for this and restarted. diff --git a/tests/test_reduce_third_party_warnings.py b/tests/test_reduce_third_party_warnings.py index 8124317bd..d1d1c6c3f 100644 --- a/tests/test_reduce_third_party_warnings.py +++ b/tests/test_reduce_third_party_warnings.py @@ -23,6 +23,30 @@ def test_seeded_umap_does_not_warn_about_n_jobs(): assert not [m for m in w if 'n_jobs' in str(m.message)] +def test_umap_seeded_through_the_reduce_dict_does_not_warn_about_n_jobs(): + """A seed passed as ``reduce={'model': 'UMAP', 'kwargs': + {'random_state': ...}}`` (the form several gallery examples use) is the + same request as the top-level ``random_state=``: neither names n_jobs, + so neither should draw umap's n_jobs warning, and both give the same + embedding.""" + pytest.importorskip('umap') + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always') + out = hyp.reduce( + _digits400(), + reduce={'model': 'UMAP', 'kwargs': {'random_state': 0}}, ndims=3) + plotted = hyp.plot( + _digits400(), '.', + reduce={'model': 'UMAP', 'kwargs': {'random_state': 0}}, ndims=3, + show=False) + assert not [m for m in w if 'n_jobs' in str(m.message)] + assert plotted is not None + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + top = hyp.reduce(_digits400(), reduce='UMAP', ndims=3, random_state=0) + np.testing.assert_allclose(np.asarray(out), np.asarray(top)) + + def test_seeded_umap_honours_an_explicit_n_jobs(): pytest.importorskip('umap') from hypertools.reduce.common import resolve_reducer From a7dfad3aabbea643e8777f734e755052eb7b3256 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sat, 21 Nov 2026 23:32:08 -0500 Subject: [PATCH 03/58] docs: plot_shapes_zoo example draws no stray axis labels The biplane is the one shape that loads as a DataFrame (columns x, y, z), so its panel alone carried axis labels, one of them in the grid's empty cell (in the 1.1.0 gallery too). The example passes empty labels. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- CHANGELOG.md | 4 ++++ examples/plot_shapes_zoo.py | 6 +++++- notes/session_2026-11-21_release-1.1.1.md | 11 +++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bfbecf686..2f51b3350 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -96,6 +96,10 @@ draws into a figure the caller built, found by executing notebooks with different on every docs build (cluster colors permuted; a different UMAP layout). Both now pass `random_state=0`, so every gallery figure that does not read live data is the same from build to build. +- **`plot_shapes_zoo.py`: no stray axis labels.** The biplane is the one + shape that loads as a DataFrame (columns `x`, `y`, `z`), so its panel + alone carried axis labels, one of them out in the grid's empty cell. The + example now passes empty labels. ### Documented limitations diff --git a/examples/plot_shapes_zoo.py b/examples/plot_shapes_zoo.py index e63c241fb..8d060b2ba 100644 --- a/examples/plot_shapes_zoo.py +++ b/examples/plot_shapes_zoo.py @@ -25,6 +25,10 @@ # fits each panel's own reduction separately, exactly as the equivalent # per-panel hyp.plot(shape, ax=ax) loop did, since these clouds differ # enough in scale that one shared fit would be dominated by the largest. +# The biplane loads as a DataFrame with columns x, y and z, which hypertools +# would write beside that one panel as axis labels; the empty labels keep +# all seven panels alike. hyp.plot([hyp.load(shape) for shape in shapes], ',', color='k', panels=(2, 4), panel_fit='independent', - title=[shape.capitalize() for shape in shapes], size=(12, 6)) + title=[shape.capitalize() for shape in shapes], size=(12, 6), + xlabel='', ylabel='', zlabel='') diff --git a/notes/session_2026-11-21_release-1.1.1.md b/notes/session_2026-11-21_release-1.1.1.md index efc8bf1ca..c98e59d2c 100644 --- a/notes/session_2026-11-21_release-1.1.1.md +++ b/notes/session_2026-11-21_release-1.1.1.md @@ -355,3 +355,14 @@ unattended; the user is on a phone. (same as the bare-name form already did). Regression test in `tests/test_reduce_third_party_warnings.py`; changelog entry. The first gallery build from the release commit was stopped for this and restarted. +- Own review of all 89 figures (contact sheets, 117 tiles: every still, + middle and last frame of every animation): everything matches 1.1.0 + apart from the three explained cases. One defect that 1.1.0 has too: + `plot_shapes_zoo_001.png` showed stray x/y/z axis labels beside the + Biplane panel (the biplane loads as a DataFrame, the other six shapes as + arrays; column names become axis labels by design). Example now passes + `xlabel='', ylabel='', zlabel=''`. Second gallery build stopped and + restarted for this. +- Observed, left as is (faithful rendering of raw data, same as 1.1.0): + in `plot_datasets_tour_001.png` the penguins and Kaggle-iris panels are + near-lines because one unnormalized column dominates. From 46c3bb39dc6aa505c4dc8cdd4633b760c7c059d3 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 00:07:31 -0500 Subject: [PATCH 04/58] release: date 1.1.1 2026-11-22; notes on the gallery review Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- CHANGELOG.md | 2 +- notes/release_notes_v1.1.1_draft.md | 5 ++++ notes/session_2026-11-21_release-1.1.1.md | 28 +++++++++++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f51b3350..380106e68 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## 1.1.1 (2026-11-21) +## 1.1.1 (2026-11-22) A patch release: three fixes for noise and side effects met when `hyp.plot` draws into a figure the caller built, found by executing notebooks with diff --git a/notes/release_notes_v1.1.1_draft.md b/notes/release_notes_v1.1.1_draft.md index 6786d507e..24897412d 100644 --- a/notes/release_notes_v1.1.1_draft.md +++ b/notes/release_notes_v1.1.1_draft.md @@ -19,6 +19,11 @@ Python 3.10 through 3.13. Extras are unchanged from 1.1.0. - **A legend or title added to the caller's axes is fitted automatically, inside that axes' own room.** Through 1.1.0 a `legend=` beside a caller's axes was fitted by widening the caller's figure, which stretched its other axes and switched off its layout engine. Now, when the figure is drawn, only the axes passed as `ax=` is narrowed just far enough that its legend ends before the canvas edge or the next panel, and lowered just far enough that its title stays on the canvas. No call is needed, and the fit follows a later `fig.tight_layout()`, `fig.subplots_adjust(...)`, resize or save. A legend with no room beside the axes is drawn inside it; one too large for its panel either way is left in place with a `UserWarning` naming the remedies. - **No `findfont` log lines for ordinary text under matplotlib 3.11 ([#292](https://github.com/ContextLab/hypertools/issues/292)).** matplotlib 3.11 logs a line each time a family in the font list has no face at a text's exact weight; one of the fallback families hypertools listed has no regular face on macOS, so every figure logged the line several times. Fallback families with no regular-weight face are now left out of the list. - **A Yahoo Finance rate limit is reported as one.** `hyp.load('yahoo:')` reported an HTTP 429 from Yahoo as a JSON decoding failure. The error now says that Yahoo is rate-limiting the address and to try again later. +- **A seeded UMAP no longer warns about `n_jobs`.** A seed passed in the `reduce` dict (`reduce={'model': 'UMAP', 'kwargs': {'random_state': 0}}`) drew umap-learn's "n_jobs value 1 overridden to 1" warning; it is now quiet, like the top-level `random_state=`. + +## Documentation + +- Two gallery examples (`plot_colorbar.py`, `plot_digits.py`) are now seeded, so their figures are the same on every docs build, and `plot_shapes_zoo.py` no longer shows stray axis labels beside one panel. ## Upgrading from 1.1.0 diff --git a/notes/session_2026-11-21_release-1.1.1.md b/notes/session_2026-11-21_release-1.1.1.md index c98e59d2c..6ed853e93 100644 --- a/notes/session_2026-11-21_release-1.1.1.md +++ b/notes/session_2026-11-21_release-1.1.1.md @@ -366,3 +366,31 @@ unattended; the user is on a phone. - Observed, left as is (faithful rendering of raw data, same as 1.1.0): in `plot_datasets_tour_001.png` the penguins and Kaggle-iris panels are near-lines because one unnormalized column dominates. + +### 2026-11-22 (after midnight) + +- Independent reviews of all 117 tiles (fresh subagent; Codex CLI with the + ten contact sheets attached): no regression from 1.1.0; the three + differing figures judged harmless; both flagged the shapes-zoo labels + (fixed). Minor points they raised that are IDENTICAL in the released + 1.1.0 and were left for the user to decide: conversation clip's box + touches the left canvas edge; teapot is faint under the one-pixel + marker; two label boxes overlap in `plot_labels`; market-sectors legend + sits close to the box in the GIF thumbnail; weather clip's last marker is + half clipped at the right edge. +- Third build (from a7dfad3a, 51 of 51 executed): 136 of 140 media files + byte-identical to the reviewed e3abb840 build; the four that differ are + the three changed examples (colorbar_002, digits_003, shapes_zoo_001 and + its thumbnail). Viewed all three: correct. +- Page-text diff against 1.1.0 (versions and timings normalized) found one + environment artifact: `plot_datasets_tour` printed kagglehub's "outdated + version (installed: 1.0.2)" notice. Upgraded kagglehub in the build venv + to 1.0.3. +- The date rolled over during the build. The release gate requires the + CHANGELOG heading not to be earlier than the release commit, and the + gallery record commit would be dated 2026-11-22, so the heading is now + 2026-11-22 and the gallery is rebuilt once more from this commit (the + gate allows only the record commit after the build). +- Issue #295 (animate= with panels=, per-frame caption, +faststart) was + filed 2026-11-22 from the timecorr work. It is a feature request, not in + this build; whether it goes into 1.1.1 is the user's decision. From d743ff5de886b10d572f63ba08ffd1c37f58da87 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 00:45:20 -0500 Subject: [PATCH 05/58] release: record the pre-built gallery Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- docs/prebuilt_gallery.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/prebuilt_gallery.json b/docs/prebuilt_gallery.json index 5e9b85333..5b5129f43 100644 --- a/docs/prebuilt_gallery.json +++ b/docs/prebuilt_gallery.json @@ -1,5 +1,5 @@ { - "commit": "c90dd87e32e545ad17d12f2568993fbd0fc55f24", - "source_commit": "514a12cb72269baca147a12d8c4cd8a783e4dd54", + "commit": "2cf4fd0dd9fe7d49e82ac91d007d3ffd7c3a54a6", + "source_commit": "46c3bb39dc6aa505c4dc8cdd4633b760c7c059d3", "version": "1.1.1" } From 12e98347ace2fedd241a1d1623799eeee03ae648 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 01:38:39 -0500 Subject: [PATCH 06/58] test: the no-warning forecast animation tests do not depend on machine speed On a slow Windows runner two Kalman fits took 0.5 s, so the 'needs 8 forecast fits ... roughly 12.8 s' notice fired inside tests that assert no warnings at all. Both pass slow_warning_seconds=None, as tests/plot/test_forecast_schedule.py does. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- notes/session_2026-11-21_release-1.1.1.md | 26 +++++++++++++++++++++++ tests/plot/test_predict_animation.py | 8 +++++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/notes/session_2026-11-21_release-1.1.1.md b/notes/session_2026-11-21_release-1.1.1.md index 6ed853e93..05f388f62 100644 --- a/notes/session_2026-11-21_release-1.1.1.md +++ b/notes/session_2026-11-21_release-1.1.1.md @@ -394,3 +394,29 @@ unattended; the user is on a phone. - Issue #295 (animate= with panels=, per-frame caption, +faststart) was filed 2026-11-22 from the timecorr work. It is a feature request, not in this build; whether it goes into 1.1.1 is the user's decision. + +### Release commit, first cut (d743ff5d) and its CI + +- Fourth build (from 46c3bb39): all 140 media files byte-identical to the + third, no kagglehub notice. Full suite on 46c3bb39: 6910 passed, 24 + skipped, 0 failed. Rehearsal: REHEARSAL PASSED (full). +- Published `docs-gallery-v1.1.1` (2cf4fd0d), recorded it (d743ff5d), + pushed as `release/1.1.1` (PR #296), published `docs-notebooks/v1.1.1/`. + All 25 release gates passed locally and in a depth-1 clone with only + pytest, nbformat and nbclient installed. Built wheel + sdist, smoke + tested, created the DRAFT GitHub release (no tag). +- The user looked at the review page + (https://claude.ai/artifact/W1YfFGsWHoKsxh3ofWgmuj): "Updated gallery + looks good; changes all go in the right direction". +- CI on d743ff5d: 14 jobs green, `test (windows-latest, 3.11)` failed in + `tests/plot/test_predict_animation.py::test_the_plotly_backend_DRAWS_the_same_case_the_same_way`: + it asserts no warnings at all, and on that runner two Kalman fits took + 0.5 s, so hypertools' own "needs 8 forecast fits ... roughly 12.8 s" + notice fired. Machine-speed dependent, nothing to do with this change. + Fix: that test and its matplotlib twin pass `slow_warning_seconds=None`, + as `tests/plot/test_forecast_schedule.py` does. +- A new commit invalidates everything pinned to d743ff5d, so the gallery is + rebuilt from the new commit and both galleries, the dist files and the + draft release's assets are redone. +- Gap in the automatic "work in flight" check: it did not see the running + `wait-for-ci.py` waiter and asked for another. diff --git a/tests/plot/test_predict_animation.py b/tests/plot/test_predict_animation.py index c558e7f69..71fbb9f82 100644 --- a/tests/plot/test_predict_animation.py +++ b/tests/plot/test_predict_animation.py @@ -401,9 +401,12 @@ def test_hue_regrouping_now_ANIMATES_its_forecasts_like_the_static_plot(): labels = np.array(['a', 'a', 'b', 'b'] * 15) with warnings.catch_warnings(record=True) as caught: warnings.simplefilter('always') + # slow_warning_seconds=None: the "these forecast fits will take + # N s" notice depends on how fast the machine is (it fired on a + # slow Windows CI runner) and is not what this test is about fig, ani = hyp.plot(data, '-', predict='Kalman', t=3, hue=labels, animate=True, duration=2, frame_rate=4, - show=False) + show=False, slow_warning_seconds=None) assert not caught, [str(w.message) for w in caught] ax = _ax(fig) ani._func(6, *ani._args) # must not raise @@ -433,9 +436,10 @@ def test_the_plotly_backend_DRAWS_the_same_case_the_same_way(): with hyp.set_interactive_backend('plotly'): with warnings.catch_warnings(record=True) as caught: warnings.simplefilter('always') + # slow_warning_seconds=None: see the matplotlib twin above fig = hyp.plot(data, '-', predict='Kalman', t=3, hue=labels, animate=True, duration=2, frame_rate=4, - show=False) + show=False, slow_warning_seconds=None) assert not caught, [str(w.message) for w in caught] roles = [(tr.meta or {}).get('hyp_forecast_role') for tr in fig.data] assert 'live' in [r for r in roles if r is not None], roles From bceea7c253f8a14cf0aa6ae538e984636525eebd Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 02:11:41 -0500 Subject: [PATCH 07/58] release: record the pre-built gallery Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- docs/prebuilt_gallery.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/prebuilt_gallery.json b/docs/prebuilt_gallery.json index 5b5129f43..ac65d5ae4 100644 --- a/docs/prebuilt_gallery.json +++ b/docs/prebuilt_gallery.json @@ -1,5 +1,5 @@ { - "commit": "2cf4fd0dd9fe7d49e82ac91d007d3ffd7c3a54a6", - "source_commit": "46c3bb39dc6aa505c4dc8cdd4633b760c7c059d3", + "commit": "598c4d87cd56c0e02d45b7282716381458673ab9", + "source_commit": "12e98347ace2fedd241a1d1623799eeee03ae648", "version": "1.1.1" } From fa8e2b7b44de8ccd32ba737682db1a1eb0753061 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 04:22:28 -0500 Subject: [PATCH 08/58] feat: saved mp4/m4v/mov files are written fast-start (GH #295) The index (moov atom) goes before the media data, so a browser starts playing a saved clip while it downloads. Applies to the matplotlib writer, the streaming recorder and the plotly export; .avi and .mkv are unchanged. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/io/streaming.py | 4 +- hypertools/plot/animate.py | 27 ++++++++++++-- hypertools/plot/plotly_backend.py | 8 +++- tests/test_animation_export.py | 61 +++++++++++++++++++++++++++++++ 4 files changed, 93 insertions(+), 7 deletions(-) diff --git a/hypertools/io/streaming.py b/hypertools/io/streaming.py index 58a851ddb..df7b39c50 100644 --- a/hypertools/io/streaming.py +++ b/hypertools/io/streaming.py @@ -482,8 +482,8 @@ def to_box(pts): writer.setup(fig, target, dpi=fig.dpi) else: from ..plot.animate import _ffmpeg_quality_kwargs - writer = animation.writers['ffmpeg'](fps=frame_rate, - **_ffmpeg_quality_kwargs()) + writer = animation.writers['ffmpeg']( + fps=frame_rate, **_ffmpeg_quality_kwargs(save_path)) writer.setup(fig, save_path, dpi=fig.dpi) def _redraw(): diff --git a/hypertools/plot/animate.py b/hypertools/plot/animate.py index d1a4ae32b..12f931d27 100644 --- a/hypertools/plot/animate.py +++ b/hypertools/plot/animate.py @@ -50,10 +50,28 @@ def _stop(self, *args): VIDEO_CRF = 23 -def _ffmpeg_quality_kwargs(): +# containers of the ISO/QuickTime family, whose index (the `moov` atom) ffmpeg +# writes at the END of the file unless told otherwise +_FASTSTART_EXTENSIONS = ('mp4', 'm4v', 'mov') + + +def _ffmpeg_quality_kwargs(save_path=None): """Writer kwargs for a quality-targeted (CRF) h264 encode, shared by - ``_save_animation`` and the streaming recorder so both agree.""" - return dict(codec='h264', extra_args=['-crf', str(VIDEO_CRF)]) + ``_save_animation`` and the streaming recorder so both agree. + + For ``.mp4``/``.m4v``/``.mov`` targets the file is also written + "fast start" (``-movflags +faststart``, GH #295): the index goes to the + front, so a browser starts playing the clip while it is still + downloading instead of fetching the whole file first. The other ffmpeg + containers (``.avi``, ``.mkv``) have no such index and are left alone. + """ + extra_args = ['-crf', str(VIDEO_CRF)] + if save_path is not None: + import os + ext = os.path.splitext(os.fspath(save_path))[1].lower().lstrip('.') + if ext in _FASTSTART_EXTENSIONS: + extra_args += ['-movflags', '+faststart'] + return dict(codec='h264', extra_args=extra_args) # every extension _save_animation understands, for error messages _SUPPORTED_ANIMATION_EXTENSIONS = ( '.gif, .png/.apng (animated PNG), .svg (animated vector graphics), ' @@ -164,7 +182,8 @@ def _save_animation(line_ani, save_path, frame_rate, dpi=None): os.remove(tmp_path) elif ext in _FFMPEG_EXTENSIONS: Writer = animation.writers["ffmpeg"] - writer = Writer(fps=frame_rate, **_ffmpeg_quality_kwargs()) + writer = Writer(fps=frame_rate, + **_ffmpeg_quality_kwargs(save_path)) line_ani.save(save_path, writer=writer, dpi=dpi) else: what = f"extension {'.' + ext!r}" if ext else "missing extension" diff --git a/hypertools/plot/plotly_backend.py b/hypertools/plot/plotly_backend.py index dcdca9cb3..421fdd624 100644 --- a/hypertools/plot/plotly_backend.py +++ b/hypertools/plot/plotly_backend.py @@ -4250,10 +4250,16 @@ def _grid_durations(n_frames, grid_ms): with tempfile.TemporaryDirectory() as tmpdir: for i, img in enumerate(images): img.save(os.path.join(tmpdir, f'frame_{i:04d}.png')) + # fast start for mp4/m4v/mov, as the matplotlib writer does + # (`animate._ffmpeg_quality_kwargs`, GH #295) + from .animate import _FASTSTART_EXTENSIONS + ext = os.path.splitext(save_path)[1].lower().lstrip('.') + faststart = (['-movflags', '+faststart'] + if ext in _FASTSTART_EXTENSIONS else []) subprocess.run( ['ffmpeg', '-y', '-framerate', str(fps), '-i', os.path.join(tmpdir, 'frame_%04d.png'), - '-pix_fmt', 'yuv420p', save_path], + '-pix_fmt', 'yuv420p', *faststart, save_path], check=True, capture_output=True) diff --git a/tests/test_animation_export.py b/tests/test_animation_export.py index 570a98eb9..4b3d55eca 100644 --- a/tests/test_animation_export.py +++ b/tests/test_animation_export.py @@ -68,6 +68,67 @@ def test_matplotlib_mp4_export(tmp_path): assert os.path.getsize(out) > 1000 +def _top_level_atoms(path): + """The top-level atom (box) names of an ISO/QuickTime file, in order.""" + import struct + names = [] + with open(path, 'rb') as f: + while True: + head = f.read(8) + if len(head) < 8: + break + size, name = struct.unpack('>I4s', head) + if size == 1: # 64-bit size follows + size = struct.unpack('>Q', f.read(8))[0] + f.seek(size - 16, 1) + elif size == 0: # atom runs to end of file + names.append(name.decode('latin-1')) + break + else: + f.seek(size - 8, 1) + names.append(name.decode('latin-1')) + return names + + +@pytest.mark.skipif(not HAS_FFMPEG, reason='ffmpeg not installed') +@pytest.mark.parametrize('ext', ['mp4', 'm4v', 'mov']) +def test_saved_video_is_fast_start(tmp_path, ext): + """GH #295: the index (`moov`) is written BEFORE the media data + (`mdat`), so a browser can start playing while the file downloads. + ffmpeg's default puts it last.""" + out = str(tmp_path / f'anim.{ext}') + hyp.plot(walk, animate=True, duration=2, frame_rate=10, size=(4, 4), + save_path=out, show=False) + plt.close('all') + atoms = _top_level_atoms(out) + assert 'moov' in atoms and 'mdat' in atoms, atoms + assert atoms.index('moov') < atoms.index('mdat'), atoms + + +@pytest.mark.skipif(not HAS_FFMPEG, reason='ffmpeg not installed') +def test_plotly_saved_mp4_is_fast_start(tmp_path): + out = str(tmp_path / 'anim.mp4') + hyp.plot(walk, animate=True, duration=1, frame_rate=5, + backend='plotly', save_path=out, show=False) + atoms = _top_level_atoms(out) + assert atoms.index('moov') < atoms.index('mdat'), atoms + + +@pytest.mark.skipif(not HAS_FFMPEG, reason='ffmpeg not installed') +def test_mkv_export_still_works_without_fast_start(tmp_path): + """`.mkv`/`.avi` have no `moov` index; the flag is not passed for them + (ffmpeg would warn about an unused option).""" + from hypertools.plot.animate import _ffmpeg_quality_kwargs + assert '+faststart' not in _ffmpeg_quality_kwargs('a.mkv')['extra_args'] + assert '+faststart' not in _ffmpeg_quality_kwargs('a.avi')['extra_args'] + assert '+faststart' in _ffmpeg_quality_kwargs('a.MP4')['extra_args'] + out = str(tmp_path / 'anim.mkv') + hyp.plot(walk, animate=True, duration=1, frame_rate=5, size=(4, 4), + save_path=out, show=False) + plt.close('all') + assert os.path.getsize(out) > 1000 + + @pytest.mark.skipif(not HAS_FFMPEG, reason='ffmpeg not installed') def test_mp4_export_is_quality_targeted_not_fixed_bitrate(tmp_path): """Until 1.1 every video was written at ``bitrate=1800`` kbit/s, so a From 8e2a42331ef881b54e5036eb756cafcd08688cea Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 05:01:47 -0500 Subject: [PATCH 09/58] feat: animate= with panels= is one animation of the whole grid; caption= (GH #295) panels=/subplots= with animate= used to raise. The grid is now drawn by re-entering plot() once per panel in a panel-cell mode, where the matplotlib backend draws into the given axes and hands back its frame function, and one FuncAnimation drives every panel on one clock. Each rotating 3-D cube is zoomed out until it stays inside its own cell; with axis labels the figure is enlarged. on_frame= is called once per frame for the figure, with a FrameContext whose new panels field holds one context per panel. caption= draws a figure-level caption (string, '{index}' pattern or a callable taking the FrameContext) under a single plot or a grid, updated every frame, placed below the lowest drawn content with the figure grown downward when there is no blank room. labels= bookkeeping is kept per axes, so labels follow the reveal in every panel. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/plot/animation_context.py | 18 +- hypertools/plot/matplotlib_backend.py | 153 +++-- hypertools/plot/plot.py | 827 ++++++++++++++++++++++++-- 3 files changed, 914 insertions(+), 84 deletions(-) diff --git a/hypertools/plot/animation_context.py b/hypertools/plot/animation_context.py index a9dee202d..5010bdf68 100644 --- a/hypertools/plot/animation_context.py +++ b/hypertools/plot/animation_context.py @@ -52,9 +52,11 @@ class FrameContext: ``sum(segment_frame_counts(...))``, which may differ by rounding. figure : matplotlib.figure.Figure or plotly.graph_objects.Figure The figure being animated. BACKEND-NATIVE. - axes : matplotlib.axes.Axes or None + axes : matplotlib.axes.Axes, tuple of Axes, or None The axes the trajectories are drawn on -- an ``Axes3D`` for 3-D plots, a plain ``Axes`` for 2-D ones (which have no ``zaxis``). + For an animated ``panels=`` grid, a tuple of every panel's axes in + panel order (see `panels`). BACKEND-NATIVE: ``None`` on plotly, which has no axes object (its equivalent state lives on the figure's ``layout``). artists : tuple @@ -221,6 +223,18 @@ class FrameContext: held) and ``'transition'`` for odd (one cloud is easing into the next) -- the parity rule `morph.morph_positions` implements. ``None`` for non-morph animations. + panels : tuple of FrameContext + Empty for a single-axes animation. For an animated ``panels=`` grid + (matplotlib), where a callback is called ONCE per frame for the + whole figure, this holds one `FrameContext` per panel, in panel + order -- each exactly the context that panel's single-axes + animation would deliver (its own ``axes``, ``artists``, + ``datasets``, ``revealed_counts``, ``window_bounds``...). On the + grid's own context ``axes`` is then a TUPLE of every panel's axes, + ``artists``, ``datasets``, ``revealed_counts`` and + ``window_bounds`` are the panels' values concatenated in panel + order, and ``current_index``/``current_fraction`` are ``None`` + (read them per panel). Notes ----- @@ -262,6 +276,7 @@ class FrameContext: segment_index: Optional[int] = None segment_kind: Optional[str] = None progress: Optional[float] = None + panels: Tuple[Any, ...] = () def __post_init__(self): """Canonicalize the container types and derive `progress`. @@ -279,6 +294,7 @@ def __post_init__(self): """ object.__setattr__(self, 'artists', tuple(self.artists)) object.__setattr__(self, 'datasets', tuple(self.datasets)) + object.__setattr__(self, 'panels', tuple(self.panels)) if self.revealed_counts is not None: object.__setattr__(self, 'revealed_counts', tuple(self.revealed_counts)) diff --git a/hypertools/plot/matplotlib_backend.py b/hypertools/plot/matplotlib_backend.py index 17837abb9..ee1d80be5 100644 --- a/hypertools/plot/matplotlib_backend.py +++ b/hypertools/plot/matplotlib_backend.py @@ -711,6 +711,37 @@ def _anim_box_zoom(zoom): # for the backend divergences a shared callee closed. +class PanelAnimationStub: + """One panel's share of an animated `panels=` grid (GH #295). + + An ordinary animated plot hands its frame function to a + `FuncAnimation`. A panel of an animated grid must not: the grid has ONE + animation, whose frame function calls every panel's. So a panel's + `_draw` returns this instead -- the frame function, its arguments, the + frame count and the frame interval, under the names `FuncAnimation` + itself uses (`_func`, `_args`, `_save_count`, `_interval`), so the code + in `plot()` that wraps `line_ani._func` (per-point colors, frame hooks) + works on either unchanged. + + `zoom_scale` is the panel's handle on its own 3-D camera zoom: the grid + lowers ``zoom_scale[0]`` until the panel's rotating cube fits its cell + (`plot._fit_rotating_cubes`). + """ + + def __init__(self, func, args, n_frames, interval, zoom_scale=None): + self._func = func + self._args = tuple(args) + self._save_count = int(n_frames) + self._interval = interval + #: one-element list holding the factor the panel's frame function + #: multiplies its 3-D box zoom by (read on every frame) + self.zoom_scale = [1.0] if zoom_scale is None else zoom_scale + + def draw(self, frame): + """Draw frame `frame` of this panel.""" + return self._func(frame, *self._args) + + def _make_save_dpi_safe(line_ani): """Guard every future ``line_ani.save(...)`` call against a real matplotlib/canvas-manager interaction that corrupts the rendered pixel @@ -868,6 +899,7 @@ def _draw( ylim=None, x_date=False, legend_order=None, + panel_cell=False, ): """ Draws the plot @@ -943,6 +975,17 @@ def _draw( # grid they turned on -- is theirs to keep; see the axis_scale='data' # branch below) _caller_ax = ax is not None + # `panel_cell=True` (GH #295): this call draws ONE PANEL OF AN ANIMATED + # `panels=` GRID into the caller's axes. The animated builders below + # then draw on that axes instead of creating a figure, and hand back a + # `PanelAnimationStub` (the frame function and its arguments) instead of + # a `FuncAnimation`: the grid owns the one animation that drives every + # panel on a shared clock. + _cell_ax = ax if (panel_cell and ax is not None) else None + # ...and a factor on the animated 3-D box zoom, which the grid lowers + # (through the stub) until the rotating cube stays inside its cell; it + # is 1.0, i.e. no change, for every ordinary animated plot. + _cell_zoom_scale = [1.0] # chemtrails/precog/bullettime (GH #127): normalize to one bool per # dataset now, at the top of `_draw`, BEFORE any nested closure below is @@ -1238,6 +1281,15 @@ def plot3D(data, fig, ax): (raw[:, 0], raw[:, 1], raw[:, 2]), i) return fig, ax, data + def _own_labels(): + """The ``(annotation, x, y[, z])`` entries `annotate_plot` recorded + for THIS call's axes (falling back to the module global, which holds + the most recently annotated plot's).""" + own = getattr(ax, '_hyp_labels_and_points', None) + if own is not None: + return own + return globals().get('labels_and_points') or [] + def annotate_plot(data, labels, lengths=None): """Create labels in 3d chart Args: @@ -1253,6 +1305,11 @@ def annotate_plot(data, labels, lengths=None): global labels_and_points labels_and_points = [] + # ...and on the axes itself: the module global holds only the LAST + # annotated plot's labels, so every earlier cell of a panel grid + # lost its own (an animated grid then updated the last panel's + # labels only; GH #295). `_own_labels` reads this. + ax._hyp_labels_and_points = labels_and_points if lengths is not None: within = [j for L in lengths for j in range(int(L))] @@ -1356,7 +1413,7 @@ def update_position(e): renderer = fig.canvas.get_renderer() except Exception: renderer = None - for entry in labels_and_points: + for entry in _own_labels(): if is_3d: label, x, y, z = entry x2, y2, _ = proj3d.proj_transform(x, y, z, proj) @@ -1395,7 +1452,7 @@ def _sync_anim_labels(num, window_frames, all_visible=False, revealed=None, # `labels_and_points` is a module global set only when annotate_plot ran # (i.e. this plot has labels); it may also still hold a PREVIOUS plot's # labels, so guard for existence and restrict to THIS axes' labels. - laps = [e for e in (globals().get('labels_and_points') or []) + laps = [e for e in _own_labels() if getattr(e[0], 'axes', None) is ax] if not laps: return @@ -1443,7 +1500,7 @@ def hide_labels(e): None """ - for label in labels_and_points: + for label in _own_labels(): label[0]._visible = False def add_labels(x, labels, explore=False): @@ -1771,7 +1828,8 @@ def update_lines_parallel( # Axes3D.dist was removed in matplotlib >= 3.8, silently disabling # zoom; set_box_aspect(zoom=...) is the supported equivalent. See # _anim_box_zoom for the (slightly zoomed-out) animation mapping. - ax.set_box_aspect(None, zoom=_anim_box_zoom(zoom)) + ax.set_box_aspect( + None, zoom=_anim_box_zoom(zoom) * _cell_zoom_scale[0]) # zip_longest: marker-only animations (or datasets with no trail # flag set at all -- GH #127) have no trail artist (trail is None @@ -1899,7 +1957,8 @@ def update_lines_spin( # Axes3D.dist was removed in matplotlib >= 3.8, silently disabling # zoom; set_box_aspect(zoom=...) is the supported equivalent. See # _anim_box_zoom for the (slightly zoomed-out) animation mapping. - ax.set_box_aspect(None, zoom=_anim_box_zoom(zoom)) + ax.set_box_aspect( + None, zoom=_anim_box_zoom(zoom) * _cell_zoom_scale[0]) for i, (line, data) in enumerate(zip(lines, data_lines)): # antialias: 'spin' draws the FULL trajectory every frame @@ -1967,7 +2026,8 @@ def update_lines_serial( total_frames = max(1, int(round(frame_rate * duration))) azim_now = azim + rotations * 360.0 * num / total_frames ax.view_init(elev=elev, azim=azim_now) - ax.set_box_aspect(None, zoom=_anim_box_zoom(zoom)) + ax.set_box_aspect( + None, zoom=_anim_box_zoom(zoom) * _cell_zoom_scale[0]) lengths = [d.shape[0] for d in data_lines] total_points = sum(lengths) @@ -2078,7 +2138,8 @@ def update_morph(num, morph_state, cube_scale, azimuths, zoom=1, elev=10): azim_now = azimuths[num] ax.view_init(elev=elev, azim=azim_now) - ax.set_box_aspect(None, zoom=_anim_box_zoom(zoom)) + ax.set_box_aspect( + None, zoom=_anim_box_zoom(zoom) * _cell_zoom_scale[0]) seg_idx, step, n_steps = _morph.frame_to_segment( morph_state["frame_counts"], num) @@ -2173,6 +2234,20 @@ def update_morph(num, morph_state, cube_scale, azimuths, zoom=1, elev=10): segment_kind='hold' if seg_idx % 2 == 0 else 'transition') return (artist,) + def _new_animation(fig, func, n_frames, fargs): + """The animation object for frame function `func`: the + `FuncAnimation` an ordinary animated plot returns, or -- for one + cell of an animated panel grid (`panel_cell=True`) -- a + `PanelAnimationStub` carrying the same function, arguments, frame + count and interval for the grid's single animation to drive.""" + if _cell_ax is not None: + return PanelAnimationStub(func, fargs, n_frames, + 1000 / frame_rate, + zoom_scale=_cell_zoom_scale) + return HyperFuncAnimation( + fig, func, n_frames, fargs=fargs, + interval=1000 / frame_rate, blit=False, repeat=False) + def dispatch_animate(x, ani_params): """Dispatch to `animate_plot3D` or `animate_plot2D` based on `x[0]`'s column count. @@ -2255,12 +2330,18 @@ def animate_plot3D( """ # initialize plot - fig = plt.figure() - ax = fig.add_subplot(111, projection="3d") - # give the (axis-off) 3D axes the full canvas: with the default - # subplot margins, the zoomed cube overflows the axes viewport at - # some rotation angles, clipping cube corners and data - ax.set_position([0.0, 0.0, 1.0, 1.0]) + if _cell_ax is not None: + # one cell of an animated panel grid: the grid made the figure + # and lays its cells out itself + ax = _cell_ax + fig = ax.figure + else: + fig = plt.figure() + ax = fig.add_subplot(111, projection="3d") + # give the (axis-off) 3D axes the full canvas: with the default + # subplot margins, the zoomed cube overflows the axes viewport + # at some rotation angles, clipping cube corners and data + ax.set_position([0.0, 0.0, 1.0, 1.0]) # create lines. Trail artists are created whenever ANY dataset draws # lines (previously is_line(fmt) required ALL datasets to be lines, @@ -2656,7 +2737,7 @@ def _trail_kwargs(kw): # LATER dataset was silently truncated (F04-003), marker-only # animations ignored duration= entirely (F04-005/F05-010), and a # 1-point FIRST dataset produced a 1-frame "animation" (F05-012). - line_ani = HyperFuncAnimation( + line_ani = _new_animation( fig, update_lines_parallel, max(1, int(round(frame_rate * duration))), @@ -2673,30 +2754,21 @@ def _trail_kwargs(kw): bullettime, elev, ), - interval=1000 / frame_rate, - blit=False, - repeat=False, ) elif style == "serial": - line_ani = HyperFuncAnimation( + line_ani = _new_animation( fig, update_lines_serial, max(1, int(round(frame_rate * duration))), fargs=(x, lines, trail, cube_scale_anim, window_frames, rotations, zoom, chemtrails, precog, bullettime, elev), - interval=1000 / frame_rate, - blit=False, - repeat=False, ) elif style == "spin": - line_ani = HyperFuncAnimation( + line_ani = _new_animation( fig, update_lines_spin, max(1, int(round(frame_rate * duration))), fargs=(x, lines, cube_scale_anim, rotations, zoom, elev), - interval=1000 / frame_rate, - blit=False, - repeat=False, ) elif style == "morph": n_morph_datasets = len(morph_state["indices"]) @@ -2704,14 +2776,11 @@ def _trail_kwargs(kw): frame_counts, _, azimuths = _morph.morph_schedule( n_morph_datasets, total_frames, rotations, azim) morph_state["frame_counts"] = frame_counts - line_ani = HyperFuncAnimation( + line_ani = _new_animation( fig, update_morph, sum(frame_counts), fargs=(morph_state, cube_scale_anim, azimuths, zoom, elev), - interval=1000 / frame_rate, - blit=False, - repeat=False, ) # `HyperAnimation.n_segments` reads this. Tagged HERE, beside the # `sum(frame_counts)` that becomes `_save_count`, so the segment @@ -2969,8 +3038,13 @@ def animate_plot2D( ) # initialize plot - fig = plt.figure() - ax = fig.add_subplot(111) + if _cell_ax is not None: + # one cell of an animated panel grid (see animate_plot3D) + ax = _cell_ax + fig = ax.figure + else: + fig = plt.figure() + ax = fig.add_subplot(111) def _wants_trail(idx): # 'serial' composes with the trail flags (see animate_plot3D's @@ -3126,26 +3200,20 @@ def _trail_kwargs(kw): if style in ["parallel", True, "window"]: # frames == round(frame_rate * duration) -- see the identical # F04-003/F04-005/F05-010/F05-012 note in `animate_plot3D`. - line_ani = HyperFuncAnimation( + line_ani = _new_animation( fig, update_lines_parallel_2d, max(1, int(round(frame_rate * duration))), fargs=(x, lines, trail, window_frames, chemtrails, precog, bullettime), - interval=1000 / frame_rate, - blit=False, - repeat=False, ) elif style == "serial": - line_ani = HyperFuncAnimation( + line_ani = _new_animation( fig, update_lines_serial_2d, max(1, int(round(frame_rate * duration))), fargs=(x, lines, trail, window_frames, chemtrails, precog, bullettime), - interval=1000 / frame_rate, - blit=False, - repeat=False, ) elif style == "morph": # 2-D morphs always use even segment timing regardless of @@ -3159,14 +3227,11 @@ def _trail_kwargs(kw): frame_counts, _, _ = _morph.morph_schedule( n_morph_datasets, total_frames, 1, 0) morph_state["frame_counts"] = frame_counts - line_ani = HyperFuncAnimation( + line_ani = _new_animation( fig, update_morph_2d, sum(frame_counts), fargs=(morph_state,), - interval=1000 / frame_rate, - blit=False, - repeat=False, ) # the 2-D half of the `n_segments` tag -- see the 3-D branch above line_ani._hyp_morph_segments = len(frame_counts) @@ -3450,7 +3515,7 @@ def _trail_kwargs(kw): if size is not None: fig.set_size_inches(size) - if line_ani is not None: + if line_ani is not None and not isinstance(line_ani, PanelAnimationStub): _make_save_dpi_safe(line_ani) return fig, ax, data, line_ani diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index 944898c47..e1622a953 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -2816,9 +2816,13 @@ def _series_expand_list(value, owner, n_input, key=None): return value -def _validate_dynamic_title(title, animate, row_indices): +def _validate_dynamic_title(title, animate, row_indices, name='title'): """Split `title=` into its static and DYNAMIC (per-frame) halves. + `name` is the keyword being validated, for the error messages: + ``caption=`` (GH #295) takes exactly the forms `title=` does and is + split by this same function. + Returns ``(static_title, dynamic)`` where `dynamic` is ``None`` for the ordinary forms and otherwise a callable ``ctx -> str`` (GH #285). @@ -2842,13 +2846,13 @@ def _validate_dynamic_title(title, animate, row_indices): # docstring promises BEFORE the pipeline runs, not a title drawn # as its own literal braces. raise ValueError( - f"title={title!r} is a per-frame format pattern (it contains " + f"{name}={title!r} is a per-frame format pattern (it contains " f"'{_TITLE_INDEX_FIELD}'), but the data passed to plot() has no " "row index to read: pass a pandas DataFrame or Series with a " "DatetimeIndex (or any other non-default index), pass a " - "callable title (ctx -> str) instead, or drop the braces for a " - "fixed title.") - return None, _make_title_pattern_resolver(title, row_indices) + f"callable {name} (ctx -> str) instead, or drop the braces for " + f"a fixed {name}.") + return None, _make_title_pattern_resolver(title, row_indices, name=name) def _title_head_row(ctx, n_rows): @@ -2895,7 +2899,7 @@ def _title_head_row(ctx, n_rows): return int(min(n_rows - 1, max(0, round(frac * (n_rows - 1))))) -def _make_title_pattern_resolver(pattern, row_indices): +def _make_title_pattern_resolver(pattern, row_indices, name='title'): """A ``ctx -> str`` that formats `pattern` with the row index under the reveal head (GH #285). See `_title_head_row` for what "the head" means. @@ -2920,22 +2924,23 @@ def _resolve(ctx): # specifier'), and they surface AFTER the pipeline has run; # say which kwarg, which pattern, and which value. raise ValueError( - f"title={pattern!r} could not be formatted with " + f"{name}={pattern!r} could not be formatted with " f"index={value!r} ({type(exc).__name__}: {exc}). The only " - "field a pattern title can reference is {index}, with an " + f"field a pattern {name} can reference is {{index}}, with an " "optional format spec the index value supports (e.g. " "'{index:%B %Y}' for a DatetimeIndex).") from exc return _resolve -def _resolve_dynamic_title_text(fn, ctx): +def _resolve_dynamic_title_text(fn, ctx, name='title'): """Call a dynamic `title=` (callable or pattern resolver) for `ctx` and insist on a string (1.1 release review T8): a callable returning - None or 42 was drawn as the literal 'None'/'42'.""" + None or 42 was drawn as the literal 'None'/'42'. `name` is the keyword + the callable came from (``title`` or ``caption``).""" value = fn(ctx) if not isinstance(value, str): raise TypeError( - f"title= callable must return a str for every frame; got " + f"{name}= callable must return a str for every frame; got " f"{type(value).__name__}: {value!r}.") return value @@ -4294,6 +4299,138 @@ def _panel_cluster_labels(probe_labels, model, spec, rows=None, return _PanelClusterLabels(labels, model, spec, categories=categories) +# -------------------------------------------------------------------------- +# caption= (GH #295): one figure-level line of text under the plot(s), +# fixed or updated every frame of an animation. +# -------------------------------------------------------------------------- + +#: ``gid`` of the caption's matplotlib ``Text`` -- how a caller finds it on +#: the returned figure (``fig.findobj(lambda a: a.get_gid() == +#: 'hypertools-caption')``) to restyle it. +CAPTION_GID = 'hypertools-caption' + +#: blank room (inches) kept above and below the caption's text +_CAPTION_PAD_IN = 0.1 + + +def _validate_caption(caption, row_indices, backend_name, ax=None): + """Split `caption=` into ``(static_text, dynamic)`` (GH #295). + + A caption takes the forms a per-frame `title=` takes -- a fixed string, + a ``{index...}`` format pattern, or a callable ``ctx -> str`` -- and is + split by the same function (`_validate_dynamic_title`). Exactly one of + the two results is set; both are None without a caption. Fails here, + before the pipeline runs, for a value of the wrong type, for the plotly + backend (the caption is a matplotlib artist), and for a caller's own + ``ax=`` (a caption belongs to a whole figure, which is then the + caller's to lay out). + """ + if caption is None: + return None, None + if isinstance(caption, bytes): + caption = caption.decode('utf-8') + if not (isinstance(caption, str) or callable(caption)): + raise TypeError( + "caption= must be a string, a '{index...}' format pattern, or a " + f"callable (ctx -> str); got {type(caption).__name__}: " + f"{caption!r}.") + if backend_name == 'plotly': + raise NotImplementedError( + "caption= is matplotlib-only. On plotly an animation is a list " + "of go.Frame payloads, so a per-frame caption would have to be " + "a layout annotation rebuilt inside every frame's layout -- " + "separate work from the matplotlib text this draws. Pass " + "backend='matplotlib' for caption=, or drop caption= (a " + "per-frame title= works on both backends).") + if ax is not None: + raise ValueError( + "caption= is drawn under the whole figure, which hypertools " + "resizes to make room for it, so it cannot be combined with a " + "caller-supplied ax=. Drop ax= (or use panels= for a grid), or " + "add the text yourself with ax.figure.text(...).") + return _validate_dynamic_title(caption, None, row_indices, + name='caption') + + +def _grow_figure_downward(fig, extra_in): + """Make `fig` taller by `extra_in` inches, adding the room at the + BOTTOM: every axes keeps its absolute size and its distance from the + top and side edges, so nothing already drawn moves relative to anything + else or changes size (a 3-D axes' cube included -- its viewport is + derived from the axes' size in inches, which is unchanged).""" + w_in, h_in = fig.get_size_inches() + new_h_in = h_in + float(extra_in) + # a persistent layout engine would undo the positions set below on the + # next draw (see `_fit_right_legend`) + try: + fig.set_layout_engine('none') + except Exception: + pass + placed = [(axis, axis.get_position(original=True), axis.get_position()) + for axis in fig.axes] + fig.set_size_inches(w_in, new_h_in) + for axis, original, active in placed: + for which, pos in (('original', original), ('active', active)): + axis.set_position( + [pos.x0, (pos.y0 * h_in + extra_in) / new_h_in, + pos.width, pos.height * h_in / new_h_in], which=which) + + +def _blank_bottom_in(fig): + """How many inches at the bottom of `fig` hold nothing: the distance + from the canvas' bottom edge up to the lowest thing drawn (any axes, + with its tick labels, axis labels, legend and unclipped artists, or a + figure-level artist), measured on a real draw. 0.0 when something + reaches the bottom edge or the figure cannot be measured -- the + caption then gets a whole new strip, which is always safe.""" + try: + box = fig.get_tightbbox(_measurement_renderer(fig)) + bottom = float(box.y0) + except Exception: # noqa: BLE001 - an unmeasurable figure: assume none + return 0.0 + if not np.isfinite(bottom): + return 0.0 + return max(0.0, bottom) + + +def _add_caption(fig, text, font=None, family=None): + """Draw `text` as `fig`'s caption (GH #295) and return its ``Text``. + + The caption is centered under everything the figure holds, a small gap + below the lowest thing drawn (`_blank_bottom_in`). Where the figure has + no blank room there for it -- an animated 3-D plot fills its canvas -- + the figure grows downward by what is missing + (`_grow_figure_downward`), so the caption never overlaps a panel, a + legend, a colorbar or a companion panel and always lies inside the + canvas. The room is sized for the number of lines `text` has; a + per-frame caption should keep that many lines (or fewer) on every + frame. + + `font` is the resolved explicit ``font=`` (a ``FontProperties``), and + `family` the fallback font stack used without one -- the caption is + styled like the title beside it. + """ + from matplotlib.font_manager import FontProperties + text = '' if text is None else str(text) + if font is not None: + props = FontProperties(font) if isinstance(font, str) else font.copy() + else: + props = FontProperties(family=family or sans_serif_stack()) + props.set_size(plt.rcParams['font.size']) + n_lines = text.count('\n') + 1 + line_in = 1.2 * props.get_size_in_points() / 72.0 + strip_in = n_lines * line_in + 2 * _CAPTION_PAD_IN + blank_in = _blank_bottom_in(fig) + if blank_in < strip_in: + _grow_figure_downward(fig, strip_in - blank_in) + blank_in = strip_in + _, h_in = fig.get_size_inches() + artist = fig.text(0.5, (blank_in - _CAPTION_PAD_IN) / h_in, text, + ha='center', va='top', fontproperties=props, + gid=CAPTION_GID) + return artist + + def _panel_probe(data, kw, ndims, caught_warnings): """Fit one panel grid's pipeline exactly as the equivalent single-axes call fits it -- by MAKING that call (``return_model=True``, figure @@ -4394,8 +4531,10 @@ def _reemit_panel_warnings(probe_caught, draw_caught): def _plot_panels(x, panels, call_kwargs, _name='panels'): - """Draw one STATIC panel per dataset (or per `reduce=` entry) in a - single figure -- the implementation behind `hyp.plot(..., panels=)`. + """Draw one panel per dataset (or per `reduce=` entry) in a single + figure -- the implementation behind `hyp.plot(..., panels=)`. With + `animate=` the panels are animated together, on one clock, by a single + animation (GH #295; matplotlib only). Two modes, chosen by `reduce=`: @@ -4410,13 +4549,30 @@ def _plot_panels(x, panels, call_kwargs, _name='panels'): Each panel's box is scaled to its own contents, exactly as a per-panel `hyp.plot(..., ax=ax)` call is today. """ - if call_kwargs.get('animate'): + _animate = call_kwargs.get('animate') + animated = (isinstance(_animate, (list, tuple, dict, np.ndarray)) + or bool(_animate)) + backend = resolve_backend(call_kwargs.get('backend', 'auto')) + if animated and backend == 'plotly': + raise NotImplementedError( + f"animated {_name}= grids are matplotlib-only. On plotly an " + "animation is a list of go.Frame payloads over ONE figure's " + "traces, so an animated grid would have to merge every panel's " + "per-frame payloads (and each scene's camera) into one frame " + "list -- separate work from the matplotlib artists this draws. " + f"Pass backend='matplotlib' for an animated {_name}= grid, or " + "drop animate= for a static plotly grid.") + if animated and call_kwargs.get('companion') is not None: raise ValueError( - f"{_name}= draws several STATIC panels in one figure and " - f"cannot be combined with animate={call_kwargs['animate']!r}: " - "an animation owns its whole figure (one axes, one clock). " - "Lay several trajectories out in the DATA instead (see the " - "ax= docstring), or drop animate= for a static panel grid.") + f"companion= cannot be combined with an animated {_name}= grid: " + "a companion panel is laid out beside ONE animated axes, and " + "the grid lays its own cells out. Give the extra series a " + "panel of its own, or drop panels= and use companion= on a " + "single animated plot.") + # caption= (GH #295) belongs to the whole grid, not to any one panel: + # validated here, before any panel is analyzed, and drawn below + caption, dynamic_caption = _validate_caption( + call_kwargs.get('caption'), _capture_row_indices(x), backend) if call_kwargs.get('ax') is not None: raise ValueError( f"{_name}= creates its own figure and axes, so it cannot also " @@ -4465,15 +4621,26 @@ def _plot_panels(x, panels, call_kwargs, _name='panels'): if save_path is not None: save_path = _normalize_save_path(save_path) return_model = call_kwargs.get('return_model', False) - backend = resolve_backend(call_kwargs.get('backend', 'auto')) + if animated and save_path is not None: + # an animated grid is saved as an animation: refuse an extension no + # animation writer handles now, not after every panel was fitted + _check_animation_save_path(save_path) # every panel call draws into the grid, silently, and never saves or # re-shows: this function owns the figure, the save and the display. shared = dict(call_kwargs) for key in ('title', 'show', 'save_path', 'return_model', 'panels', - 'subplots', 'ax', 'panel_fit'): + 'subplots', 'ax', 'panel_fit', 'caption'): shared.pop(key, None) shared['show'] = False + # on_frame= on an animated grid is called once per frame for the whole + # FIGURE (see `_animate_panel_grid`), not once per panel + grid_hooks = None + if animated: + grid_hooks = FrameHooks() + if shared.get('on_frame') is not None: + grid_hooks.add(shared['on_frame']) + shared.pop('on_frame', None) # panel_fit= (GH #285): 'shared' (the default, and everything before # 1.1.x) fits ONE pipeline across every dataset and gives each panel its @@ -4607,6 +4774,17 @@ def _plot_panels(x, panels, call_kwargs, _name='panels'): lifts = [_panel_lift_for(xi, src) for xi, src in zip(xf, panel_sources[i])] if any(lift is not None for lift in lifts): + if animated: + raise ValueError( + f"an animated {_name}= grid needs every panel's " + "analyzed data to have the same number of columns " + "(2 or 3), but panel " + f"{i + 1}'s is narrower than the grid's 3-D cells " + "(a narrower panel is drawn flat on its cell's " + "floor in a STATIC grid, which has no animated " + "counterpart). Give every panel 3 columns (or " + "pass ndims=2 for an all-2-D grid), or drop " + "animate=.") kw['_panel_lift'] = lifts # the analysis already ran (above); each panel DRAWS its rows kw.update(transform=list(xf), reduce=None, normalize=None, @@ -4654,12 +4832,17 @@ def _plot_panels(x, panels, call_kwargs, _name='panels'): size=call_kwargs.get('size'), backend='matplotlib') panel_axes = [] panel_models = [] + #: an animated grid's panels, in panel order: each animated panel call + #: appends its frame function, frame hooks and axes here (GH #295) + cells = [] if animated else None with warnings.catch_warnings(record=True) as draw_warnings: warnings.simplefilter('always') for i in range(n_panels): kw = dict(panel_kwargs[i]) kw.update(ax=axes[i], title=titles[i], show=False, save_path=None, return_model=return_model, size=None) + if animated: + kw['_panel_animation'] = cells if panel_ndims < (3 if ndims is None else min(ndims, 3)): # cells lowered to the data's width (`_panel_cell_ndims`): # the panel call's `ax=` projection check reads ndims=, @@ -4696,6 +4879,22 @@ def _plot_panels(x, panels, call_kwargs, _name='panels'): fig.set_size_inches(_w + _extra, _h) fig.tight_layout() + if animated: + return _animate_panel_grid( + fig, cells, panel_axes, panel_models, (nrows, ncols), + grid_hooks=grid_hooks, caption=caption, + dynamic_caption=dynamic_caption, font=call_kwargs.get('font'), + save_path=save_path, show=show, return_model=return_model, + shared_pipeline=shared_pipeline, + resize=call_kwargs.get('size') is None, _name=_name) + + if caption is not None or dynamic_caption is not None: + # a static grid's caption: fixed text, or the dynamic forms + # resolved once for the finished figure (as a dynamic title= is on + # a static plot) + _add_grid_caption(fig, caption, dynamic_caption, panel_axes, + call_kwargs.get('font')) + if save_path is not None: fig.savefig(save_path) if not show: @@ -4731,6 +4930,374 @@ def _plot_panels(x, panels, call_kwargs, _name='panels'): return fig +def _check_animation_save_path(save_path): + """Raise the animation writers' own "unsupported format" error for a + `save_path` none of them handles (`animate._save_animation` raises it + at save time; an animated panel grid checks before it fits anything).""" + from .animate import _FFMPEG_EXTENSIONS, _SUPPORTED_ANIMATION_EXTENSIONS + ext = os.path.splitext(os.fspath(save_path))[1].lower().lstrip('.') + if ext not in ('svg', 'gif', 'png', 'apng') + tuple(_FFMPEG_EXTENSIONS): + what = f"extension {'.' + ext!r}" if ext else "missing extension" + raise ValueError( + f"unsupported animation save format ({what}) for " + f"{save_path!r}; supported extensions are " + f"{_SUPPORTED_ANIMATION_EXTENSIONS}. (For a static image " + "instead, pass animate=False.)") + + +def _grid_caption_font(font, text): + """``(font, family)`` for a panel grid's caption, resolved from the + call's `font=` exactly as a single plot resolves its text: an explicit + font is applied as given, and without one the caption uses hypertools' + fallback font stack (plus an auto-detected family when `text` has + characters the stack cannot draw).""" + resolved = resolve_font(font, [text]) + if font is not None: + return resolved, None + return None, sans_serif_stack( + extra=resolved.get_name() if resolved is not None else None) + + +def _add_grid_caption(fig, caption, dynamic_caption, panel_axes, font, + context=None): + """Draw a panel grid's caption and return its ``Text``. A dynamic + caption (pattern or callable) is resolved for `context` -- frame 0 of + an animated grid -- or, without one, for the finished static figure.""" + text = caption + if dynamic_caption is not None: + if context is None: + context = FrameContext( + frame=None, n_frames=None, figure=fig, + axes=tuple(panel_axes), style=False, progress=1.0) + text = _resolve_dynamic_title_text(dynamic_caption, context, + name='caption') + resolved_font, family = _grid_caption_font(font, text) + return _add_caption(fig, text, font=resolved_font, family=family) + + +def _panel_grid_context(fig, cells, frame, n_frames): + """The figure-level `FrameContext` of an animated panel grid's frame + (GH #295), built from what every panel's updater just recorded. + + ``panels`` holds one ordinary `FrameContext` per panel (its own axes, + artists, datasets and reveal state). The grid's own fields describe + the whole figure: ``axes`` is a tuple of the panel axes, ``artists`` + and ``datasets`` every panel's in panel order, and ``revealed_counts`` + / ``window_bounds`` likewise (None when any panel has none). The + per-dataset reveal position (``current_index``/``current_fraction``) + has no figure-level meaning and is None; read it from ``panels``. + """ + panel_contexts = tuple( + FrameContext(figure=fig, axes=cell['axes'], + **{**cell['hooks'].state, + 'frame': frame, 'n_frames': n_frames}) + for cell in cells) + + def _joined(name): + values = [getattr(ctx, name) for ctx in panel_contexts] + if any(v is None for v in values): + return None + return tuple(item for v in values for item in v) + + def _common(name): + values = {getattr(ctx, name) for ctx in panel_contexts} + return values.pop() if len(values) == 1 else None + + first = panel_contexts[0] + return FrameContext( + frame=frame, n_frames=n_frames, figure=fig, + axes=tuple(cell['axes'] for cell in cells), + artists=_joined('artists') or (), + datasets=_joined('datasets') or (), + style=first.style, order=first.order, + revealed_counts=_joined('revealed_counts'), + window_bounds=_joined('window_bounds'), + segment_index=_common('segment_index'), + segment_kind=_common('segment_kind'), + panels=panel_contexts) + + +#: how much of its axes' square a rotating panel cube may fill, at most +_PANEL_CUBE_FILL = 0.96 + + +def _cube_reach(axis): + """How far a 3-D axes' cube reaches from the center of the square the + axes is drawn in, at the widest camera angle of a full turn (at the + axes' current elevation and box zoom): 0.5 is the square's edge.""" + import itertools + from mpl_toolkits.mplot3d import proj3d + elev, azim0 = axis.elev, axis.azim + corners = np.array(list(itertools.product( + axis.get_xlim3d(), axis.get_ylim3d(), axis.get_zlim3d()))) + reach = 0.0 + for azim in np.arange(0.0, 360.0, 3.0): + axis.view_init(elev=elev, azim=azim) + px, py, _ = proj3d.proj_transform( + corners[:, 0], corners[:, 1], corners[:, 2], axis.get_proj()) + # fractions of the axes' square: 0.5 is its center + frac = axis.transLimits.transform(np.column_stack([px, py])) + reach = max(reach, float(np.abs(frac - 0.5).max())) + axis.view_init(elev=elev, azim=azim0) + return reach + + +def _axis_label_reach(fig, cells, step=30.0): + """Per cell, how far its 3-D AXIS LABELS reach from the center of the + axes' square over a full turn (0.5 is the square's edge; 0.0 for a + cell without labels). Label placement is matplotlib's, decided at draw + time, so this draws the figure once per sampled camera angle.""" + reaches = [0.0] * len(cells) + views = [(cell['axes'].elev, cell['axes'].azim) for cell in cells] + for azim in np.arange(0.0, 360.0, step): + for cell, (elev, _) in zip(cells, views): + cell['axes'].view_init(elev=elev, azim=azim) + renderer = _measurement_renderer(fig) + for k, cell in enumerate(cells): + axis = cell['axes'] + to_square = axis.transAxes.inverted() + for axis3d in axis._axis_map.values(): + label = axis3d.label + if not (label.get_text() and label.get_visible()): + continue + box = label.get_window_extent(renderer) + frac = to_square.transform(box.get_points()) + reaches[k] = max(reaches[k], + float(np.abs(frac - 0.5).max())) + for cell, (elev, azim) in zip(cells, views): + cell['axes'].view_init(elev=elev, azim=azim) + return reaches + + +#: the least a LABELED rotating panel cube may reach from the center of its +#: axes' square (0.5 is the square's edge): below this the cube is too +#: small beside its own axis labels, and the figure grows instead +_PANEL_LABELED_CUBE_REACH = 0.3 + + +def _fit_rotating_cubes(fig, cells, resize=True, _name='panels'): + """Zoom every animated 3-D panel out until its cube -- and its axis + labels, when it has any -- stay inside the panel's own cell at EVERY + camera angle of the rotation (GH #295). + + A single animated 3-D plot gives its axes the whole canvas, because the + cube an animation draws -- zoomed, and wider on screen when seen + corner-on -- overflows a normal subplot box at some angles (the frame + and the data are drawn unclipped). In a grid that overflow would run + into the panel's own title and legend and into the next panel. So the + cube's projected extent is measured over a full turn, at the panel's + own elevation and zoom, and the panel's box zoom is lowered + (`PanelAnimationStub.zoom_scale`) until the widest view fits the square + matplotlib draws a 3-D axes in -- which the title sits above and the + legend beside. A panel whose cube already fits is left alone, and 2-D + panels have no camera and are never touched. + + Axis labels (`xlabel=`/`ylabel=`/`zlabel=`) hang a fixed distance + outside the cube and swing around with it, so a labeled panel's cube is + drawn smaller still, until the labels fit too. That distance does not + shrink with the figure: in a small cell the labels would leave the cube + almost no room, so the whole figure is enlarged first (`resize`, i.e. + no explicit `size=`), and with an explicit `size=` too small for them + this raises, naming the size that would do. + """ + cubes = [cell for cell in cells if hasattr(cell['axes'], 'get_proj')] + limit = 0.5 * _PANEL_CUBE_FILL + + def _fit_cube(cell, target): + # the projection is perspective, so the reach is not exactly linear + # in the zoom: correct and re-measure (two passes settle it) + for _ in range(4): + # frame 0 sets the panel's elevation and applies its box zoom + cell['stub'].draw(0) + cell['reach'] = _cube_reach(cell['axes']) + if abs(cell['reach'] - target) <= 0.001 * target or ( + target >= limit and cell['reach'] <= target): + break + cell['stub'].zoom_scale[0] *= target / cell['reach'] + + for cell in cubes: + _fit_cube(cell, limit) + labeled = [cell for cell in cubes + if any(axis3d.label.get_text() + for axis3d in cell['axes']._axis_map.values())] + if labeled: + # how far the labels stand outside the cube, in square widths + gaps = [max(0.0, label_reach - cell['reach']) + for cell, label_reach in zip( + labeled, _axis_label_reach(fig, labeled))] + width, height = fig.get_size_inches() + grow_w = grow_h = 1.0 + for cell, gap in zip(labeled, gaps): + # the side this panel's square needs for its labels to leave + # the cube its share, against the cell's own width and height + # (the square is the smaller of the two) + box = cell['axes'].get_position(original=True) + cell_w, cell_h = box.width * width, box.height * height + side = (min(cell_w, cell_h) * gap + / (limit - _PANEL_LABELED_CUBE_REACH)) + grow_w = max(grow_w, side / cell_w) + grow_h = max(grow_h, side / cell_h) + if grow_w > 1.0 or grow_h > 1.0: + if not resize: + raise ValueError( + f"the axis labels (xlabel=/ylabel=/zlabel=) of this " + f"animated 3-D {_name}= grid swing around each panel's " + f"rotating cube and need more room than a " + f"{width:g} x {height:g} inch figure gives each panel. " + f"Pass a larger size= (about " + f"({width * grow_w:.1f}, {height * grow_h:.1f}) or " + "more), leave size= out to have the figure sized for " + "them, or drop the axis labels.") + # the labels' distance from the cube is fixed in points, so a + # larger figure is what gives the cube its share back + fig.set_size_inches(width * grow_w, height * grow_h) + for _ in range(5): + if not labeled: + break + over = [] + for cell, label_reach in zip(labeled, + _axis_label_reach(fig, labeled)): + excess = label_reach - limit + if excess <= 0.005: + continue + # pull the cube in by what the labels overshoot + _fit_cube(cell, max(0.1, cell['reach'] - excess)) + over.append(cell) + labeled = over + for cell in cubes: + # leave every panel showing frame 0 at its final zoom + cell['stub'].draw(0) + + +def _animate_panel_grid(fig, cells, panel_axes, panel_models, grid, + grid_hooks, caption, dynamic_caption, font, + save_path, show, return_model, shared_pipeline, + resize=True, _name='panels'): + """Turn a drawn grid of animated panels into ONE animation (GH #295). + + Every panel call left its frame function in `cells` (a + `PanelAnimationStub`, already wrapped with that panel's own per-frame + updaters: dynamic title, forecasts, per-point colors). This builds the + single `FuncAnimation` whose frame function draws frame ``num`` of + every panel -- one clock for the whole figure -- then updates the + caption and calls the grid's `on_frame=` callbacks once, with a + figure-level `FrameContext` (see `_panel_grid_context`). Saves, closes + and returns exactly as an animated single-axes call does: a + `HyperAnimation`, or the panel bundle with ``'animation'`` added when + `return_model=True`. + """ + from .animate import HyperFuncAnimation + from .hyper_animation import HyperAnimation, mark_draw_started + from .matplotlib_backend import _make_save_dpi_safe + + def _abandon(): + # an error before the animation is handed back: leave no figure + # registered with pyplot behind (as the single-axes path does) + if not show: + plt.close(fig) + + frame_counts = [int(cell['stub']._save_count) for cell in cells] + if len(set(frame_counts)) != 1: + _abandon() + raise ValueError( + f"an animated {_name}= grid runs every panel on one clock, but " + f"the panels would draw different numbers of frames " + f"({frame_counts}, in panel order). Give every panel the same " + "schedule: the same number of datasets per panel for " + "animate='morph', and scalar duration=/frame_rate=/rotations=.") + n_frames = frame_counts[0] + interval = cells[0]['stub']._interval + try: + _fit_rotating_cubes(fig, cells, resize=resize, _name=_name) + except Exception: + _abandon() + raise + + def _draw_panels(num): + for cell in cells: + cell['stub'].draw(num) + return _panel_grid_context(fig, cells, num, n_frames) + + caption_artist = None + if caption is not None or dynamic_caption is not None: + try: + # frame 0's text sizes the caption strip, and is what a still + # of the figure shows; the panels are drawn at frame 0 to get + # its context (frames are idempotent, see `FrameContext`) + caption_artist = _add_grid_caption( + fig, caption, dynamic_caption, panel_axes, font, + context=(_draw_panels(0) if dynamic_caption is not None + else None)) + except Exception: + _abandon() + raise + + def _grid_frame(num, *_): + context = _draw_panels(num) + if dynamic_caption is not None: + caption_artist.set_text(_resolve_dynamic_title_text( + dynamic_caption, context, name='caption')) + for callback in grid_hooks.callbacks: + callback(context) + + line_ani = HyperFuncAnimation( + fig, _grid_frame, n_frames, interval=interval, blit=False, + repeat=False) + # a morph grid's panels share one hold/transition schedule (they have + # the same frame count); `HyperAnimation.n_segments` reads this + segments = {getattr(cell['stub'], '_hyp_morph_segments', None) + for cell in cells} + if len(segments) == 1 and None not in segments: + line_ani._hyp_morph_segments = segments.pop() + _make_save_dpi_safe(line_ani) + if save_path is not None: + frame_rate = 1000.0 / interval + if abs(frame_rate - round(frame_rate)) < 1e-6: + frame_rate = int(round(frame_rate)) + try: + _save_animation(line_ani, save_path, frame_rate) + except Exception: + mark_draw_started(line_ani) + _abandon() + raise + if not show: + # the same close an animated single-axes call makes (see `plot`): + # deregister the figure from pyplot, keep its canvas, and drop the + # animation's pending first-draw hook + live_canvas = fig.canvas + plt.close(fig) + if fig.canvas is not live_canvas: + fig.set_canvas(live_canvas) + first_draw_id = getattr(line_ani, '_first_draw_id', None) + if first_draw_id is not None: + try: + fig.canvas.mpl_disconnect(first_draw_id) + except Exception: + pass + line_ani._first_draw_id = None + + if return_model: + mark_draw_started(line_ani) + for model in panel_models: + # a panel has no animation of its own: the grid's drives it + model['animation'] = None + return { + 'fig': fig, + 'axes': panel_axes, + 'panels': grid, + 'panel_models': panel_models, + 'xform_data': [m['xform_data'][0] if len(m['xform_data']) == 1 + else m['xform_data'] for m in panel_models], + 'colors': panel_models[0].get('colors') if panel_models else None, + 'pipeline': shared_pipeline, + 'animation': line_ani, + } + anim = HyperAnimation(fig, line_ani, frame_hooks=grid_hooks) + anim.colors = cells[0]['colors'] if cells else None + return anim + + + def _plot_panels_plotly(panel_data, panel_kwargs, titles, nrows, ncols, ndims, call_kwargs, shared_pipeline=None, panel_pipelines=None): @@ -4946,6 +5513,7 @@ def plot( label_anchor=None, legend_kwargs=None, legend_colors=None, + caption=None, **kwargs, ): """ @@ -6354,6 +6922,8 @@ def plot( low-opacity trail (past / future / whole, per its flag) led by a short opaque comet-head, while already-revealed datasets stay fully drawn and future ones stay invisible -- see `bullettime` below. + With `panels=` (matplotlib) the whole grid is one animation and + the mode plays in every panel on a shared clock -- see `panels=`. 2-D animations (round17 #9, GH #123): every style EXCEPT `'spin'` works for `ndims=2` as well as `ndims=3`, in both backends, using a @@ -6951,6 +7521,11 @@ def plot( portable across backends; every other field is identical across backends. + With an animated `panels=` grid the callback is called once per + frame for the whole figure, with ``ctx.axes`` a tuple of the panel + axes and ``ctx.panels`` one per-panel ``FrameContext`` each (see + `panels=`). + >>> import numpy as np >>> import hypertools as hyp >>> data = [np.cumsum(np.random.default_rng(0).standard_normal( @@ -6959,6 +7534,54 @@ def plot( ... ctx.axes.set_title(f'frame {ctx.frame} of {ctx.n_frames}') >>> anim = hyp.plot(data, animate=True, on_frame=annotate, show=False) + caption (matplotlib only) : str, callable, or None + One line of text centered UNDER the figure -- under the plot, its + legend and colorbar, any `companion=` panel, or a whole `panels=` + grid -- such as a running "timepoint 201 of 300" or a date beneath + a row of animated panels. It takes the forms a per-frame `title=` + takes: + + * a plain string, drawn as given on every frame; + * a format pattern containing ``{index`` (``'{index}'``, + ``'{index:%B %Y}'``), formatted on every frame with the input's + own row-index value under the reveal head -- the first dataset + that carries an index is read, exactly as for `title=`; + * a callable ``ctx -> str`` given that frame's ``FrameContext``, + e.g. ``lambda ctx: f'timepoint {ctx.frame + 1} of + {ctx.n_frames}'``. It must return a string. + + On an ANIMATED plot the caption is updated on every frame (a + `panels=` grid's callable gets the figure-level context described + under `panels=`). On a STATIC plot it is drawn once: a pattern or + callable is resolved for the finished figure, as a dynamic + `title=` is (``frame``/``n_frames`` are None and ``progress`` is + 1.0, so a pattern shows the LAST row's index). + + The caption sits a small gap below the lowest thing drawn. Where + the figure has no blank room there -- an animated 3-D plot fills + its canvas -- the figure is made taller by the caption's height, + and nothing already drawn moves or shrinks, so the caption never + overlaps a panel, a legend or a colorbar and never leaves the + canvas. Room is made for as many lines as the first frame's + caption has (``'\\n'`` starts a new line); keep later frames to + that many. It is drawn in the plot's font (`font=`), at the + default text size; it is a matplotlib ``Text`` with + ``gid='hypertools-caption'``, should you want to restyle it:: + + caption = anim.figure.findobj( + lambda a: a.get_gid() == 'hypertools-caption')[0] + caption.set_color('gray') + + Raises ``NotImplementedError`` under ``backend='plotly'`` (use a + per-frame `title=` there, which both backends support) and + ``ValueError`` with a caller-supplied `ax=`, whose figure is the + caller's to lay out. Default None (no caption). + + >>> anim = hyp.plot(data, animate=True, duration=1, show=False, + ... caption=lambda ctx: f'frame {ctx.frame + 1}') + >>> anim.draw_frame(4).figure.texts[-1].get_text() + 'frame 5' + simplify : bool Whether hypertools may silently downsample to keep a render tractable. Today this governs ``animate='morph'`` **only**: a morph @@ -7138,12 +7761,11 @@ def plot( survives both ``draw_frame`` and ``save`` (measured). Use ``on_frame=`` for decoration that must CHANGE with the frame, such as a marker tracking the head of a trace. - Several animated panels in one figure are not supported; lay the - panels out in the DATA instead (translate each column group into its - own region of one shared frame) and make a single plot call. + For several animated panels in one figure, pass ``panels=`` with + ``animate=`` (one animation of the whole grid; see `panels=`). panels : bool, int, (nrows, ncols), or None - Draw one STATIC panel per dataset in a single figure, instead of + Draw one panel per dataset in a single figure, instead of every dataset on one axes -- the built-in form of the ``fig, axes = plt.subplots(nrows, ncols, subplot_kw={'projection': '3d'}); for ax, d in zip(axes.ravel(), @@ -7218,10 +7840,42 @@ def plot( `forecast_cluster=` groups each panel's own forecast endpoints (with a single model, one per panel -- it then warns and inherits). - STATIC ONLY: combining `panels=` with any truthy `animate=` raises - ``ValueError`` (an animation owns its whole figure -- see `ax=`), as - does combining it with `ax=` or `explore=True`. Under - `backend='plotly'` the same grid is built with + ANIMATED GRIDS (matplotlib only). With a truthy `animate=` the + whole grid is ONE animation: every panel runs on the same clock + (`duration=` x `frame_rate=` frames), and one ``HyperAnimation`` is + returned for the figure -- ``hyp.plot([a, b, c, d], panels=(1, 4), + animate=True, duration=10, caption='{index}', + save_path='grid.mp4')`` writes one video of four panels. Each + panel is animated exactly as the single-axes call for its data is: + every `animate=` style and `order=` value, `tail_duration=`, + `rotations=`, the trail flags, `predict=`, per-frame titles and so + on apply PER PANEL. In particular the ordering is per panel, not + across panels: ``order='serial'`` reveals the datasets of each + panel one after another (with one dataset per panel, every panel + simply reveals its own), and the panels never take turns. Every + panel must draw the same number of frames (``animate='morph'`` + needs the same number of datasets in each panel), or the call + raises ``ValueError``. Each 3-D panel's cube is zoomed out as far + as it takes to stay inside its own cell through the whole + rotation, so `zoom=` can shrink a panel's cube but cannot enlarge + it past its cell; with axis labels (`xlabel=`/`ylabel=`/`zlabel=`) + the figure is enlarged so the rotating labels fit as well (an + explicit `size=` too small for them raises, naming a size that + fits). `caption=` adds a line of text under the grid, updated + every frame. `on_frame=` is called ONCE per frame for the whole + figure: its ``FrameContext`` has ``axes`` as a tuple of the panel + axes, ``artists`` and ``datasets`` as every panel's in panel + order, and ``panels`` as one ordinary per-panel ``FrameContext`` + each (that panel's own axes, artists and reveal state). + `return_model=True` returns the panel bundle described below with + ``'animation'`` (the grid's ``FuncAnimation``) added. Not + supported, each with an error saying so: ``backend='plotly'`` + (``NotImplementedError``; a static plotly grid works), + `companion=`, and panels whose analyzed data differ in width. + + Combining `panels=` with `ax=` or `explore=True` raises + ``ValueError``. Under + `backend='plotly'` the same (static) grid is built with `plotly.subplots.make_subplots` (3-D panels as ``type='scene'`` cells), and `return_model=True` returns the SAME bundle keys there as on matplotlib (``fig``, ``axes``, ``panels``, ``panel_models``, @@ -7730,7 +8384,9 @@ def plot( of everything the animation draws, measured from rendered pixels in figure fractions -- see `HyperAnimation.drawn_extent`) and auto-plays inline in notebooks -- keep a reference to it so the - underlying ``matplotlib.animation.FuncAnimation`` stays alive. + underlying ``matplotlib.animation.FuncAnimation`` stays alive. An + animated `panels=` grid returns ONE ``HyperAnimation`` for the + whole figure. When ``return_model=True``, a dict ``{'fig': ..., 'xform_data': ..., 'trace_data': ..., 'trace_metadata': ..., 'animation': ..., 'pipeline': ..., @@ -7770,6 +8426,11 @@ def plot( # rows in its 3-D cell (`_PanelLift`, one entry per dataset of the # panel, None for 3-wide ones): internal, never a user kwarg _panel_lift = kwargs.pop('_panel_lift', None) + # ...and its marker that this call draws ONE PANEL OF AN ANIMATED GRID + # into the given `ax=` (GH #295): a list the call appends its frame + # function, frame hooks and axes to (`_plot_animated_panels` collects + # them into the grid's single animation). Internal, never a user kwarg. + _panel_animation = kwargs.pop('_panel_animation', None) # early kwarg validation (release-1.0 audit): catch renamed/misspelled/ # unknown keyword arguments HERE, with a clear TypeError naming the @@ -7785,8 +8446,8 @@ def plot( palette, forecast_palette, sort=palette_sort, reduce=palette_reduce, manip=palette_manip, normalize=palette_normalize, align=palette_align) - # panels=/subplots= (GH #285): compose several STATIC panels in one - # figure. Handled by re-entering plot() once per panel, so this branch + # panels=/subplots= (GH #285): compose several panels (static, or + # animated together, GH #295) in one figure. Handled by re-entering plot() once per panel, so this branch # runs BEFORE any other local exists -- `locals()` here is exactly this # call's own arguments, which is what each panel call is rebuilt from. if panels is not None and subplots is not None: @@ -7799,7 +8460,7 @@ def plot( _panel_call = {k: v for k, v in locals().items() if k not in ('x', 'kwargs', 'panels', 'subplots', '_panels_spec', '_panels_name', - '_panel_lift')} + '_panel_lift', '_panel_animation')} _panel_call.update(kwargs) return _plot_panels(x, _panels_spec, _panel_call, _name=_panels_name) @@ -8268,6 +8929,10 @@ def plot( _resolved_order) _companion = _validate_companion(companion, animate, resolve_backend(backend)) + # GH #295: `caption=` -- a figure-level caption under the plot, in the + # forms `title=` takes (fixed text, a `{index...}` pattern, a callable). + caption, _dynamic_caption = _validate_caption( + caption, _row_indices, resolve_backend(backend), ax=ax) # fail-fast on on_frame= (plan 1.1 Task 7, same precedent as title=/ # order= above): needs only its own callability and the raw animate= @@ -8490,7 +9155,8 @@ def plot( # installed fonts. xlabel/ylabel/zlabel are drawn text too (fresh-Colab # review 2026-09-11: an axis label alone in a script outside the stack # rendered as tofu). - _font_texts = [labels, legend, title, hue, xlabel, ylabel, zlabel] + _font_texts = [labels, legend, title, hue, xlabel, ylabel, zlabel, + caption] if colorbar is not None: _font_texts.append(colorbar.get('label')) _font_texts.append(colorbar.get('ticks')) @@ -8695,14 +9361,14 @@ def plot( # the DATA instead -- translate each group into its own region of one # shared frame -- which keeps it to a single call and a single # animation (see `examples/`). - if _raw_animate_style(animate): + if _raw_animate_style(animate) and _panel_animation is None: raise ValueError( "ax= cannot be combined with animate=: an animated plot owns " "its own figure, so the axes you passed would be left empty " "and the animation drawn somewhere else. Drop ax= and use the " "returned animation's .figure (or .figure.axes[0]) to style " - "what was drawn; for several panels in one animation, lay the " - "panels out in the data and make a single plot call." + "what was drawn; for several panels in one animation, pass " + "panels= (one animated panel per dataset, on one clock)." ) if ndims > 2: # a 2-D axes under the default (3-D) ndims: whether the plot IS @@ -12685,6 +13351,7 @@ def _plotly_before_show(drawn): xlim=_data_xlim, ylim=_data_ylim, x_date=_series_is_date, + panel_cell=_panel_animation is not None, ) if ax is not None and hasattr(ax, 'set_prop_cycle'): # what a later `ax=` call continues the palette @@ -13221,6 +13888,7 @@ def _hyp_frame_with_hooks(num, *fargs, # animations (whose default, non-maximized axes already leave # normal title room) are never touched. if (ax is not None and line_ani is not None + and _panel_animation is None and xform[0].shape[1] >= 3 and (title is not None or _segment_titles is not None or _dynamic_title is not None @@ -13285,7 +13953,24 @@ def _hyp_frame_with_hooks(num, *fargs, setattr(fig, _HYP_FIGURE_ATTR, True) _caller_figure = _user_supplied_ax and not getattr( fig, _HYP_FIGURE_ATTR, False) - if (not animate and not _caller_figure + # A cell of an animated panel grid (GH #295) is laid out like a + # static cell: the grid's figure is hypertools' own, and the + # legend fit below must measure the cell where the layout puts + # it (unfitted, it repositioned the cell by hand, which takes + # an axes out of every later `tight_layout`). + if _panel_animation is not None and ax is not None: + # ...but its ANIMATED artists must not drive that layout: + # before the first frame they are one-point stubs (a morph + # cloud, an unclipped trail) whose extents say nothing + # about what the panel will show, and what it will show + # stays inside the cell's own box at every frame (see + # `_fit_rotating_cubes`). The box, the title, the legend + # and the axis labels are what the layout arranges. + for _artist in (list(ax.lines) + list(ax.collections) + + list(ax.patches)): + _artist.set_in_layout(False) + if ((not animate or _panel_animation is not None) + and not _caller_figure and isinstance(fig, plt.Figure)): fig.tight_layout() @@ -13375,6 +14060,61 @@ def _update_companions(ctx, _drawn=_panels_drawn): for _panel in _panels_drawn: update_companion_panel(_panel, 0) + # caption= (GH #295): one figure-level line of text under + # everything drawn above -- the plot, its legend and colorbar, + # any companion panel -- so it is added LAST, in a strip the + # figure grows downward by (nothing already drawn moves or + # shrinks). A dynamic caption is driven per frame by an + # internal updater, like a dynamic title; frame 0's text (the + # finished figure's, for a static plot) is resolved here, both + # to size the strip and so a still of the figure carries it. + if (caption is not None or _dynamic_caption is not None) \ + and isinstance(fig, plt.Figure): + _caption_text = caption + if _dynamic_caption is not None: + _static_ctx = not animate or line_ani is None + try: + _caption_text = _resolve_dynamic_title_text( + _dynamic_caption, FrameContext( + frame=None if _static_ctx else 0, + n_frames=(None if _static_ctx + else int(line_ani._save_count)), + figure=fig, axes=ax, + datasets=tuple(xform), + style=animate if animate else False, + order=order, + current_index=( + 0 if order == 'serial' + and not _static_ctx else None), + revealed_counts=tuple( + len(d) if _static_ctx else 1 + for d in xform), + window_bounds=( + tuple((0, len(d)) for d in xform) + if _static_ctx else None), + progress=1.0 if _static_ctx else None), + name='caption') + except Exception: + # see the dynamic-title probe above: the user's + # callable raised before any animation was handed + # back, so detach it and close the abandoned figure + if line_ani is not None: + from .hyper_animation import mark_draw_started + mark_draw_started(line_ani) + if (not show and not _user_supplied_ax + and isinstance(fig, plt.Figure)): + plt.close(fig) + raise + _caption_artist = _add_caption( + fig, _caption_text, font=_artist_font, + family=list(plt.rcParams['font.family'])) + if _dynamic_caption is not None and line_ani is not None: + def _update_caption(ctx, _fn=_dynamic_caption, + _artist=_caption_artist): + _artist.set_text(_resolve_dynamic_title_text( + _fn, ctx, name='caption')) + _frame_hooks.add_internal(_update_caption) + # save. `fig.savefig`, NOT `plt.savefig` (release-1.0 audit, # F09-001: `plt.savefig` writes pyplot's CURRENT figure, so # with a user-supplied ax= whose figure was not current the @@ -13452,6 +14192,15 @@ def _update_companions(ctx, _drawn=_panels_drawn): pass line_ani._first_draw_id = None + if _panel_animation is not None: + # one panel of an animated grid (GH #295): hand the grid this + # panel's frame function (the stub `_draw` returned, wrapped above + # exactly as a `FuncAnimation`'s would be), its frame hooks and its + # axes. The grid builds the one animation. + _panel_animation.append({ + 'stub': line_ani, 'hooks': _frame_hooks, 'axes': ax, + 'colors': colors_info}) + if return_model: # gather reduce params (spec, not a fitted instance) if isinstance(reduce, dict): @@ -13632,7 +14381,7 @@ def _update_companions(ctx, _drawn=_panels_drawn): # then `anim.to_html5_video()` works (it used to fail on the bare tuple). # HyperAnimation still unpacks as the legacy (figure, animation) tuple, so # `fig, anim = hyp.plot(...)` keeps working too. - if line_ani is not None: + if line_ani is not None and _panel_animation is None: from .hyper_animation import HyperAnimation _hyper_anim = HyperAnimation(fig, line_ani, frame_hooks=_frame_hooks) # GH #285: the resolved color scale, so a companion panel can From c75df702a24c08a171b05be2758ffaa5258af58f Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 05:01:47 -0500 Subject: [PATCH 10/58] test: animated panel grids and caption= (GH #295) New real-figure tests for the grid animation and the caption. The tests that asserted the old panels= + animate= refusal now assert the animation, and the three trail keywords are checked per panel on an animated grid. The 1.1.0 changelog tests read that release's own Added subsection. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- tests/test_animated_panels.py | 701 ++++++++++++++++++++++++++++++++ tests/test_changelog_1_1.py | 10 +- tests/test_plot_caption.py | 463 +++++++++++++++++++++ tests/test_plot_panels.py | 27 +- tests/test_plot_panels_audit.py | 63 ++- 5 files changed, 1246 insertions(+), 18 deletions(-) create mode 100644 tests/test_animated_panels.py create mode 100644 tests/test_plot_caption.py diff --git a/tests/test_animated_panels.py b/tests/test_animated_panels.py new file mode 100644 index 000000000..becb89c74 --- /dev/null +++ b/tests/test_animated_panels.py @@ -0,0 +1,701 @@ +"""Animated panel grids: `animate=` together with `panels=` (GH #295). + +`hyp.plot([a, b, c, d], panels=(1, 4), animate=True)` gives ONE animation of +the whole grid: one clock for every panel, each panel animated exactly as +the single-axes call for its data is, and one `HyperAnimation` returned for +the figure. + +Real figures, real frames, rendered headless: every assertion reads artists, +camera angles and extents back off the returned figure after drawing real +frames, or reads a file a real writer produced. Nothing is mocked. +""" +import itertools +import shutil +import subprocess +import warnings + +import matplotlib +matplotlib.use('Agg') + +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +import pytest +from matplotlib.animation import FuncAnimation +from mpl_toolkits.mplot3d import proj3d + +import hypertools as hyp +from hypertools.plot.hyper_animation import HyperAnimation +from hypertools.plot.plot import subplots as hyp_subplots + +HAS_FFMPEG = shutil.which('ffmpeg') is not None +HAS_FFPROBE = shutil.which('ffprobe') is not None + + +def _walk(seed, rows=40, cols=5): + rng = np.random.default_rng(seed) + return np.cumsum(rng.normal(size=(rows, cols)), axis=0) + + +DATA = [_walk(seed) for seed in range(4)] + + +def _grid(data=None, **kwargs): + """An animated grid with short, test-sized defaults.""" + call = dict(panels=(1, 4), animate=True, duration=1, frame_rate=8, + show=False) + call.update(kwargs) + return hyp.plot(DATA if data is None else data, **call) + + +def _panel_axes(fig): + """The grid's visible panel axes (not colorbar axes), in panel order.""" + return [ax for ax in fig.axes + if ax.get_visible() and not hasattr(ax, '_colorbar') + and ax.get_label() != ''] + + +def _line_data(line): + """A drawn line's coordinates as one (n_points, n_dims) array.""" + if hasattr(line, 'get_data_3d'): + return np.column_stack([np.asarray(c, dtype=float) + for c in line.get_data_3d()]) + return np.column_stack([np.asarray(c, dtype=float) + for c in line.get_data()]) + + +def _drawn(ax): + """Everything the panel's data lines show right now, concatenated.""" + return np.vstack([_line_data(line) for line in ax.lines]) + + +@pytest.fixture(autouse=True) +def _close_figures(): + yield + plt.close('all') + + +# --- the returned object ------------------------------------------------ + +def test_an_animated_grid_returns_one_hyper_animation_for_the_figure(): + anim = _grid() + assert isinstance(anim, HyperAnimation) + assert isinstance(anim.animation, FuncAnimation) + fig, raw = anim # still unpacks as (figure, animation) + assert fig is anim.figure and raw is anim.animation + axes = _panel_axes(fig) + assert len(axes) == 4 + assert all(ax.name == '3d' for ax in axes) + # ONE animation drives the figure, not one per panel + assert all(ax.figure is fig for ax in axes) + + +@pytest.mark.parametrize('duration, frame_rate', [(1, 8), (2, 5), (0.5, 12)]) +def test_the_grid_draws_duration_times_frame_rate_frames(duration, + frame_rate): + anim = _grid(duration=duration, frame_rate=frame_rate) + assert anim.n_frames == int(round(duration * frame_rate)) + + +def test_subplots_alias_animates_the_same_grid(): + anim = hyp.plot(DATA, subplots=(2, 2), animate=True, duration=1, + frame_rate=8, show=False) + assert isinstance(anim, HyperAnimation) + assert len(_panel_axes(anim.figure)) == 4 + + +def test_spare_cells_stay_hidden(): + anim = _grid(DATA[:3], panels=(2, 2)) + assert sum(ax.get_visible() for ax in anim.figure.axes) == 3 + + +def test_show_false_leaves_no_figure_registered_with_pyplot(): + before = set(plt.get_fignums()) + anim = _grid() + assert set(plt.get_fignums()) == before + # ...and the returned animation still draws + anim.draw_frame(3) + anim.figure.canvas.draw() + + +# --- one clock, every panel --------------------------------------------- + +def test_every_panels_artists_change_between_frames(): + anim = _grid() + axes = _panel_axes(anim.figure) + anim.draw_frame(1) + early = [_drawn(ax) for ax in axes] + anim.draw_frame(anim.n_frames - 1) + late = [_drawn(ax) for ax in axes] + for i, (a, b) in enumerate(zip(early, late)): + assert a.shape != b.shape or not np.allclose(a, b), ( + f'panel {i} drew the same thing on frames 1 and ' + f'{anim.n_frames - 1}: it is not on the shared clock') + + +def test_every_panel_rotates_its_own_camera_in_step(): + anim = _grid(rotations=1, duration=2) + axes = _panel_axes(anim.figure) + anim.draw_frame(0) + start = [ax.azim for ax in axes] + anim.draw_frame(anim.n_frames // 2) + middle = [ax.azim for ax in axes] + # every panel's camera moved, and all panels are at the same angle + for a, b in zip(start, middle): + assert abs(((b - a + 180) % 360) - 180) > 30 + assert np.allclose(middle, middle[0]) + assert np.allclose(start, start[0]) + + +def test_more_rotations_turn_every_camera_further(): + one = _grid(rotations=1, duration=2) + two = _grid(rotations=2, duration=2) + frame = 3 + one.draw_frame(0), two.draw_frame(0) + base = _panel_axes(one.figure)[0].azim + one.draw_frame(frame), two.draw_frame(frame) + for ax1, ax2 in zip(_panel_axes(one.figure), _panel_axes(two.figure)): + assert (ax2.azim - base) == pytest.approx(2 * (ax1.azim - base)) + + +#: every one of these is a per-panel animation setting: the grid must draw +#: each panel exactly as the single-axes call with the same setting does +_PER_PANEL_SETTINGS = { + 'parallel': dict(), + 'tail_duration': dict(tail_duration=0.25), + 'rotations': dict(rotations=2), + 'spin': dict(animate='spin'), + 'window': dict(animate='window', tail_duration=0.5), + 'chemtrails': dict(chemtrails=True), + 'precog': dict(precog=True), + 'serial': dict(order='serial'), + 'two-d': dict(ndims=2), + 'markers': dict(fmt='o'), + 'elevation': dict(elev=35), +} + + +@pytest.mark.parametrize('setting', sorted(_PER_PANEL_SETTINGS)) +def test_each_panel_is_animated_exactly_as_its_single_axes_call(setting): + """`panel_fit='independent'` fits each panel as `hyp.plot(x[i], ...)` + does, so the artists a grid panel shows on frame k must be the artists + that single-axes animation shows on frame k -- same rows, same trail, + same camera angle.""" + extra = _PER_PANEL_SETTINGS[setting] + data = DATA[:3] + grid = _grid(data, panels=(1, 3), panel_fit='independent', **extra) + axes = _panel_axes(grid.figure) + singles = [hyp.plot(d, animate=extra.get('animate', True), duration=1, + frame_rate=8, show=False, + **{k: v for k, v in extra.items() if k != 'animate'}) + for d in data] + assert all(single.n_frames == grid.n_frames for single in singles) + for frame in (0, grid.n_frames // 2, grid.n_frames - 1): + grid.draw_frame(frame) + for i, (ax, single) in enumerate(zip(axes, singles)): + single.draw_frame(frame) + single_ax = single.figure.axes[0] + assert len(ax.lines) == len(single_ax.lines) + for line, expected in zip(ax.lines, single_ax.lines): + got, want = _line_data(line), _line_data(expected) + assert got.shape == want.shape, (setting, frame, i) + assert np.allclose(got, want, equal_nan=True), ( + setting, frame, i) + assert line.get_alpha() == expected.get_alpha() + if ax.name == '3d': + assert ax.azim == pytest.approx(single_ax.azim) + assert ax.elev == pytest.approx(single_ax.elev) + + +def test_tail_duration_changes_what_every_panel_shows(): + short = _grid(animate='window', tail_duration=0.25, duration=2) + long_ = _grid(animate='window', tail_duration=1.0, duration=2) + frame = short.n_frames - 1 + short.draw_frame(frame), long_.draw_frame(frame) + for ax_short, ax_long in zip(_panel_axes(short.figure), + _panel_axes(long_.figure)): + assert len(_drawn(ax_short)) < len(_drawn(ax_long)) + + +def test_serial_order_plays_within_each_panel_not_across_panels(): + """order='serial' reveals each panel's own datasets one after another; + it is not a sequence across the panels.""" + anim = _grid(order='serial', duration=2) + axes = _panel_axes(anim.figure) + anim.draw_frame(anim.n_frames // 2) + # half way through, EVERY panel has revealed part of its own dataset + counts = [len(_line_data(ax.lines[0])) for ax in axes] + assert all(count > 1 for count in counts), counts + assert len(set(counts)) == 1, counts + + +# --- titles, legends, colorbars ----------------------------------------- + +def test_titles_are_per_panel(): + names = ['one', 'two', 'three', 'four'] + anim = _grid(title=names) + assert [ax.get_title() for ax in _panel_axes(anim.figure)] == names + + +def test_a_single_title_names_every_panel(): + anim = _grid(title='same') + assert [ax.get_title() for ax in _panel_axes(anim.figure)] == ['same'] * 4 + + +def test_a_callable_title_is_updated_per_panel_every_frame(): + anim = _grid(title=lambda ctx: f'frame {ctx.frame}') + anim.draw_frame(5) + assert [ax.get_title() for ax in _panel_axes(anim.figure)] == ( + ['frame 5'] * 4) + + +def test_every_panel_gets_its_legend(): + anim = _grid(legend=['a', 'b', 'c', 'd']) + legends = [ax.get_legend() for ax in _panel_axes(anim.figure)] + assert all(legend is not None for legend in legends) + assert [legend.get_texts()[0].get_text() for legend in legends] == ( + ['a', 'b', 'c', 'd']) + + +def test_every_panel_gets_its_colorbar(): + hue = [np.arange(len(d), dtype=float) for d in DATA[:3]] + anim = _grid(DATA[:3], panels=(1, 3), hue=hue, colorbar=True) + fig = anim.figure + # three panels and three colorbar axes + assert len(fig.axes) == 6 + assert sum(ax.name == '3d' for ax in fig.axes) == 3 + + +# --- fits --------------------------------------------------------------- + +def test_shared_fit_gives_the_static_grids_coordinates(): + """The pipeline is fit exactly as for a static grid; only the drawing + is animated.""" + static = hyp.plot(DATA, panels=(1, 4), show=False, return_model=True) + moving = _grid(return_model=True) + for a, b in zip(static['xform_data'], moving['xform_data']): + assert np.allclose(a, b) + assert moving['pipeline'] is not None + + +def test_independent_fit_differs_from_the_shared_fit(): + shared = _grid(return_model=True) + independent = _grid(panel_fit='independent', return_model=True) + assert independent['pipeline'] is None + assert any(not np.allclose(a, b) for a, b in + zip(shared['xform_data'], independent['xform_data'])) + + +def test_a_reducer_list_animates_one_panel_per_reducer(): + anim = _grid(DATA[:3], panels=True, reduce=['PCA', 'FastICA'], + title=['PCA', 'FastICA']) + axes = _panel_axes(anim.figure) + assert len(axes) == 2 + assert [ax.get_title() for ax in axes] == ['PCA', 'FastICA'] + # every panel draws EVERY dataset + assert all(len(ax.lines) == 3 for ax in axes) + anim.draw_frame(anim.n_frames - 1) + last = [_drawn(ax) for ax in axes] + # ...through a different reducer + assert last[0].shape != last[1].shape or not np.allclose(last[0], + last[1]) + # and each reducer panel matches that reducer's own single-axes call + single = hyp.plot(DATA[:3], reduce='PCA', animate=True, duration=1, + frame_rate=8, show=False) + single.draw_frame(single.n_frames - 1) + for line, expected in zip(axes[0].lines, single.figure.axes[0].lines): + assert np.allclose(_line_data(line), _line_data(expected)) + + +def test_a_morph_grid_reports_its_segments(): + anim = _grid(DATA[:3], panels=True, reduce=['PCA', 'FastICA'], + animate='morph', duration=2) + # three clouds: hold, move, hold, move, hold + assert anim.n_segments == 5 + anim.draw_frame(0) + first = [np.asarray(ax.collections[-1].get_offsets()) + if ax.collections else None + for ax in _panel_axes(anim.figure)] + anim.draw_frame(anim.n_frames - 1) + assert first is not None + + +def test_return_model_adds_the_animation_to_the_panel_bundle(): + bundle = _grid(return_model=True) + assert isinstance(bundle['animation'], FuncAnimation) + assert bundle['panels'] == (1, 4) + assert len(bundle['axes']) == len(bundle['panel_models']) == 4 + assert len(bundle['xform_data']) == 4 + # a panel has no animation of its own + assert all(model['animation'] is None + for model in bundle['panel_models']) + # the handle draws the grid + bundle['animation']._func(2) + assert bundle['fig'] is bundle['axes'][0].figure + + +# --- geometry: nothing leaves its cell or the canvas ---------------------- + +def _cube_corners_px(ax): + corners = np.array(list(itertools.product( + ax.get_xlim3d(), ax.get_ylim3d(), ax.get_zlim3d()))) + x, y, _ = proj3d.proj_transform(corners[:, 0], corners[:, 1], + corners[:, 2], ax.get_proj()) + return ax.transData.transform(np.column_stack([x, y])) + + +def _inside(inner, outer, slack=1.0): + return (inner.x0 >= outer.x0 - slack and inner.x1 <= outer.x1 + slack + and inner.y0 >= outer.y0 - slack and inner.y1 <= outer.y1 + slack) + + +@pytest.mark.parametrize('extra', [ + dict(), + dict(zoom=3), + dict(elev=45), + dict(panels=(2, 2)), + dict(panels=(4, 1)), + dict(animate='spin', rotations=2), +], ids=['default', 'zoom', 'elev', '2x2', '4x1', 'spin']) +def test_every_rotating_cube_stays_inside_its_own_cell(extra): + anim = _grid(duration=3, frame_rate=12, **extra) + fig = anim.figure + axes = _panel_axes(fig) + for frame in range(anim.n_frames): + anim.draw_frame(frame) + fig.canvas.draw() + for i, ax in enumerate(axes): + box = ax.get_window_extent() + corners = _cube_corners_px(ax) + assert corners[:, 0].min() >= box.x0 - 0.5, (frame, i) + assert corners[:, 0].max() <= box.x1 + 0.5, (frame, i) + assert corners[:, 1].min() >= box.y0 - 0.5, (frame, i) + assert corners[:, 1].max() <= box.y1 + 0.5, (frame, i) + + +def test_panel_boxes_do_not_overlap_each_other(): + anim = _grid(legend=['a', 'b', 'c', 'd'], title=['1', '2', '3', '4']) + fig = anim.figure + anim.draw_frame(0) + fig.canvas.draw() + boxes = [ax.get_window_extent() for ax in _panel_axes(fig)] + for a, b in itertools.combinations(boxes, 2): + assert not a.overlaps(b) + + +def test_titles_and_legends_stay_on_the_canvas_and_clear_of_the_cubes(): + anim = _grid(legend=['alpha', 'beta', 'gamma', 'delta'], + title=['one', 'two', 'three', 'four'], duration=2, + frame_rate=6) + fig = anim.figure + axes = _panel_axes(fig) + for frame in (0, anim.n_frames // 2, anim.n_frames - 1): + anim.draw_frame(frame) + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + canvas = fig.bbox + for i, ax in enumerate(axes): + title = ax.title.get_window_extent(renderer) + legend = ax.get_legend().get_window_extent(renderer) + assert _inside(title, canvas), (frame, i, 'title') + assert _inside(legend, canvas), (frame, i, 'legend') + corners = _cube_corners_px(ax) + # the title is above the cube, the legend to its right + assert title.y0 >= corners[:, 1].max(), (frame, i) + assert legend.x0 >= corners[:, 0].max(), (frame, i) + # ...and the legend stops short of the next panel's cube + if i + 1 < len(axes): + next_corners = _cube_corners_px(axes[i + 1]) + assert legend.x1 <= next_corners[:, 0].min(), (frame, i) + + +def test_axis_labels_enlarge_the_figure_and_stay_inside_their_cells(): + plain = _grid(DATA[:3], panels=(1, 3)) + labeled = _grid(DATA[:3], panels=(1, 3), xlabel='first axis', + ylabel='second axis', zlabel='third axis', duration=2, + frame_rate=6) + assert (labeled.figure.get_size_inches()[0] + > plain.figure.get_size_inches()[0]) + fig = labeled.figure + axes = _panel_axes(fig) + for frame in range(labeled.n_frames): + labeled.draw_frame(frame) + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + for i, ax in enumerate(axes): + box = ax.get_window_extent() + for axis in (ax.xaxis, ax.yaxis, ax.zaxis): + label = axis.label.get_window_extent(renderer) + # a few pixels of slack: matplotlib places the labels at + # draw time and the fit samples the turn every 30 degrees + assert _inside(label, box, slack=0.06 * box.width), ( + frame, i, axis.label.get_text()) + assert _inside(box, fig.bbox) + + +def test_two_d_panels_animate_in_fixed_boxes(): + anim = _grid(ndims=2, panels=(2, 2), title=['a', 'b', 'c', 'd']) + fig = anim.figure + axes = _panel_axes(fig) + assert all(ax.name == 'rectilinear' for ax in axes) + anim.draw_frame(0) + fig.canvas.draw() + before = [ax.get_position().bounds for ax in axes] + anim.draw_frame(anim.n_frames - 1) + fig.canvas.draw() + assert [ax.get_position().bounds for ax in axes] == before + for a, b in itertools.combinations( + [ax.get_tightbbox(fig.canvas.get_renderer()) for ax in axes], 2): + assert not a.overlaps(b) + + +# --- labels= ------------------------------------------------------------ + +def test_point_labels_follow_the_reveal_in_every_panel(): + """The annotation bookkeeping was one module-level list holding only + the LAST plot's labels, so in a grid only the last panel's labels + followed the animation.""" + labels = [[f'p{j}' if j in (0, 35) else None for j in range(len(d))] + for d in DATA[:3]] + anim = _grid(DATA[:3], panels=(1, 3), labels=labels, duration=2) + axes = _panel_axes(anim.figure) + + def visible(ax): + return sorted(text.get_text() for text in ax.texts + if text.get_visible()) + + anim.draw_frame(1) + early = [visible(ax) for ax in axes] + anim.draw_frame(anim.n_frames - 1) + late = [visible(ax) for ax in axes] + # the late point's label appears in EVERY panel only once it is reached + assert all('p35' not in shown for shown in early), early + assert all('p35' in shown for shown in late), late + + +# --- on_frame ----------------------------------------------------------- + +def test_on_frame_is_called_once_per_frame_for_the_whole_figure(): + seen = [] + anim = _grid(on_frame=seen.append) + assert seen == [] # nothing fires at construction + anim.draw_frame(3) + assert len(seen) == 1 + ctx = seen[0] + axes = _panel_axes(anim.figure) + assert ctx.frame == 3 and ctx.n_frames == anim.n_frames + assert ctx.figure is anim.figure + assert isinstance(ctx.axes, tuple) and list(ctx.axes) == axes + assert ctx.progress == pytest.approx(3 / (anim.n_frames - 1)) + + +def test_the_grid_context_holds_one_context_per_panel(): + seen = [] + anim = _grid(on_frame=seen.append) + anim.draw_frame(4) + ctx = seen[-1] + axes = _panel_axes(anim.figure) + assert len(ctx.panels) == 4 + for panel, ax in zip(ctx.panels, axes): + assert panel.axes is ax + assert panel.frame == 4 and panel.n_frames == anim.n_frames + assert all(artist.axes is ax for artist in panel.artists) + assert len(panel.datasets) == 1 + assert panel.revealed_counts is not None + # the figure-level fields are every panel's, in panel order + assert ctx.artists == tuple(a for p in ctx.panels for a in p.artists) + assert len(ctx.datasets) == 4 + assert ctx.revealed_counts == tuple( + c for p in ctx.panels for c in p.revealed_counts) + assert ctx.current_index is None + + +def test_a_single_axes_context_has_no_panels(): + seen = [] + anim = hyp.plot(DATA[0], animate=True, duration=1, frame_rate=8, + on_frame=seen.append, show=False) + anim.draw_frame(2) + assert seen[-1].panels == () + assert seen[-1].axes is anim.figure.axes[0] + + +def test_on_frame_can_be_attached_after_the_call(): + anim = _grid() + seen = [] + assert anim.on_frame(lambda ctx: seen.append(ctx.frame)) is anim + anim.draw_frame(2).draw_frame(5) + assert seen == [2, 5] + + +def test_on_frame_must_be_callable(): + with pytest.raises(TypeError, match='on_frame must be callable'): + _grid(on_frame=3) + + +# --- export ------------------------------------------------------------- + +def test_saving_a_gif_writes_every_frame_of_the_whole_grid(tmp_path): + from PIL import Image + out = tmp_path / 'grid.gif' + anim = _grid(save_path=str(out), title=['a', 'b', 'c', 'd']) + with Image.open(out) as im: + assert im.n_frames == anim.n_frames == 8 + width, height = im.size + fig = anim.figure + assert (width, height) == tuple( + int(v) for v in fig.get_size_inches() * fig.dpi) + # one wide image holding four panels, not one panel's worth + assert width > height + + +def test_the_saved_gif_shows_all_four_panels_moving(tmp_path): + from PIL import Image + out = tmp_path / 'grid.gif' + anim = _grid(save_path=str(out), duration=2) + fig = anim.figure + anim.draw_frame(0) + fig.canvas.draw() + width = fig.bbox.width + spans = [(ax.get_window_extent().x0 / width, + ax.get_window_extent().x1 / width) + for ax in _panel_axes(fig)] + with Image.open(out) as im: + im.seek(1) + early = np.asarray(im.convert('RGB')).astype(int) + im.seek(im.n_frames - 1) + late = np.asarray(im.convert('RGB')).astype(int) + changed = np.abs(early - late).max(-1) > 40 + for i, (x0, x1) in enumerate(spans): + band = changed[:, int(x0 * changed.shape[1]): + int(x1 * changed.shape[1])] + assert band.any(), f'panel {i} is identical in both saved frames' + + +@pytest.mark.skipif(not HAS_FFMPEG, reason='ffmpeg not installed') +def test_saving_an_mp4_writes_every_frame(tmp_path): + out = tmp_path / 'grid.mp4' + anim = _grid(save_path=str(out), caption='a caption') + assert out.stat().st_size > 1000 + if not HAS_FFPROBE: + return + probe = subprocess.run( + ['ffprobe', '-v', 'error', '-select_streams', 'v:0', + '-count_frames', '-show_entries', 'stream=nb_read_frames', + '-of', 'csv=p=0', str(out)], + capture_output=True, text=True, check=True) + assert int(probe.stdout.strip().split(',')[0]) == anim.n_frames + + +def test_hyper_animation_save_writes_the_grid(tmp_path): + from PIL import Image + anim = _grid() + out = tmp_path / 'later.gif' + anim.save(out) + with Image.open(out) as im: + assert im.n_frames == anim.n_frames + + +def test_to_jshtml_embeds_every_frame(): + anim = _grid(duration=1, frame_rate=5) + html = anim.to_jshtml() + assert html.count('data:image/png;base64') == anim.n_frames == 5 + + +def test_an_unsupported_extension_is_refused_before_anything_is_fitted( + tmp_path): + with pytest.raises(ValueError, match='unsupported animation save format'): + _grid(save_path=str(tmp_path / 'grid.xyz')) + + +# --- refusals ----------------------------------------------------------- + +def test_the_plotly_backend_is_refused_like_companion(): + with pytest.raises(NotImplementedError, + match="backend='matplotlib'") as err: + _grid(backend='plotly') + assert 'matplotlib-only' in str(err.value) + + +def test_a_static_plotly_grid_still_works(): + fig = hyp.plot(DATA, panels=(1, 4), backend='plotly', show=False) + assert type(fig).__module__.startswith(('plotly', 'hypertools')) + assert len(fig.data) >= 4 + + +def test_companion_is_refused_with_what_to_do_instead(): + with pytest.raises(ValueError, match='companion= cannot be combined'): + _grid(companion={'data': np.arange(40.0)}) + + +def test_explore_is_refused(): + with pytest.raises(ValueError, match='explore'): + _grid(explore=True) + + +def test_panels_of_different_widths_are_refused(): + mixed = [_walk(0, cols=5), _walk(1, cols=2)] + with pytest.raises(ValueError, match='same number of columns'): + hyp.plot(mixed, panels=True, panel_fit='independent', animate=True, + duration=1, frame_rate=8, show=False) + # the static grid draws the narrow panel flat on its cell's floor + fig = hyp.plot(mixed, panels=True, panel_fit='independent', show=False) + assert len(_panel_axes(fig)) == 2 + + +def test_a_caller_supplied_ax_is_refused_with_panels(): + fig, axes = hyp_subplots(1, 1) + with pytest.raises(ValueError, match='ax='): + _grid(ax=axes[0]) + + +def test_the_public_ax_plus_animate_refusal_still_holds(): + fig, axes = hyp_subplots(1, 2) + with pytest.raises(ValueError, match='cannot be combined with animate'): + hyp.plot(DATA[0], ax=axes[0], animate=True, show=False) + # ...and the internal marker is not a public keyword + assert '_panel_animation' not in str( + __import__('inspect').signature(hyp.plot)) + + +def test_axis_labels_that_cannot_fit_an_explicit_size_are_refused(): + with pytest.raises(ValueError, match='larger size=') as err: + _grid(DATA[:3], panels=(1, 3), size=(4, 3), xlabel='first axis', + ylabel='second axis', zlabel='third axis') + assert 'drop the axis labels' in str(err.value) + assert not plt.get_fignums() + + +def test_panels_with_different_frame_counts_are_refused(): + """Every public route gives the panels one schedule, so this drives the + grid builder with two real panels drawn at different frame rates.""" + from hypertools.plot.animation_context import FrameHooks + from hypertools.plot.plot import _animate_panel_grid + fig, axes = hyp_subplots(1, 2) + cells = [] + hyp.plot(DATA[0], ax=axes[0], animate=True, duration=1, frame_rate=8, + show=False, _panel_animation=cells) + hyp.plot(DATA[1], ax=axes[1], animate=True, duration=1, frame_rate=5, + show=False, _panel_animation=cells) + assert [cell['stub']._save_count for cell in cells] == [8, 5] + with pytest.raises(ValueError, match='different numbers of frames'): + _animate_panel_grid( + fig, cells, list(axes), [], (1, 2), grid_hooks=FrameHooks(), + caption=None, dynamic_caption=None, font=None, save_path=None, + show=False, return_model=False, shared_pipeline=None) + + +def test_an_animated_grid_raises_no_warnings(): + with warnings.catch_warnings(): + warnings.simplefilter('error') + anim = _grid(title=['a', 'b', 'c', 'd'], legend=['a', 'b', 'c', 'd'], + caption='quiet') + anim.draw_frame(0) + anim.figure.canvas.draw() + + +def test_a_frame_grid_of_dataframes_keeps_its_index_for_the_caption(): + index = pd.date_range('2024-01-01', periods=40, freq='D') + frames = [pd.DataFrame(d, index=index) for d in DATA[:2]] + anim = _grid(frames, panels=(1, 2), caption='{index:%Y-%m-%d}') + anim.draw_frame(anim.n_frames - 1) + assert anim.figure.texts[-1].get_text() == '2024-02-09' diff --git a/tests/test_changelog_1_1.py b/tests/test_changelog_1_1.py index e563baa1a..5d943d2f5 100644 --- a/tests/test_changelog_1_1.py +++ b/tests/test_changelog_1_1.py @@ -139,7 +139,10 @@ def test_the_documented_duplicate_time_rejection_actually_happens(): def test_added_documents_every_new_capability(): - added = _section(_changelog(), '### Added') + # the 1.1.0 section's own Added subsection: a later release has one + # too (GH #295), and it sits above this one + text = _changelog() + added = _section(_section(text, _heading_1_1_0(text)), '### Added') for phrase in ('column MultiIndex', 'hue', 'hyp.predict', 'trace_data', 'plotly'): assert phrase in added, f'missing {phrase!r}' @@ -183,7 +186,10 @@ def test_the_release_review_subsection_documents_its_user_visible_fixes(): def test_added_names_the_scoring_and_source_kwargs(): """The Added section describes backtests, imputer scoring and the synthetic/web loaders, so it has to name the keywords that drive them.""" - added = _section(_changelog(), '### Added') + # the 1.1.0 section's own Added subsection: a later release has one + # too (GH #295), and it sits above this one + text = _changelog() + added = _section(_section(text, _heading_1_1_0(text)), '### Added') for phrase in ('`metrics=`', '`return_imputed=True`', '`**source_kwargs`'): assert phrase in added, f'missing {phrase!r}' diff --git a/tests/test_plot_caption.py b/tests/test_plot_caption.py new file mode 100644 index 000000000..9549d407a --- /dev/null +++ b/tests/test_plot_caption.py @@ -0,0 +1,463 @@ +"""`caption=`: a figure-level caption, updated every frame (GH #295). + +One line of text centered under the figure -- a single plot or a whole +`panels=` grid -- given as a plain string, a ``'{index...}'`` pattern, or a +callable taking the frame's `FrameContext` (the forms a per-frame `title=` +takes). + +Real figures and real frames, rendered headless: caption text is read back +off the returned figure after `HyperAnimation.draw_frame`, and positions +are measured from a real draw. Nothing is mocked, and no assertion depends +on a font's absolute metrics. +""" +import matplotlib +matplotlib.use('Agg') + +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +import pytest + +import hypertools as hyp +from hypertools.plot.animation_context import FrameContext +from hypertools.plot.plot import CAPTION_GID +from hypertools.plot.plot import subplots as hyp_subplots + + +def _walk(seed, rows=40, cols=5): + rng = np.random.default_rng(seed) + return np.cumsum(rng.normal(size=(rows, cols)), axis=0) + + +DATA = [_walk(seed) for seed in range(4)] +DATES = pd.date_range('2024-01-01', periods=40, freq='D') +FRAMES = [pd.DataFrame(d, index=DATES) for d in DATA] + + +def _counter(ctx): + return f'timepoint {ctx.frame + 1} of {ctx.n_frames}' + + +def _single(data=None, **kwargs): + call = dict(animate=True, duration=1, frame_rate=8, show=False) + call.update(kwargs) + return hyp.plot(DATA[0] if data is None else data, **call) + + +def _grid(data=None, **kwargs): + call = dict(panels=(1, 4), animate=True, duration=1, frame_rate=8, + show=False) + call.update(kwargs) + return hyp.plot(DATA if data is None else data, **call) + + +def _caption(fig): + """The figure's caption Text, found the documented way (by gid).""" + found = fig.findobj(lambda a: a.get_gid() == CAPTION_GID) + assert len(found) == 1, f'{len(found)} captions on the figure' + return found[0] + + +def _text_at(anim, frame): + anim.draw_frame(frame) + return _caption(anim.figure).get_text() + + +@pytest.fixture(autouse=True) +def _close_figures(): + yield + plt.close('all') + + +#: the three places an animated caption is drawn +_MAKERS = { + 'single-3d': lambda **kw: _single(**kw), + 'single-2d': lambda **kw: _single(ndims=2, **kw), + 'grid': lambda **kw: _grid(**kw), +} + + +# --- text per frame ----------------------------------------------------- + +@pytest.mark.parametrize('where', sorted(_MAKERS)) +def test_a_plain_string_is_drawn_on_every_frame(where): + anim = _MAKERS[where](caption='a fixed caption') + assert [_text_at(anim, f) for f in (0, 3, anim.n_frames - 1)] == ( + ['a fixed caption'] * 3) + + +@pytest.mark.parametrize('where', sorted(_MAKERS)) +def test_a_callable_is_resolved_for_every_frame(where): + anim = _MAKERS[where](caption=_counter) + assert _text_at(anim, 0) == 'timepoint 1 of 8' + assert _text_at(anim, 4) == 'timepoint 5 of 8' + assert _text_at(anim, 7) == 'timepoint 8 of 8' + # frames are order-independent: going back redraws the earlier text + assert _text_at(anim, 2) == 'timepoint 3 of 8' + + +def test_a_still_of_a_fresh_animation_already_shows_frame_zero(): + anim = _single(caption=_counter) + assert _caption(anim.figure).get_text() == 'timepoint 1 of 8' + anim = _grid(caption=_counter) + assert _caption(anim.figure).get_text() == 'timepoint 1 of 8' + + +@pytest.mark.parametrize('maker, data', [ + (_single, FRAMES[0]), + (_grid, FRAMES), +], ids=['single', 'grid']) +def test_an_index_pattern_reads_the_row_under_the_reveal_head(maker, data): + anim = maker(data, caption='{index:%Y-%m-%d}') + assert _text_at(anim, 0) == '2024-01-01' + assert _text_at(anim, anim.n_frames - 1) == '2024-02-09' + middle = pd.Timestamp(_text_at(anim, anim.n_frames // 2)) + assert DATES[0] < middle < DATES[-1] + + +def test_a_pattern_caption_matches_the_same_pattern_title(): + anim = _single(FRAMES[0], ndims=2, title='{index:%d %b}', + caption='{index:%d %b}') + for frame in range(anim.n_frames): + anim.draw_frame(frame) + assert (_caption(anim.figure).get_text() + == anim.figure.axes[0].get_title()) + + +def test_a_grid_callable_gets_the_figure_level_context(): + seen = [] + + def caption(ctx): + seen.append(ctx) + return f'{len(ctx.panels)} panels, frame {ctx.frame}' + + anim = _grid(caption=caption) + assert _text_at(anim, 5) == '4 panels, frame 5' + ctx = seen[-1] + assert isinstance(ctx, FrameContext) + assert isinstance(ctx.axes, tuple) and len(ctx.axes) == 4 + assert ctx.figure is anim.figure + + +def test_a_single_axes_callable_gets_the_ordinary_context(): + seen = [] + + def caption(ctx): + seen.append(ctx) + return f'{ctx.progress:.2f}' + + anim = _single(caption=caption) + assert _text_at(anim, anim.n_frames - 1) == '1.00' + assert seen[-1].axes is anim.figure.axes[0] + assert seen[-1].revealed_counts is not None + assert seen[-1].panels == () + + +def test_the_caption_is_updated_before_on_frame_runs(): + """A user callback sees the CURRENT frame's caption, as it sees the + current frame's artists.""" + seen = [] + anim = _single(caption=_counter) + anim.on_frame(lambda ctx: seen.append( + _caption(ctx.figure).get_text())) + anim.draw_frame(6) + assert seen == ['timepoint 7 of 8'] + + +# --- placement ---------------------------------------------------------- + +def _boxes(fig): + """(caption box, [box of everything else drawn]) after a real draw.""" + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + caption = _caption(fig).get_window_extent(renderer) + others = [] + for ax in fig.axes: + if not ax.get_visible(): + continue + others.append(ax.get_window_extent(renderer)) + if ax.get_title(): + others.append(ax.title.get_window_extent(renderer)) + if ax.get_legend() is not None: + others.append(ax.get_legend().get_window_extent(renderer)) + return caption, others + + +_PLACEMENTS = { + 'single-3d': lambda: _single(caption=_counter, title='a title', + legend=['a']), + 'single-2d': lambda: _single(ndims=2, caption=_counter, title='a title', + legend=['a']), + 'single-colorbar': lambda: _single( + caption=_counter, hue=np.arange(40.0), colorbar=True), + 'single-companion': lambda: _single( + caption=_counter, companion={'data': np.arange(40.0)}), + 'grid-row': lambda: _grid(caption=_counter, title=list('abcd'), + legend=list('abcd')), + 'grid-2x2': lambda: _grid(panels=(2, 2), caption=_counter, + title=list('abcd')), + 'grid-2d': lambda: _grid(ndims=2, panels=(2, 2), caption=_counter, + title=list('abcd')), + 'grid-colorbar': lambda: _grid( + DATA[:3], panels=(1, 3), caption=_counter, colorbar=True, + hue=[np.arange(40.0)] * 3), + 'grid-sized': lambda: _grid(caption=_counter, size=(11, 3)), + 'grid-two-lines': lambda: _grid(caption='first line\nsecond line', + title=list('abcd')), + 'static': lambda: hyp.plot(DATA[0], caption='static', legend=['a'], + title='t', show=False), + 'static-grid': lambda: hyp.plot(DATA, panels=(2, 2), caption='static', + legend=list('abcd'), show=False), +} + + +@pytest.mark.parametrize('case', sorted(_PLACEMENTS)) +def test_the_caption_is_inside_the_canvas_and_clear_of_everything(case): + made = _PLACEMENTS[case]() + fig = made.figure if hasattr(made, 'draw_frame') else made + frames = ([0, made.n_frames // 2, made.n_frames - 1] + if hasattr(made, 'draw_frame') else [None]) + for frame in frames: + if frame is not None: + made.draw_frame(frame) + caption, others = _boxes(fig) + canvas = fig.bbox + assert caption.width > 0 and caption.height > 0 + assert caption.x0 >= canvas.x0 and caption.x1 <= canvas.x1, case + assert caption.y0 >= canvas.y0 and caption.y1 <= canvas.y1, case + for other in others: + assert not caption.overlaps(other), (case, frame) + # under everything, not merely beside it + assert caption.y1 <= other.y0 + 0.5, (case, frame) + # centered on the canvas + middle = 0.5 * (caption.x0 + caption.x1) + assert middle == pytest.approx(0.5 * canvas.width, abs=1.0) + + +def test_the_caption_stays_clear_of_a_rotating_cube_on_every_frame(): + import itertools + from mpl_toolkits.mplot3d import proj3d + anim = _grid(caption=_counter, duration=3, frame_rate=10, elev=40) + fig = anim.figure + axes = [ax for ax in fig.axes if ax.get_visible()] + for frame in range(anim.n_frames): + anim.draw_frame(frame) + fig.canvas.draw() + top = _caption(fig).get_window_extent(fig.canvas.get_renderer()).y1 + for ax in axes: + corners = np.array(list(itertools.product( + ax.get_xlim3d(), ax.get_ylim3d(), ax.get_zlim3d()))) + x, y, _ = proj3d.proj_transform( + corners[:, 0], corners[:, 1], corners[:, 2], ax.get_proj()) + lowest = ax.transData.transform(np.column_stack([x, y]))[:, 1] + assert lowest.min() >= top, frame + + +def test_a_full_canvas_plot_grows_downward_and_the_plot_keeps_its_size(): + """An animated 3-D plot fills its canvas, so the caption's room is + ADDED below it: the axes keeps its size in inches and its place + relative to the top.""" + plain = _single() + captioned = _single(caption='under the plot') + w0, h0 = plain.figure.get_size_inches() + w1, h1 = captioned.figure.get_size_inches() + assert w1 == pytest.approx(w0) + assert h1 > h0 + box0 = plain.figure.axes[0].get_position() + box1 = captioned.figure.axes[0].get_position() + assert box1.width * w1 == pytest.approx(box0.width * w0) + assert box1.height * h1 == pytest.approx(box0.height * h0) + # same distance from the top edge + assert (1 - box1.y1) * h1 == pytest.approx((1 - box0.y1) * h0) + + +def test_a_plot_with_blank_room_below_is_not_resized(): + """Where the figure already has blank room under the plot (a 2-D + animation's margin), the caption goes there and nothing moves.""" + plain = _single(ndims=2) + captioned = _single(ndims=2, caption='fits in the margin') + assert tuple(captioned.figure.get_size_inches()) == pytest.approx( + tuple(plain.figure.get_size_inches())) + assert (captioned.figure.axes[0].get_position().bounds + == pytest.approx(plain.figure.axes[0].get_position().bounds)) + + +def test_more_lines_get_more_room(): + one = _single(caption='one line') + three = _single(caption='one\ntwo\nthree') + assert (three.figure.get_size_inches()[1] + > one.figure.get_size_inches()[1]) + caption, _ = _boxes(three.figure) + assert caption.y0 >= 0 + + +def test_no_caption_leaves_the_figure_exactly_as_it_was(): + anim = _single() + assert not anim.figure.findobj(lambda a: a.get_gid() == CAPTION_GID) + assert tuple(anim.figure.get_size_inches()) == pytest.approx((6.4, 4.8)) + fig = hyp.plot(DATA, panels=(2, 2), show=False) + assert not fig.texts + + +def test_the_caption_uses_the_plots_font(): + anim = _single(caption='styled', title='a title') + caption = _caption(anim.figure) + title = anim.figure.axes[0].title + assert caption.get_fontname() == title.get_fontname() + # ...and can be restyled through the documented handle + caption.set_color('gray') + anim.draw_frame(3) + assert _caption(anim.figure).get_color() == 'gray' + + +# --- static plots ------------------------------------------------------- + +def test_a_static_plot_draws_its_caption_once(): + fig = hyp.plot(DATA[0], caption='a static caption', show=False) + assert _caption(fig).get_text() == 'a static caption' + + +def test_a_static_pattern_shows_the_last_row(): + fig = hyp.plot(FRAMES[0], caption='{index:%Y-%m-%d}', show=False) + assert _caption(fig).get_text() == '2024-02-09' + + +def test_a_static_callable_gets_the_finished_figures_context(): + seen = [] + + def caption(ctx): + seen.append(ctx) + return 'done' + + fig = hyp.plot(DATA[0], caption=caption, show=False) + assert _caption(fig).get_text() == 'done' + assert len(seen) == 1 + assert seen[0].frame is None and seen[0].n_frames is None + assert seen[0].progress == 1.0 + assert seen[0].revealed_counts == (len(seen[0].datasets[0]),) + + +def test_a_static_grid_draws_its_caption_under_every_panel(): + fig = hyp.plot(FRAMES, panels=(1, 4), caption='{index:%Y-%m-%d}', + show=False) + assert _caption(fig).get_text() == '2024-02-09' + caption, others = _boxes(fig) + assert all(caption.y1 <= other.y0 + 0.5 for other in others) + + +def test_a_static_caption_is_saved_with_the_figure(tmp_path): + """A static 2-D plot fills its canvas down to the tick labels, so the + caption's room is added below: the saved image is as wide, taller, and + the caption's own box holds ink.""" + from PIL import Image + plain, captioned = tmp_path / 'plain.png', tmp_path / 'captioned.png' + hyp.plot(DATA[0], ndims=2, save_path=str(plain), show=False) + fig = hyp.plot(DATA[0], ndims=2, save_path=str(captioned), show=False, + caption='saved with the figure') + with Image.open(plain) as a, Image.open(captioned) as b: + assert a.size[0] == b.size[0] + assert b.size[1] > a.size[1] + image = np.asarray(b.convert('L')).astype(int) + assert image.shape == tuple( + int(v) for v in (fig.bbox.height, fig.bbox.width)) + fig.canvas.draw() + box = _caption(fig).get_window_extent(fig.canvas.get_renderer()) + height = image.shape[0] + rows = slice(int(height - box.y1), int(height - box.y0) + 1) + cols = slice(int(box.x0), int(box.x1) + 1) + background = image[-1, 0] + # the caption's box holds ink, in the bottom fifth of the image + assert (np.abs(image[rows, cols] - background) > 80).any() + assert rows.start > 0.8 * height + + +# --- construction does not start the animation ---------------------------- + +@pytest.mark.parametrize('where', sorted(_MAKERS)) +def test_adding_a_caption_does_not_fire_on_frame(where): + """Placing the caption measures the figure on a real draw; that draw + must not run a frame through the user's callback.""" + seen = [] + anim = _MAKERS[where](caption=_counter, on_frame=seen.append, + legend=True) + assert seen == [] + anim.draw_frame(2) + assert [ctx.frame for ctx in seen] == [2] + + +def test_a_saved_animation_carries_the_changing_caption(tmp_path): + from PIL import Image + out = tmp_path / 'captioned.gif' + anim = _single(ndims=2, caption=_counter, save_path=str(out), + duration=1, frame_rate=6) + with Image.open(out) as im: + assert im.n_frames == anim.n_frames == 6 + frames = [] + for k in (0, 5): + im.seek(k) + frames.append(np.asarray(im.convert('L')).astype(int)) + fig = anim.figure + fig.canvas.draw() + box = _caption(fig).get_window_extent(fig.canvas.get_renderer()) + height = frames[0].shape[0] + rows = slice(int(height - box.y1) - 2, int(height - box.y0) + 2) + cols = slice(int(box.x0) - 2, int(box.x1) + 2) + # the caption's own pixels differ between the first and last frame + assert (np.abs(frames[0][rows, cols] - frames[1][rows, cols]) > 40).any() + + +# --- refusals ----------------------------------------------------------- + +@pytest.mark.parametrize('value', [5, 3.5, ['a', 'b'], ('a',), {'a': 1}]) +def test_a_caption_of_the_wrong_type_is_refused(value): + with pytest.raises(TypeError, match='caption= must be a string'): + _single(caption=value) + with pytest.raises(TypeError, match='caption= must be a string'): + _grid(caption=value) + + +def test_a_pattern_without_an_index_is_refused_before_the_pipeline_runs(): + with pytest.raises(ValueError, match="caption='{index}' is a per-frame"): + _single(caption='{index}') + with pytest.raises(ValueError, match="caption='{index}' is a per-frame"): + _grid(caption='{index}') + + +def test_a_pattern_the_index_cannot_format_names_the_caption(): + with pytest.raises(ValueError, match='caption=.*could not be formatted'): + _single(FRAMES[0], caption='{index:%q%!}{other}') + + +@pytest.mark.parametrize('maker', [_single, _grid], ids=['single', 'grid']) +def test_a_callable_must_return_a_string(maker): + before = set(plt.get_fignums()) + with pytest.raises(TypeError, match='caption= callable must return a str'): + maker(caption=lambda ctx: 3) + # the abandoned figure is not left registered with pyplot + assert set(plt.get_fignums()) == before + + +@pytest.mark.parametrize('extra', [ + dict(animate=True, duration=1, frame_rate=8), + dict(), + dict(panels=(1, 4)), +], ids=['animated', 'static', 'static-grid']) +def test_the_plotly_backend_is_refused_like_companion(extra): + data = DATA if 'panels' in extra else DATA[0] + with pytest.raises(NotImplementedError, + match="backend='matplotlib'") as err: + hyp.plot(data, caption='c', backend='plotly', show=False, **extra) + assert 'caption= is matplotlib-only' in str(err.value) + + +def test_a_caller_supplied_ax_is_refused(): + fig, axes = hyp_subplots(1, 2) + with pytest.raises(ValueError, match='caption= is drawn under the whole'): + hyp.plot(DATA[0], ax=axes[0], caption='c', show=False) + assert not fig.texts + + +def test_caption_is_a_named_parameter_defaulting_to_none(): + import inspect + parameter = inspect.signature(hyp.plot).parameters['caption'] + assert parameter.default is None diff --git a/tests/test_plot_panels.py b/tests/test_plot_panels.py index d85d30848..11a5a5010 100644 --- a/tests/test_plot_panels.py +++ b/tests/test_plot_panels.py @@ -261,9 +261,30 @@ def test_empty_reduce_list_raises(): # --- refusals ----------------------------------------------------------- -def test_panels_with_animate_raises(): - with pytest.raises(ValueError, match='animate'): - hyp.plot(_datasets(3), panels=True, animate=True, show=False) +def test_panels_with_animate_is_one_animation_of_the_whole_grid(): + """GH #295: `panels=` with `animate=` used to raise ("draws several + STATIC panels"); it now returns ONE animation whose every frame draws + every panel (tests/test_animated_panels.py covers it in depth).""" + from hypertools.plot.hyper_animation import HyperAnimation + anim = hyp.plot(_datasets(3), panels=True, animate=True, duration=1, + frame_rate=6, show=False) + try: + assert isinstance(anim, HyperAnimation) + assert anim.n_frames == 6 + panels = [ax for ax in anim.figure.axes if ax.get_visible()] + assert len(panels) == 3 + + def drawn(ax): + return [np.column_stack(line.get_data_3d()) for line in ax.lines] + + anim.draw_frame(1) + early = [drawn(ax) for ax in panels] + anim.draw_frame(5) + late = [drawn(ax) for ax in panels] + for a, b in zip(early, late): + assert a[0].shape != b[0].shape or not np.allclose(a[0], b[0]) + finally: + matplotlib.pyplot.close(anim.figure) def test_panels_with_ax_raises(): diff --git a/tests/test_plot_panels_audit.py b/tests/test_plot_panels_audit.py index 534c0b718..40c81a5bb 100644 --- a/tests/test_plot_panels_audit.py +++ b/tests/test_plot_panels_audit.py @@ -507,13 +507,15 @@ def test_repeated_forecast_colours_match_the_single_axes_figure(backend, fit, #: added to a roster in plot.py or, with a reason, here. _NOT_SLICED = { 'x': 'the datasets themselves', - 'animate': 'rejected under panels= (an animation owns its figure)', + 'animate': 'one mode for the whole grid, played in every panel (GH ' + '#295); a per-dataset morph list is passed whole, so a panel ' + 'that does not hold that many datasets refuses it', 'resample': 'its per-dataset arrays are its OUTPUT, not an argument', 'ax': 'rejected under panels=; mentions per-dataset layouts only', 'title_color': 'per SEGMENT of a serial/morph title, not per dataset', 'forecast_cluster': 'groups each panel\'s own forecast endpoints', 'forecast_n_clusters': 'a count for forecast_cluster=, not a list', - 'forecast_trail': 'animation only; panels= is static', + 'forecast_trail': 'one value for every animated panel', 'return_model': 'describes the bundle, takes no per-dataset value', 'colorbar': 'drawn per panel', 'label_anchor': 'positions a per-dataset labels= entry; one value', @@ -525,13 +527,14 @@ def test_repeated_forecast_colours_match_the_single_axes_figure(backend, fit, 'hue_mode': 'describes the hue matrix, one value', 'color_reduce': 'reduces a hue matrix, one spec', 't': 'one horizon for every forecast', - 'dataset_fade': 'animation only; panels= is static', - 'companion': 'animation only; panels= is static', + 'dataset_fade': 'one (floor, decay) for every animated panel', + 'companion': 'refused with an animated panels= grid; a static ' + 'grid refuses it as every static plot does', 'frame_kwargs': 'one frame style for every panel', 'save_path': 'one file for the whole grid', 'size': 'one figure size for the whole grid', - 'loop': 'animation only; panels= is static', - 'on_frame': 'animation only; panels= is static', + 'loop': 'one value for every animated (morph) panel', + 'on_frame': 'called once per frame for the whole animated grid', 'transform': 'replaces the pipeline for the panel probe, whose rows ' 'each panel then receives through its own transform=', 'panels': 'the grid itself (its description names the sliced arguments)', @@ -647,20 +650,54 @@ def _style(bundle, i, backend, panel=True): _PER_DATASET_TESTED_ELSEWHERE = { 'truth': 'test_truth_list_reaches_only_its_own_panel', + # the three trails are animation-only: an ANIMATED grid shows them + # (GH #295; `panels=` used to reject `animate=`) + 'chemtrails': 'test_trail_list_reaches_only_its_own_animated_panel', + 'precog': 'test_trail_list_reaches_only_its_own_animated_panel', + 'bullettime': 'test_trail_list_reaches_only_its_own_animated_panel', } -#: roster entries a STATIC grid cannot show: the three trails are -#: animation-only (`panels=` rejects `animate=`), and `density=` has no -#: per-dataset list form -- `plot()` rejects a list on the single-axes -#: path and on every panel alike. +#: roster entries no grid can show: `density=` has no per-dataset list +#: form -- `plot()` rejects a list on the single-axes path and on every +#: panel alike. _PER_DATASET_STATIC_INVISIBLE = { - 'chemtrails': 'animation only', - 'precog': 'animation only', - 'bullettime': 'animation only', 'density': 'no per-dataset list form (plot() rejects a list)', } +@pytest.mark.parametrize('fit', FITS) +@pytest.mark.parametrize('key', ['chemtrails', 'precog', 'bullettime']) +def test_trail_list_reaches_only_its_own_animated_panel(fit, key): + """A per-dataset trail list is narrowed to each panel of an ANIMATED + grid (GH #295): the panel whose dataset asked for a trail draws a head + and a trail, the other draws its head alone -- as the two datasets do + on the single animated axes.""" + data = walks() + kwargs = {key: [True, False]} + single = quiet_plot(data, animate=True, duration=1, frame_rate=6, + **kwargs) + grid = quiet_plot(data, panels=True, panel_fit=fit, animate=True, + duration=1, frame_rate=6, **kwargs) + try: + # single axes: two heads, and ONE trail (the first dataset's) + assert len(single['fig'].axes[0].lines) == 3 + assert [len(ax.lines) for ax in grid['axes']] == [2, 1] + trail = grid['axes'][0].lines[1] + head = grid['axes'][0].lines[0] + assert trail.get_alpha() == pytest.approx(0.3 * (head.get_alpha() + or 1.0)) + # ...and the grid's own frames draw the trail the single-axes + # animation draws on the same frame + single_trail = single['fig'].axes[0].lines[2] + for frame in (0, 3, 5): + grid['animation']._func(frame) + single['animation']._func(frame, *single['animation']._args) + assert (len(np.asarray(trail.get_data_3d()[0])) + == len(np.asarray(single_trail.get_data_3d()[0]))) + finally: + close_all() + + def test_every_per_dataset_roster_entry_has_a_partitioning_test(): covered = (set(_PER_DATASET_CASES) | set(_PER_DATASET_TESTED_ELSEWHERE) | set(_PER_DATASET_STATIC_INVISIBLE)) From 66314d249211161ddc415f000507e34caf4cc3f1 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 05:01:47 -0500 Subject: [PATCH 11/58] docs: animated panel grids and caption= (GH #295) Animation guide sections, a gallery example, the FrameContext.panels attribute, the changelog entries and a session note. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- CHANGELOG.md | 39 +++++++++++ docs/animation.rst | 68 +++++++++++++++++++ docs/conf.py | 2 +- docs/hypertools.FrameContext.rst | 1 + docs/tutorials/plot.ipynb | 2 +- examples/animate_panels.py | 35 ++++++++++ ...sion_2026-11-22_feat295-animated-panels.md | 53 +++++++++++++++ 7 files changed, 198 insertions(+), 2 deletions(-) create mode 100644 examples/animate_panels.py create mode 100644 notes/session_2026-11-22_feat295-animated-panels.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 380106e68..b20552102 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,47 @@ A patch release: three fixes for noise and side effects met when `hyp.plot` draws into a figure the caller built, found by executing notebooks with `jupyter nbconvert` under matplotlib 3.11. No API changes. +### Added + +- **Animated panel grids: `animate=` with `panels=` (GH #295).** + `hyp.plot([a, b, c, d], panels=(1, 4), animate=True, save_path='grid.mp4')` + now gives ONE animation of the whole grid (matplotlib): every panel runs + on the same clock, each panel is animated exactly as the single-axes call + for its data is (every `animate=` style and `order=` value, trails, + `tail_duration=`, `rotations=`, `predict=`, per-panel titles, legends and + colorbars, `panel_fit=`, a list-valued `reduce=`), and one + `HyperAnimation` is returned for the figure. The combination used to + raise `ValueError`. Styles and orderings play per panel, not as a + sequence across panels. Each 3-D panel's cube is zoomed out as far as it + takes to stay inside its own cell through the whole rotation, and with + axis labels the figure is enlarged so the rotating labels fit. + `on_frame=` is called once per frame for the whole figure, with a + `FrameContext` whose `axes` is a tuple of the panel axes and whose new + `panels` field holds one per-panel context each. `return_model=True` + returns the panel bundle with `'animation'` added. Refused with an error + that says what to do instead: `backend='plotly'` + (`NotImplementedError`; static plotly grids are unchanged), `companion=`, + panels whose analyzed data differ in width, and panels that would draw + different numbers of frames. `ax=` with `animate=` is still refused. + New gallery example: `examples/animate_panels.py`. +- **`caption=`: a figure-level caption, updated every frame (GH #295).** + One line of text centered under the figure -- a single plot or a whole + `panels=` grid -- given as a plain string, a `'{index...}'` pattern or a + callable taking the frame's `FrameContext` (the forms a per-frame + `title=` takes), for example + `caption=lambda ctx: f'timepoint {ctx.frame + 1} of {ctx.n_frames}'`. It + sits just below the lowest thing drawn, and the figure is made taller + where there is no blank room for it, so it never overlaps a panel, a + legend or a colorbar and never leaves the canvas. On a static plot it is + drawn once. Matplotlib only: `backend='plotly'` raises + `NotImplementedError`, and a caller-supplied `ax=` raises `ValueError`. + ### Fixed +- **`labels=` in a panel grid stay with their own panel.** The annotations' + bookkeeping was one module-level list holding only the most recently + drawn plot's labels, so in a grid only the last panel's labels were + repositioned or hidden on a mouse press; each axes now keeps its own. - **The backend warning is issued once, and only when it applies (GH #290).** When hypertools cannot set up an interactive matplotlib backend at import (for example in a notebook kernel without `ipympl`), it keeps a warning to diff --git a/docs/animation.rst b/docs/animation.rst index a1d89e4e8..16401be1a 100644 --- a/docs/animation.rst +++ b/docs/animation.rst @@ -702,6 +702,74 @@ What ``animate='morph'`` does *clouds*, so there is no time axis to forecast along -- this is a statement about what a morph means, not a gap to be filled later. +Animated panel grids +-------------------- + +``panels=`` (alias ``subplots=``) draws one panel per dataset, and with +``animate=`` the whole grid is ONE animation (matplotlib only): every panel +runs on the same clock, and a single ``HyperAnimation`` is returned for the +figure, so one ``save_path=`` writes one video of all the panels: + +.. code-block:: python + + anim = hyp.plot([a, b, c, d], '-', panels=(1, 4), animate=True, + duration=10, tail_duration=2, rotations=1, + title=['A', 'B', 'C', 'D'], save_path='grid.mp4') + +Each panel is animated exactly as the single-axes call for its data is: +every ``animate=`` style and ``order=`` value, the trail flags, ``predict=``, +per-frame titles, legends and colorbars apply per panel. The ordering is per +panel too, not a sequence across panels: ``order='serial'`` reveals the +datasets *within* each panel one after another, and the panels never take +turns. ``panel_fit=`` and a list-valued ``reduce=`` (one panel per reducer) +work as they do for a static grid. + +A few things are specific to a grid: + +* Every panel must draw the same number of frames, or the call raises + ``ValueError`` (``animate='morph'`` needs the same number of datasets in + each panel). +* Each 3-D panel's cube is zoomed out as far as it takes to stay inside its + own cell through the whole rotation, so ``zoom=`` can shrink a panel's + cube but not enlarge it past its cell. With ``xlabel=``/``ylabel=``/ + ``zlabel=`` the figure is enlarged so the rotating axis labels fit too; + an explicit ``size=`` too small for them raises, naming a size that fits. +* ``on_frame=`` is called once per frame for the whole figure. Its + ``FrameContext`` has ``axes`` as a tuple of the panel axes, ``artists`` + and ``datasets`` as every panel's in panel order, and ``panels`` as one + ordinary per-panel ``FrameContext`` each (that panel's own axes, artists, + ``revealed_counts`` and so on). +* ``backend='plotly'`` raises ``NotImplementedError`` (a static plotly grid + works), ``companion=`` raises ``ValueError``, and so do panels whose + analyzed data differ in width. + +Captions +-------- + +``caption=`` (matplotlib only) draws one line of text centered under the +figure -- under a single plot, or under a whole ``panels=`` grid -- and +updates it on every frame. It takes the forms a per-frame ``title=`` takes: +a plain string, a ``'{index...}'`` pattern formatted with the input's own row +index under the reveal head, or a callable given the frame's +``FrameContext``: + +.. code-block:: python + + hyp.plot([a, b, c, d], '-', panels=(1, 4), animate=True, + caption=lambda ctx: f'timepoint {ctx.frame + 1} of {ctx.n_frames}') + + hyp.plot(df, '-', animate=True, caption='{index:%B %Y}') + +The caption sits a small gap below the lowest thing drawn; where the figure +has no blank room there (an animated 3-D plot fills its canvas) the figure +is made taller by the caption's height, so the caption never overlaps a +panel, a legend or a colorbar and never leaves the canvas. Room is made for +as many lines as the first frame's caption has. On a static plot the caption +is drawn once, a pattern or callable being resolved for the finished figure. +``caption=`` raises ``NotImplementedError`` under ``backend='plotly'`` (a +per-frame ``title=`` works on both backends) and ``ValueError`` with a +caller-supplied ``ax=``. + Companion panels ----------------- diff --git a/docs/conf.py b/docs/conf.py index 682cddc77..b5c817291 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -438,7 +438,7 @@ def _quiet_gallery_only_warnings(gallery_conf, fname): 'plot_text', 'plot_corpus', 'plot_sotus', 'plot_gensim_text', # animation basics 'animate', 'animate_spin', 'animate_trails', 'animate_trails_mix', - 'save_movie', 'animate_plotly', + 'animate_panels', 'save_movie', 'animate_plotly', # animated showcases 'plot_story_trajectories', 'animate_morph_zoo', 'animate_surface_morph', 'animate_conversation', 'animate_painting_embeddings', diff --git a/docs/hypertools.FrameContext.rst b/docs/hypertools.FrameContext.rst index 65d2c34c7..3046bb705 100644 --- a/docs/hypertools.FrameContext.rst +++ b/docs/hypertools.FrameContext.rst @@ -28,6 +28,7 @@ ~FrameContext.current_index ~FrameContext.datasets ~FrameContext.order + ~FrameContext.panels ~FrameContext.progress ~FrameContext.revealed_counts ~FrameContext.segment_index diff --git a/docs/tutorials/plot.ipynb b/docs/tutorials/plot.ipynb index 8969be47a..aa4971297 100644 --- a/docs/tutorials/plot.ipynb +++ b/docs/tutorials/plot.ipynb @@ -1552,7 +1552,7 @@ "output_type": "stream", "text": [ "HypertoolsIOError: could not load 'no_such_file.csv'. Tried, in order:\n", - "ValueError: ax= cannot be combined with animate=: an animated plot owns its own figure, so the axes you passed would be left empty and the animation drawn somewhere else. Drop ax= and use the returned animation's .figure (or .figure.axes[0]) to style what was drawn; for several panels in one animation, lay the panels out in the data and make a single plot call.\n" + "ValueError: ax= cannot be combined with animate=: an animated plot owns its own figure, so the axes you passed would be left empty and the animation drawn somewhere else. Drop ax= and use the returned animation's .figure (or .figure.axes[0]) to style what was drawn; for several panels in one animation, pass panels= (one animated panel per dataset, on one clock).\n" ] } ], diff --git a/examples/animate_panels.py b/examples/animate_panels.py new file mode 100644 index 000000000..7098e9c2a --- /dev/null +++ b/examples/animate_panels.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +""" +===================================== +Animating a grid of panels together +===================================== + +``panels=`` draws each dataset in a panel of its own, and with ``animate=`` +the whole grid becomes one animation: every panel runs on the same clock, and +one object is returned (and saved) for the figure. ``caption=`` adds a line of +text under the grid that is updated on every frame -- here a running +timepoint counter. The data are three participants' brain-activity +trajectories (``hyp.load('weights_sample')``), 300 timepoints each, reduced +together so the panels share one set of axes. +""" + +# Code source: Contextual Dynamics Laboratory +# License: MIT + +import hypertools as hyp + +# load example data: a list of three (300 timepoints x 100 features) arrays +data = hyp.load('weights_sample') + + +# the caption is rebuilt for every frame from that frame's context; at 30 +# frames per second, a 10-second clip draws one frame per timepoint +def timepoint(ctx): + return f'timepoint {ctx.frame + 1} of {ctx.n_frames}' + + +# backend='matplotlib': an animated panel grid is a matplotlib animation +# (on Colab the default backend would be plotly) +fig, ani = hyp.plot(data, panels=(1, 3), animate=True, duration=10, + title=['Participant 1', 'Participant 2', 'Participant 3'], + caption=timepoint, size=(10, 3.6), backend='matplotlib') diff --git a/notes/session_2026-11-22_feat295-animated-panels.md b/notes/session_2026-11-22_feat295-animated-panels.md new file mode 100644 index 000000000..aca69a355 --- /dev/null +++ b/notes/session_2026-11-22_feat295-animated-panels.md @@ -0,0 +1,53 @@ +# Session 2026-11-22: GH #295, animated panel grids and `caption=` + +Branch `feat/295-animated-panels` (not pushed, no version bump, no tag). + +## What was built + +- `animate=` with `panels=`/`subplots=` returns ONE `HyperAnimation` of the + whole grid. `_plot_panels` still re-enters `plot()` once per panel; in + "panel cell" mode (`_panel_animation=` private kwarg, `_draw(panel_cell=True)`) + the matplotlib backend draws into the given axes and returns a + `PanelAnimationStub` (frame function + frame count) in place of a + `FuncAnimation`. `_animate_panel_grid` then drives every stub from one + `HyperFuncAnimation`. +- `caption=` (matplotlib): string, `'{index}'` pattern, or callable taking a + `FrameContext`. Drawn by `_add_caption` as a `fig.text` with gid + `hypertools-caption`, placed just under the lowest drawn content; the + figure grows downward only when there is not enough blank room. +- `FrameContext.panels`: one context per panel for a grid; the grid context's + `axes` is a tuple. +- `labels=` bookkeeping is now per axes (`ax._hyp_labels_and_points`), so + labels follow the reveal in every panel. + +## Layout notes + +- A rotating 3-D cube overflows its (square) viewport at some azimuths; + `_fit_rotating_cubes` lowers a per-cell zoom scale until the projected + cube stays inside at every azimuth. With axis labels the figure is + enlarged (or, with an explicit `size=`, a ValueError says to pass a larger + one or drop the labels). +- In cell mode `fig.tight_layout()` must run per panel as it does for a + static panel, and animated artists are excluded from layout. + +## Refused combinations + +plotly backend (NotImplementedError naming `backend='matplotlib'`), +`companion=`, `explore=`, `ax=`, panels of different widths +(`panel_fit='independent'`), axis labels that cannot fit an explicit `size=`, +`caption=` on plotly / with `ax=` / wrong type / `{index}` without an index. +The public `ax=` + `animate=` refusal is unchanged. + +## Known, not changed + +- A STATIC 3-D grid with axis labels clips the labels at the right edge of + the last panel (seen while comparing; static output was kept + pixel-identical here). Needs its own fix. + +## Tests + +`tests/test_animated_panels.py`, `tests/test_plot_caption.py`; the three +old-refusal tests in `tests/test_plot_panels.py` and +`tests/test_plot_panels_audit.py` now assert the new behavior. The full +suite was not run (about 25 minutes); the panel, animation, hook, title, +docs and example test files were. From cf530eb1bed20114f44cd35e323be989d1258d07 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 05:06:31 -0500 Subject: [PATCH 12/58] feat: an animated panel grid's default figure is sized by the grid (GH #295) Without size=, one 3.2 in square cell per panel (at least 6.4 in wide) instead of matplotlib's 6.4 x 4.8 in, so a saved clip of a row of panels is not mostly blank canvas. A static grid's default size is unchanged. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- CHANGELOG.md | 4 ++++ docs/animation.rst | 4 ++++ examples/animate_panels.py | 2 +- hypertools/plot/plot.py | 22 ++++++++++++++++++++-- tests/test_animated_panels.py | 35 +++++++++++++++++++++++++++++++++++ 5 files changed, 64 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b20552102..467aefb02 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,10 @@ draws into a figure the caller built, found by executing notebooks with sequence across panels. Each 3-D panel's cube is zoomed out as far as it takes to stay inside its own cell through the whole rotation, and with axis labels the figure is enlarged so the rotating labels fit. + Without `size=`, the figure is sized by the grid (3.2 in per panel each + way, at least 6.4 in wide) instead of matplotlib's fixed 6.4 x 4.8 in, so a + saved clip of a row of panels is not mostly blank canvas; a static grid's + default size is unchanged. `on_frame=` is called once per frame for the whole figure, with a `FrameContext` whose `axes` is a tuple of the panel axes and whose new `panels` field holds one per-panel context each. `return_model=True` diff --git a/docs/animation.rst b/docs/animation.rst index 16401be1a..eb8232711 100644 --- a/docs/animation.rst +++ b/docs/animation.rst @@ -726,6 +726,10 @@ work as they do for a static grid. A few things are specific to a grid: +* Without ``size=`` the figure is sized by the grid -- 3.2 in per panel each + way, and at least 6.4 in wide -- so a saved clip of a row of panels is not + mostly blank canvas. (A static grid keeps matplotlib's 6.4 x 4.8 in + default.) ``size=`` sets the whole figure's size as usual. * Every panel must draw the same number of frames, or the call raises ``ValueError`` (``animate='morph'`` needs the same number of datasets in each panel). diff --git a/examples/animate_panels.py b/examples/animate_panels.py index 7098e9c2a..0e6c6d62f 100644 --- a/examples/animate_panels.py +++ b/examples/animate_panels.py @@ -32,4 +32,4 @@ def timepoint(ctx): # (on Colab the default backend would be plotly) fig, ani = hyp.plot(data, panels=(1, 3), animate=True, duration=10, title=['Participant 1', 'Participant 2', 'Participant 3'], - caption=timepoint, size=(10, 3.6), backend='matplotlib') + caption=timepoint, backend='matplotlib') diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index e1622a953..7e428653a 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -4530,6 +4530,11 @@ def _reemit_panel_warnings(probe_caught, draw_caught): registry=registry) +#: side (inches) of one panel's cell in an animated `panels=` grid's default +#: figure (no `size=`); see `_plot_panels` +_ANIMATED_PANEL_CELL_INCHES = 3.2 + + def _plot_panels(x, panels, call_kwargs, _name='panels'): """Draw one panel per dataset (or per `reduce=` entry) in a single figure -- the implementation behind `hyp.plot(..., panels=)`. With @@ -4828,8 +4833,18 @@ def _plot_panels(x, panels, call_kwargs, _name='panels'): _reemit_panel_warnings(probe_warnings, draw_warnings) return grid + _grid_size = call_kwargs.get('size') + if animated and _grid_size is None: + # an animated grid's default figure is sized BY the grid, one + # square cell per panel: every frame of the saved clip carries the + # figure's whole canvas, and matplotlib's 6.4 x 4.8 in default + # leaves a 1 x 4 row of cubes with more blank canvas above and + # below it than the cubes themselves fill (GH #295). Never narrower + # than that default, so a single column keeps its usual width. + _grid_size = (max(6.4, _ANIMATED_PANEL_CELL_INCHES * ncols), + _ANIMATED_PANEL_CELL_INCHES * nrows) fig, axes = subplots(nrows, ncols, ndims=panel_ndims, - size=call_kwargs.get('size'), backend='matplotlib') + size=_grid_size, backend='matplotlib') panel_axes = [] panel_models = [] #: an animated grid's panels, in panel order: each animated panel call @@ -7861,7 +7876,10 @@ def plot( it past its cell; with axis labels (`xlabel=`/`ylabel=`/`zlabel=`) the figure is enlarged so the rotating labels fit as well (an explicit `size=` too small for them raises, naming a size that - fits). `caption=` adds a line of text under the grid, updated + fits). Without `size=` the figure is sized BY THE GRID -- 3.2 in + per panel each way, at least 6.4 in wide -- so a saved clip of a + row of panels is not mostly blank canvas (a static grid keeps the + 6.4 x 4.8 in default). `caption=` adds a line of text under the grid, updated every frame. `on_frame=` is called ONCE per frame for the whole figure: its ``FrameContext`` has ``axes`` as a tuple of the panel axes, ``artists`` and ``datasets`` as every panel's in panel diff --git a/tests/test_animated_panels.py b/tests/test_animated_panels.py index becb89c74..56c0dd0f9 100644 --- a/tests/test_animated_panels.py +++ b/tests/test_animated_panels.py @@ -97,6 +97,41 @@ def test_the_grid_draws_duration_times_frame_rate_frames(duration, assert anim.n_frames == int(round(duration * frame_rate)) +@pytest.mark.parametrize('shape, expected', [ + ((1, 4), (12.8, 3.2)), ((2, 2), (6.4, 6.4)), ((4, 1), (6.4, 12.8)), + ((1, 3), (9.6, 3.2))]) +def test_the_default_figure_is_sized_by_the_grid(shape, expected): + """No `size=`: one 3.2 in square cell per panel (never narrower than + matplotlib's 6.4 in), so a saved clip of a 1 x 4 row is not mostly blank + canvas above and below the panels. Bare panels (no title, legend, + labels or caption) need no extra room, so the size is exactly that.""" + ani = _grid(DATA[:shape[0] * shape[1]], panels=shape) + assert tuple(ani.figure.get_size_inches()) == pytest.approx(expected) + + +def test_the_default_grid_figure_is_mostly_panel_not_blank_canvas(): + """What the sizing is for: in a 1 x 4 row, the panels' cubes span most + of the figure's height on a real draw (they spanned about a fifth of + it on the 6.4 x 4.8 in default).""" + ani = _grid() + fig = ani.figure + ani.draw_frame(0) + fig.canvas.draw() + ink = np.asarray(fig.canvas.buffer_rgba())[..., :3].min(axis=2) < 128 + rows = np.flatnonzero(ink.any(axis=1)) + assert (rows[-1] - rows[0]) / ink.shape[0] > 0.45 + + +def test_an_explicit_size_is_kept_for_a_bare_grid(): + ani = _grid(size=(9, 4)) + assert tuple(ani.figure.get_size_inches()) == pytest.approx((9, 4)) + + +def test_a_static_grid_keeps_its_default_size(): + fig = hyp.plot(DATA, panels=(1, 4), show=False) + assert tuple(fig.get_size_inches()) == pytest.approx((6.4, 4.8)) + + def test_subplots_alias_animates_the_same_grid(): anim = hyp.plot(DATA, subplots=(2, 2), animate=True, duration=1, frame_rate=8, show=False) From a26288c7eed3b77da1036db3b65f9bdafc7542c6 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 05:25:59 -0500 Subject: [PATCH 13/58] feat: panel grids share colors, one legend and one colorbar (GH #295) Color means one thing across a panels= grid: each dataset keeps its single-axes color, hue= maps through one grid-wide scale, and the legend and colorbar are drawn once, in a strip right of the grid, on both backends and for animated grids. Per-panel legends/colorbars remain only where clusters are fit per panel. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/plot/plot.py | 1017 ++++++++++++++++++--- hypertools/plot/plotly_backend.py | 147 ++- tests/test_panels_shared_legend_colors.py | 487 ++++++++++ 3 files changed, 1538 insertions(+), 113 deletions(-) create mode 100644 tests/test_panels_shared_legend_colors.py diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index 7e428653a..4acb42d59 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -4376,6 +4376,26 @@ def _grow_figure_downward(fig, extra_in): pos.width, pos.height * h_in / new_h_in], which=which) +def _grow_figure_rightward(fig, extra_in): + """Make `fig` wider by `extra_in` inches, adding the room on the + RIGHT: every axes keeps its absolute size and its distance from the + left, top and bottom edges (`_grow_figure_downward`'s twin).""" + w_in, h_in = fig.get_size_inches() + new_w_in = w_in + float(extra_in) + try: + fig.set_layout_engine('none') + except Exception: + pass + placed = [(axis, axis.get_position(original=True), axis.get_position()) + for axis in fig.axes] + fig.set_size_inches(new_w_in, h_in) + for axis, original, active in placed: + for which, pos in (('original', original), ('active', active)): + axis.set_position( + [pos.x0 * w_in / new_w_in, pos.y0, + pos.width * w_in / new_w_in, pos.height], which=which) + + def _blank_bottom_in(fig): """How many inches at the bottom of `fig` hold nothing: the distance from the canvas' bottom edge up to the lowest thing drawn (any axes, @@ -4434,7 +4454,9 @@ def _add_caption(fig, text, font=None, family=None): def _panel_probe(data, kw, ndims, caught_warnings): """Fit one panel grid's pipeline exactly as the equivalent single-axes call fits it -- by MAKING that call (``return_model=True``, figure - thrown away) -- and hand back ``(xform, pipeline, clustering)``: the analyzed rows + thrown away) -- and hand back ``(xform, pipeline, clustering, colors)`` + (``colors`` being the call's resolved color scale, its bundle's + ``'colors'``, which a grid shares across its panels): the analyzed rows (one array per input dataset; for ``ndims`` > 3 the 3-D display projection the single-axes call drew, since a reduce=None panel cannot draw wider rows, P4), the fitted pipeline, and the clustering the @@ -4483,7 +4505,7 @@ def _panel_probe(data, kw, ndims, caught_warnings): if models.get('cluster_labels') is not None: clustering = (models['cluster_labels'], _panel_cluster_model(kw), _hard_cluster_categories(models['cluster_labels'])) - return xform, probe.get('pipeline'), clustering + return xform, probe.get('pipeline'), clustering, probe.get('colors') def _panel_cluster_model(kw): @@ -4535,6 +4557,530 @@ def _reemit_panel_warnings(probe_caught, draw_caught): _ANIMATED_PANEL_CELL_INCHES = 3.2 +# -------------------------------------------------------------------------- +# A `panels=` grid's shared colors, legend and colorbar (1.2): color means +# one thing across the whole figure, and what explains it is drawn once. +# -------------------------------------------------------------------------- + +#: ``gid`` of the ONE legend a `panels=` grid draws for the whole figure (a +#: figure-level legend: ``fig.legends``), and of the axes of its one +#: colorbar -- how a caller finds them on the returned figure. +SHARED_LEGEND_GID = 'hypertools-shared-legend' +SHARED_COLORBAR_GID = 'hypertools-shared-colorbar' + +#: blank room (inches) left of, between and right of the shared legend and +#: colorbar in the strip a grid reserves for them beside its panels +_SHARED_STRIP_PAD_IN = 0.15 + +#: width (inches) of the shared colorbar's bar, and its height as a +#: fraction of the grid's +_SHARED_COLORBAR_WIDTH_IN = 0.18 +_SHARED_COLORBAR_HEIGHT = 0.6 + + +class _PanelFurnitureConflict(Exception): + """The panels' legends (or colorbars) cannot be drawn once for the + figure: one label looks different in two panels, so a single entry + would be wrong for one of them. The grid then keeps them per panel.""" + + +def _panel_meanings_differ(kw, per_panel_reduce, panel_fit): + """Whether the grid's colors mean something DIFFERENT in every panel, + so each panel must keep its own legend/colorbar: clusters + (`cluster=`/`n_clusters=`) fit separately per panel -- under + ``panel_fit='independent'``, or in a reducer-list grid, where each + panel clusters its own embedding -- and forecast clusters + (`forecast_cluster=`/`forecast_n_clusters=`), which every panel fits + over its own forecasts. Cluster 1 of one panel is then not cluster 1 + of the next.""" + clustered = bool(kw.get('cluster')) or kw.get('n_clusters') is not None + if clustered and (per_panel_reduce or panel_fit == 'independent'): + return True + return (kw.get('predict') is not None + and (bool(kw.get('forecast_cluster')) + or kw.get('forecast_n_clusters') is not None)) + + +def _panel_dataset_colors(grid_kw, sources): + """The color each dataset takes in the single-axes call of ALL of them + (`grid_kw`: the grid's own kwargs), one per dataset -- what a one-panel- + per-dataset grid draws dataset i in, so a color names one dataset + across the figure. An entry is None where the single-axes call colors + the dataset some other way that each panel already reproduces: an + explicit `color=`, a color letter in `fmt=`, a per-dataset or + ``{category: color}`` `palette=`, a `hue=`/`cluster=` grouping, or a + MultiIndex frame (drawn as several traces).""" + n = len(sources) + none = [None] * n + if (grid_kw.get('hue') is not None or grid_kw.get('cluster') + or grid_kw.get('n_clusters') is not None + or grid_kw.get('color') is not None + or grid_kw.get('colors') is not None): + return none + palette = grid_kw.get('palette') + palette = 'hls' if palette is None else palette + if (isinstance(palette, collections.abc.Mapping) + or _looks_like_dataset_palettes(palette)): + return none + if any(isinstance(getattr(src, 'index', None), pd.MultiIndex) + for src in sources): + return none + fmts = _panel_draw_fmts(grid_kw.get('fmt'), n) + cycle = iter(_palette_continuation(palette, n)) + colors = [] + for i in range(n): + letter = _fmt_color_letter( + fmts[i] if fmts is not None and i < len(fmts) else None) + color = None if letter is not None else next(cycle, None) + colors.append(None if color is None + else tuple(float(v) for v in color[:3])) + return colors + + +def _panel_color_probe(lengths, grid_kw): + """The color scale the single-axes call of every dataset resolves for + the grid's `hue=` (its bundle's ``'colors'``), for a grid with no such + call to read it from (``panel_fit='independent'`` fits each panel + alone): that call's color resolution, run on placeholder rows of the + datasets' own lengths with no analysis. None when it cannot be + resolved (the grid then keeps per-panel legends and colorbars).""" + rows = [np.column_stack([np.linspace(0.0, 1.0, max(int(n), 1)), + np.linspace(1.0, 0.0, max(int(n), 1)) ** 2, + np.sin(np.arange(max(int(n), 1)))]) + for n in lengths] + try: + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + probe = plot(rows, hue=grid_kw.get('hue'), + palette=grid_kw.get('palette') or 'hls', + fmt=grid_kw.get('fmt'), reduce=None, show=False, + return_model=True, backend='matplotlib') + except Exception: # noqa: BLE001 - reported by the panel calls instead + return None + if isinstance(probe.get('fig'), plt.Figure): + plt.close(probe['fig']) + return probe.get('colors') + + +def _hue_label_strings(hue): + """The distinct category labels of a (panel's) categorical `hue=`, as + the strings the resolved color scale keys its categories by; missing + labels (None/NaN) are not categories.""" + out = [] + + def _walk(value): + if isinstance(value, (str, bytes)) or np.ndim(value) == 0: + if not is_missing_label(value) and str(value) not in out: + out.append(str(value)) + return + for item in (value.tolist() if isinstance(value, np.ndarray) + else list(value)): + _walk(item) + + _walk(hue) + return out + + +def _panel_apply_hue_scale(kw, scale, shared): + """Make one panel (kwargs `kw`, already narrowed to its dataset) draw + its `hue=` under the GRID's color scale `scale` (the single-axes + call's ``'colors'``): a continuous hue is mapped over the grid-wide + value range (``shared['limits']``, see `plot`'s ``_panel_shared``), + and a categorical hue through the grid's own ``{category: color}`` + mapping, narrowed to the categories this panel has (a `palette=` + mapping may only name categories the plot draws). Returns False when + the panel has a category the scale does not know -- the grid then + cannot claim one shared mapping.""" + if not isinstance(scale, dict) or kw.get('hue') is None: + return True + if scale.get('kind') == 'continuous': + shared['limits'] = (float(scale['vmin']), float(scale['vmax'])) + return True + categories = scale.get('categories') or {} + if scale.get('kind') != 'discrete' or not categories \ + or _looks_like_dataset_palettes(kw.get('palette')): + return True + try: + present = _hue_label_strings(kw['hue']) + except TypeError: + return False + if any(label not in categories for label in present): + return False + if present: + kw['palette'] = {label: tuple(categories[label]) + for label in categories if label in present} + return True + + +def _legend_handle_signature(handle, color=True): + """What a legend handle LOOKS like, as a comparable value: its artist + type, line/marker/hatch styling and (with `color`) its colors. Two + entries with the same label and the same signature are the same + entry.""" + from matplotlib.colors import to_rgba_array + + def _plain(value): + try: + return np.round(np.asarray(value, dtype=float), 4).tolist() + except (TypeError, ValueError): + return repr(value) + + signature = [type(handle).__name__] + for getter in ('get_linestyle', 'get_linewidth', 'get_marker', + 'get_markersize', 'get_alpha', 'get_hatch', 'get_sizes'): + if hasattr(handle, getter): + signature.append((getter, _plain(getattr(handle, getter)()))) + if color: + for getter in ('get_color', 'get_markerfacecolor', + 'get_markeredgecolor', 'get_facecolor', + 'get_edgecolor'): + if not hasattr(handle, getter): + continue + value = getattr(handle, getter)() + try: + value = np.round(to_rgba_array(value), 4).tolist() + except (TypeError, ValueError): + value = repr(value) + signature.append((getter, value)) + return repr(signature) + + +def _merge_panel_legends(panel_axes): + """The ONE legend a grid draws for its panels' legends: ``(handles, + labels, template)``, or None when no panel drew a legend. `template` + is the first panel legend, whose text styling the shared one copies. + + The entries are the union of the panels', without duplicates: the data + entries in panel (dataset) order, then the `predict=`/`truth=` overlay + entries. Two entries are one when they have the same label and look + the same. An overlay entry that differs between panels only in color + (one model's forecasts, each continuing a dataset of another color) is + one entry in the neutral `forecast.FORECAST_LEGEND_COLOR`, the glyph + the single-axes legend gives a label that spans several colors. Any + other label that looks different in two panels raises + `_PanelFurnitureConflict`: one entry would be wrong for a panel. + """ + from matplotlib.lines import Line2D + from .forecast import FORECAST_LEGEND_COLOR + entries = [] + template = None + for ax in panel_axes: + legend = ax.get_legend() + if legend is None: + continue + template = legend if template is None else template + overlay = {getattr(line, '_hyp_forecast_label', None) + for line in ax.lines + if getattr(line, '_hyp_forecast_role', None) + in ('static', 'live')} + overlay |= {getattr(line, '_hyp_truth_label', None) + for line in ax.lines} + overlay = {str(label) for label in overlay if label is not None} + for handle, text in zip(legend.legend_handles, legend.get_texts()): + label = text.get_text() + entry = {'label': label, 'handle': handle, + 'look': _legend_handle_signature(handle), + 'shape': _legend_handle_signature(handle, color=False), + 'overlay': label in overlay} + same = [e for e in entries if e['label'] == label] + if not same: + entries.append(entry) + elif any(e['look'] == entry['look'] for e in same): + continue + elif (entry['overlay'] and isinstance(handle, Line2D) + and any(e['overlay'] and e['shape'] == entry['shape'] + for e in same)): + for e in same: + if e['overlay'] and e['shape'] == entry['shape']: + e['neutral'] = True + else: + raise _PanelFurnitureConflict(label) + if template is None: + return None + ordered = ([e for e in entries if not e['overlay']] + + [e for e in entries if e['overlay']]) + handles = [] + for entry in ordered: + handle = entry['handle'] + if entry.get('neutral'): + handle = Line2D( + [], [], color=FORECAST_LEGEND_COLOR, + linestyle=handle.get_linestyle(), + linewidth=handle.get_linewidth(), alpha=handle.get_alpha(), + marker=handle.get_marker(), + markersize=handle.get_markersize(), label=entry['label']) + handles.append(handle) + return handles, [e['label'] for e in ordered], template + + +def _merge_panel_colorbars(infos, order=None): + """The ONE colorbar a grid draws for its panels' colorbars (`infos`: + each panel's `_build_colorbar_info` result), or None without any. + Continuous scales over one palette merge into their common value range + (under a grid's shared limits they are already identical); discrete + scales into the union of their ``label -> color`` pairs, in `order` + (the grid scale's category order) when it covers them, else in panel + order. A label colored differently in two panels, or mixed kinds, + raises `_PanelFurnitureConflict`.""" + if not infos: + return None + merged = dict(infos[0]) + kinds = {info['kind'] for info in infos} + if kinds == {'continuous'}: + if any(repr(info['palette']) != repr(merged['palette']) + for info in infos): + raise _PanelFurnitureConflict('palette') + merged['vmin'] = min(info['vmin'] for info in infos) + merged['vmax'] = max(info['vmax'] for info in infos) + return merged + if kinds != {'discrete'}: + raise _PanelFurnitureConflict('kind') + mapping = {} + for info in infos: + for label, color in zip(info['labels'], np.asarray(info['colors'])): + color = np.asarray(color, dtype=float)[:3] + if str(label) not in mapping: + mapping[str(label)] = (label, color) + elif not np.allclose(mapping[str(label)][1], color, atol=1e-6): + raise _PanelFurnitureConflict(str(label)) + keys = list(mapping) + if order is not None and set(keys) <= set(order): + keys = [key for key in order if key in mapping] + merged['labels'] = [mapping[key][0] for key in keys] + merged['colors'] = np.asarray([mapping[key][1] for key in keys]) + return merged + + +def _merge_panel_color_scales(scales, dataset_mode=False, names=None): + """A grid bundle's ``'colors'``: the one color scale its panels share, + merged from each panel's own (`scales`, the panel bundles' + ``'colors'``). Continuous scales are the grid's common one; discrete + scales merge into the union of their groups -- every dataset's color, + in panel order, for a one-panel-per-dataset grid (`dataset_mode`) with + nothing grouping the data (labeled with `names`, the grid's `legend=` + list, when given), otherwise ``label -> color`` by name. Where + the panels' scales do not combine (colors that mean different things + per panel), the first panel's is returned as before and each panel's + own is in ``panel_models[i]['colors']``.""" + from matplotlib.colors import BoundaryNorm, ListedColormap + scales = [s for s in scales if isinstance(s, dict)] + if not scales: + return None + first = scales[0] + if len(scales) == 1 or {s.get('kind') for s in scales} != {'discrete'}: + return first + if any(s.get('colors') is None for s in scales): + return first + ungrouped = dataset_mode and all( + len(s['colors']) == 1 for s in scales) + if ungrouped: + colors = [np.asarray(s['colors'][0], dtype=float)[:3] + for s in scales] + if names is not None and len(names) == len(scales): + labels, named = list(names), True + else: + labels, named = [i + 1 for i in range(len(scales))], False + else: + try: + merged = _merge_panel_colorbars( + [{'kind': 'discrete', 'labels': s['labels'], + 'colors': s['colors']} for s in scales]) + except _PanelFurnitureConflict: + return first + colors, labels = list(merged['colors']), merged['labels'] + named = any(s.get('categories') for s in scales) + colors = np.asarray(colors) + return dict(first, cmap=ListedColormap(colors), + norm=BoundaryNorm(np.arange(len(colors) + 1) - 0.5, + len(colors)), + colors=colors, labels=list(labels), + categories=({str(label): tuple(color) + for label, color in zip(labels, colors)} + if named else {})) + + +def _shared_legend_call(template, legend_kwargs): + """``(kwargs, placed)`` for the grid's one figure-level legend: the + styling hypertools draws a legend with, in the panels' own text font + (`template` is one of their legends), under the caller's + `legend_kwargs=`. `placed` says the caller positioned it + (``loc``/``bbox_to_anchor``): those then place the one legend in + FIGURE coordinates and no strip is reserved for it.""" + call = dict(loc='center left', borderaxespad=0.0, frameon=False) + texts = template.get_texts() + if texts: + call['prop'] = texts[0].get_fontproperties() + user = dict(legend_kwargs or {}) + placed = 'loc' in user or 'bbox_to_anchor' in user + if 'fontsize' in user and 'prop' in call and 'prop' not in user: + prop = call['prop'].copy() + prop.set_size(user.pop('fontsize')) + call['prop'] = prop + call.update(user) + return call, placed + + +def _add_shared_furniture(fig, panel_axes, legend_spec, colorbar_info, + legend_kwargs=None, widen=True): + """Draw a panel grid's ONE legend and/or ONE colorbar in a strip to + the right of the grid, and lay the grid out beside it. + + `legend_spec` is `_merge_panel_legends`' result (the panels' own + legends are removed here) and `colorbar_info` `_merge_panel_colorbars`' + (either may be None). The strip is as wide as what it holds, measured + on a real draw: with `widen` (no explicit `size=`) the figure grows by + that much, so the panels keep their size; otherwise the grid is laid + out in the figure's remaining width. A legend too tall for the figure + is wrapped into columns. A colorbar whose ``location`` is not + ``'right'`` is attached to the whole grid on that side instead + (matplotlib's own multi-axes colorbar). + + Returns the strip's state for `_place_shared_furniture`, which + positions the legend and colorbar and is called again whenever the + figure is resized afterwards (the caption, an animated grid's cube + fit). + """ + from matplotlib.cm import ScalarMappable + from matplotlib.colors import BoundaryNorm, ListedColormap, Normalize + strip = {'legend': None, 'colorbar': None, 'legend_in': (0.0, 0.0), + 'colorbar_in': 0.0, 'panel_axes': list(panel_axes), + 'placed': False, 'rect_right': 1.0} + pad = _SHARED_STRIP_PAD_IN + width_in, height_in = fig.get_size_inches() + + if legend_spec is not None: + handles, labels, template = legend_spec + call, placed = _shared_legend_call(template, legend_kwargs) + for ax in panel_axes: + if ax.get_legend() is not None: + ax.get_legend().remove() + if not placed: + call['bbox_to_anchor'] = (0.5, 0.5) + call['bbox_transform'] = fig.transFigure + columns = 1 + while True: + _call = dict(call) + if columns > 1: + _call['ncols'] = columns + legend = fig.legend(handles, labels, **_call) + box = legend.get_window_extent(_measurement_renderer(fig)) + size_in = (box.width / fig.dpi, box.height / fig.dpi) + if (placed or 'ncols' in call or 'ncol' in call + or size_in[1] <= height_in - 2 * pad + or columns >= len(labels)): + break + # too tall for the figure: wrap the entries into columns + legend.remove() + columns = max(columns + 1, int(np.ceil( + columns * size_in[1] / (height_in - 2 * pad)))) + legend.set_gid(SHARED_LEGEND_GID) + strip.update(legend=legend, placed=placed, + legend_in=(0.0, 0.0) if placed else size_in) + + mappable = ticklabels = None + if colorbar_info is not None: + if colorbar_info['kind'] == 'continuous': + mappable = ScalarMappable( + norm=Normalize(vmin=colorbar_info['vmin'], + vmax=colorbar_info['vmax']), + cmap=continuous_colormap(colorbar_info['palette'])) + ticks = colorbar_info['ticks'] + else: + n = len(colorbar_info['colors']) + mappable = ScalarMappable( + norm=BoundaryNorm(np.arange(n + 1) - 0.5, n), + cmap=ListedColormap(colorbar_info['colors'])) + ticks = (colorbar_info['ticks'] + if colorbar_info['ticks'] is not None + else list(range(n))) + if colorbar_info['ticks'] is None: + ticklabels = [str(lbl) for lbl in colorbar_info['labels']] + mappable.set_array([]) + in_strip = mappable is not None and colorbar_info['location'] == 'right' + + def _finish(cbar): + if ticklabels is not None: + cbar.set_ticklabels(ticklabels) + if colorbar_info['label']: + cbar.set_label(colorbar_info['label']) + _apply_font_to_colorbar(cbar, colorbar_info.get('font')) + if (colorbar_info['kind'] == 'discrete' + and colorbar_info['location'] in ('right', 'left')): + # first group at the top, as the legend reads (`_add_colorbar`) + cbar.ax.invert_yaxis() + cbar.ax.set_gid(SHARED_COLORBAR_GID) + strip['colorbar'] = cbar + + if in_strip: + cax = fig.add_axes([0.45, 0.2, _SHARED_COLORBAR_WIDTH_IN / width_in, + 0.6]) + _finish(fig.colorbar(mappable, cax=cax, + **({} if ticks is None else {'ticks': ticks}))) + box = cax.get_tightbbox(_measurement_renderer(fig)) + strip['colorbar_in'] = box.width / fig.dpi + + strip_in = sum(part + pad for part in (strip['legend_in'][0], + strip['colorbar_in']) if part) + if strip_in: + strip_in += pad + # The grid is laid out in a figure WITHOUT the strip -- the figure as + # it is when it is about to grow by the strip, or narrowed by it under + # an explicit `size=` -- and the strip is then added on the right + # (`_grow_figure_rightward`), so the layout is exactly the legend-less + # grid's. (`tight_layout(rect=...)` is not: it drops the room a 3-D + # panel's title needs, which then pokes out of the top of the canvas.) + grid_in = width_in if widen else max(width_in - strip_in, + 0.3 * width_in) + strip_in = (width_in + strip_in if widen else width_in) - grid_in + fig.set_size_inches(grid_in, height_in) + with warnings.catch_warnings(): + # the colorbar's axes is placed by hand (below), which + # `tight_layout` reports as an axes it cannot lay out + warnings.filterwarnings( + 'ignore', message='This figure includes Axes that are not ' + 'compatible with tight_layout') + # the panels were last laid out around their own legends, which + # are gone: one pass from there under-reserves a 3-D panel's + # title room (its box is aspect-constrained), a second settles it + for _ in range(3): + fig.tight_layout() + _grow_figure_rightward(fig, strip_in) + strip['rect_right'] = grid_in / (grid_in + strip_in) + if mappable is not None and not in_strip: + _finish(fig.colorbar( + mappable, ax=list(panel_axes), + location=colorbar_info['location'], + shrink=_SHARED_COLORBAR_HEIGHT, + **({} if ticks is None else {'ticks': ticks}))) + _place_shared_furniture(fig, strip) + return strip + + +def _place_shared_furniture(fig, strip): + """Position a grid's shared legend and colorbar (`strip`, from + `_add_shared_furniture`) in the strip right of the panels: the legend + first, then the colorbar, each vertically centered on the grid. + Idempotent, and re-run after anything resizes the figure -- the strip + starts at the same fraction of the figure's width, and what it holds + keeps its size in inches.""" + if strip is None: + return + width_in, height_in = fig.get_size_inches() + boxes = [ax.get_position() for ax in strip['panel_axes']] + y0, y1 = min(b.y0 for b in boxes), max(b.y1 for b in boxes) + middle = 0.5 * (y0 + y1) + x = strip['rect_right'] + _SHARED_STRIP_PAD_IN / width_in + legend = strip['legend'] + if legend is not None and not strip['placed']: + legend.set_bbox_to_anchor((x, middle), transform=fig.transFigure) + x += (strip['legend_in'][0] + _SHARED_STRIP_PAD_IN) / width_in + cbar = strip['colorbar'] + if cbar is not None and strip['colorbar_in']: + height = _SHARED_COLORBAR_HEIGHT * (y1 - y0) + cbar.ax.set_position([x, middle - 0.5 * height, + _SHARED_COLORBAR_WIDTH_IN / width_in, height]) + + def _plot_panels(x, panels, call_kwargs, _name='panels'): """Draw one panel per dataset (or per `reduce=` entry) in a single figure -- the implementation behind `hyp.plot(..., panels=)`. With @@ -4679,6 +5225,9 @@ def _plot_panels(x, panels, call_kwargs, _name='panels'): shared_pipeline = None #: the warnings the probes raised, re-issued once the grid is drawn probe_warnings = [] + #: the color scale the single-axes call of the whole grid resolves + #: (its bundle's ``'colors'``), which the panels share + grid_scale = None #: per panel: the input datasets it draws (for their index/column #: labels), its analyzed rows (one array per dataset), its fitted #: pipeline, and its narrowed kwargs @@ -4693,13 +5242,14 @@ def _plot_panels(x, panels, call_kwargs, _name='panels'): panel_kwargs.append(kw) probes = [_panel_probe(x, kw, ndims, probe_warnings) for kw in panel_kwargs] - panel_xforms = [xf for xf, _, _ in probes] - panel_pipelines = [pipe for _, pipe, _ in probes] + panel_xforms = [probe[0] for probe in probes] + panel_pipelines = [probe[1] for probe in probes] + grid_scale = probes[0][3] # each reducer panel draws EVERY dataset: its probe's labels whole panel_clusters = [ None if clus is None else _panel_cluster_labels( clus[0], clus[1], kw.get('cluster'), categories=clus[2]) - for (_, _, clus), kw in zip(probes, panel_kwargs)] + for (_, _, clus, _), kw in zip(probes, panel_kwargs)] elif panel_fit == 'independent': # one FULL pipeline per panel: each panel's fit is byte-for-byte # the ``hyp.plot(datasets[i], ...)`` the caller would have written, @@ -4718,18 +5268,18 @@ def _plot_panels(x, panels, call_kwargs, _name='panels'): probes = [_panel_probe(panel_sources[i], panel_kwargs[i], ndims, probe_warnings) for i in range(n_panels)] - panel_xforms = [xf for xf, _, _ in probes] - panel_pipelines = [pipe for _, pipe, _ in probes] + panel_xforms = [probe[0] for probe in probes] + panel_pipelines = [probe[1] for probe in probes] # each probe clustered its own panel's rows: replayed whole panel_clusters = [ None if clus is None else _panel_cluster_labels( clus[0], clus[1], kw.get('cluster'), categories=clus[2]) - for (_, _, clus), kw in zip(probes, panel_kwargs)] + for (_, _, clus, _), kw in zip(probes, panel_kwargs)] else: # ONE shared fit across every dataset: run the very call the user # would have made without panels=, take its analyzed (pre-display- # rescale) data, and give each panel its own dataset's rows - xform, shared_pipeline, shared_clustering = _panel_probe( + xform, shared_pipeline, shared_clustering, grid_scale = _panel_probe( x, shared, ndims, probe_warnings) lengths = [int(xi.shape[0]) for xi in xform] panel_sources = [[datasets[i]] for i in range(n_panels)] @@ -4760,6 +5310,56 @@ def _plot_panels(x, panels, call_kwargs, _name='panels'): # after the pipeline) panel_ndims = _panel_cell_ndims( panel_ndims, [xi for xf in panel_xforms for xi in xf]) + + # COLOR MEANS ONE THING ACROSS THE FIGURE (1.2). A reducer-list grid's + # panels each draw every dataset through the same color resolution, so + # they agree already. A one-panel-per-dataset grid's panels each see + # one dataset, so the grid resolves what the single-axes call of ALL + # the datasets would draw and hands every panel its share: its + # dataset's color (palette position i of n), its number under + # ``legend=True``, and the grid's `hue=` scale (one value range for a + # continuous hue, one category -> color mapping for a categorical one). + meanings_differ = _panel_meanings_differ(shared, per_panel_reduce, + panel_fit) + #: per panel, what `plot()` reads as ``_panel_shared`` + panel_shared = [{} for _ in range(n_panels)] + #: the names a one-panel-per-dataset grid's bundle lists its datasets' + #: colors under (the `legend=` list), when nothing groups the data + color_names = None + if not per_panel_reduce: + if shared.get('hue') is not None and panel_fit == 'independent': + grid_scale = _panel_color_probe(lengths, shared) + if grid_scale is None: + meanings_differ = True + # one drawn trace per dataset (ndims=1 draws one line per COLUMN, + # colored by column in every panel alike) + one_trace = panel_ndims != 1 or all( + xi.ndim == 2 and xi.shape[1] == 1 + for xf in panel_xforms for xi in xf) + own_colors = (_panel_dataset_colors(shared, datasets) if one_trace + else [None] * n_panels) + ungrouped = (shared.get('hue') is None and not shared.get('cluster') + and shared.get('n_clusters') is None) + _legend = shared.get('legend') + if (ungrouped and isinstance(_legend, (list, tuple)) + and len(_legend) == n_panels): + color_names = list(_legend) + for i in range(n_panels): + kw = panel_kwargs[i] + if own_colors[i] is not None: + kw['color'] = [own_colors[i]] + if kw.get('legend') is True and ungrouped and panel_ndims != 1: + # the single-axes call numbers its datasets 1..n; every + # panel numbered its own dataset 1 + kw['legend'] = [i + 1] + if not _panel_apply_hue_scale(kw, grid_scale, panel_shared[i]): + # a panel's categories are not the grid scale's: no + # shared mapping to claim + meanings_differ = True + #: the grid scale's category order, for the shared colorbar + scale_order = (list(grid_scale['categories']) + if isinstance(grid_scale, dict) + and grid_scale.get('categories') else None) panel_data = [] for i in range(n_panels): kw = panel_kwargs[i] @@ -4829,7 +5429,10 @@ def _plot_panels(x, panels, call_kwargs, _name='panels'): grid = _plot_panels_plotly( panel_data, panel_kwargs, titles, nrows, ncols, panel_ndims, plotly_kwargs, shared_pipeline=shared_pipeline, - panel_pipelines=panel_pipelines) + panel_pipelines=panel_pipelines, + panel_shared=panel_shared, consolidate=not meanings_differ, + scale_order=scale_order, color_names=color_names, + dataset_mode=not per_panel_reduce) _reemit_panel_warnings(probe_warnings, draw_warnings) return grid @@ -4843,56 +5446,119 @@ def _plot_panels(x, panels, call_kwargs, _name='panels'): # than that default, so a single column keeps its usual width. _grid_size = (max(6.4, _ANIMATED_PANEL_CELL_INCHES * ncols), _ANIMATED_PANEL_CELL_INCHES * nrows) - fig, axes = subplots(nrows, ncols, ndims=panel_ndims, - size=_grid_size, backend='matplotlib') - panel_axes = [] - panel_models = [] - #: an animated grid's panels, in panel order: each animated panel call - #: appends its frame function, frame hooks and axes here (GH #295) - cells = [] if animated else None - with warnings.catch_warnings(record=True) as draw_warnings: - warnings.simplefilter('always') - for i in range(n_panels): - kw = dict(panel_kwargs[i]) - kw.update(ax=axes[i], title=titles[i], show=False, - save_path=None, return_model=return_model, size=None) - if animated: - kw['_panel_animation'] = cells - if panel_ndims < (3 if ndims is None else min(ndims, 3)): - # cells lowered to the data's width (`_panel_cell_ndims`): - # the panel call's `ax=` projection check reads ndims=, - # not the data, so tell it the dimensionality its axes - # actually has (the drawing is the same: the rows are - # already analyzed) - kw['ndims'] = panel_ndims - result = plot(panel_data[i], **kw) - if return_model: - # the fit this panel was drawn from: the panel itself is - # drawn through `transform=`, whose bundles carry - # `pipeline=None` (release audit 2026-09-07, 3) - result['pipeline'] = panel_pipelines[i] - panel_models.append(result) - panel_axes.append(axes[i]) + + def _draw_grid(consolidate): + """Draw every panel into a fresh grid figure. With `consolidate` + the panels hand their colorbars to the grid instead of drawing + them, and their legends are merged into one afterwards; returns + the figure, its axes, the panel bundles, the animated cells, the + draw-time warnings and the panels' colorbars.""" + fig, axes = subplots(nrows, ncols, ndims=panel_ndims, + size=_grid_size, backend='matplotlib') + models = [] + #: an animated grid's panels, in panel order: each animated panel + #: call appends its frame function, frame hooks and axes here + #: (GH #295) + cells = [] if animated else None + colorbars = [] + try: + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + for i in range(n_panels): + kw = dict(panel_kwargs[i]) + kw.update(ax=axes[i], title=titles[i], show=False, + save_path=None, return_model=return_model, + size=None) + if animated: + kw['_panel_animation'] = cells + kw['_panel_shared'] = dict( + panel_shared[i], + **({'colorbars': colorbars} if consolidate else {})) + if panel_ndims < (3 if ndims is None else min(ndims, 3)): + # cells lowered to the data's width + # (`_panel_cell_ndims`): the panel call's `ax=` + # projection check reads ndims=, not the data, so + # tell it the dimensionality its axes actually has + # (the drawing is the same: the rows are already + # analyzed) + kw['ndims'] = panel_ndims + result = plot(panel_data[i], **kw) + if return_model: + # the fit this panel was drawn from: the panel + # itself is drawn through `transform=`, whose + # bundles carry `pipeline=None` (release audit + # 2026-09-07, 3) + result['pipeline'] = panel_pipelines[i] + models.append(result) + except Exception: + plt.close(fig) + raise + return fig, axes, models, cells, caught, colorbars + + # ONE legend and ONE colorbar for the figure (1.2) whenever they say + # the same thing in every panel; per panel where the colors mean + # something different in each (`_panel_meanings_differ`), or where one + # label turns out to look different in two panels + # (`_PanelFurnitureConflict`: the grid is then drawn again, per panel) + consolidate = not meanings_differ + legend_spec = colorbar_info = None + fig, axes, panel_models, cells, draw_warnings, colorbars = _draw_grid( + consolidate) + panel_axes = list(axes[:n_panels]) + if consolidate: + try: + legend_spec = _merge_panel_legends(panel_axes) + colorbar_info = _merge_panel_colorbars(colorbars, scale_order) + except _PanelFurnitureConflict: + plt.close(fig) + consolidate = False + legend_spec = colorbar_info = None + (fig, axes, panel_models, cells, draw_warnings, + colorbars) = _draw_grid(False) + panel_axes = list(axes[:n_panels]) _reemit_panel_warnings(probe_warnings, draw_warnings) for spare in axes[n_panels:]: spare.set_visible(False) - if call_kwargs.get('size') is None: - # room beside every column for the legends/colorbars the panels - # drew -- what the plotly grid reserves as its gutter (110 px per - # legend or colorbar) -- so `tight_layout` does not shrink the - # panels to fit them (1.1 release review, feature-tour 9.8: three - # 10-entry legends left three 1.3 in cubes). An explicit `size=` - # is honored verbatim. - _cols = ncols if n_panels > 1 else 1 - _extra = 0.0 - if any(a.get_legend() is not None for a in panel_axes): - _extra += 1.1 * _cols - if len(fig.axes) > len(axes): # colorbar axes beside the panels - _extra += 1.1 * _cols - if _extra: - _w, _h = fig.get_size_inches() - fig.set_size_inches(_w + _extra, _h) - fig.tight_layout() + strip = None + if consolidate and (legend_spec is not None + or colorbar_info is not None): + # room for them is reserved ONCE, in a strip right of the grid: + # the default figure grows by the strip's measured width (an + # explicit `size=` is honored verbatim, the grid laid out beside + # the strip) + strip = _add_shared_furniture( + fig, panel_axes, legend_spec, colorbar_info, + legend_kwargs=call_kwargs.get('legend_kwargs'), + widen=call_kwargs.get('size') is None) + else: + if call_kwargs.get('size') is None: + # per-panel legends/colorbars (colors that mean something + # different in every panel): room beside every column for + # them -- what the plotly grid reserves as its gutter (110 px + # per legend or colorbar) -- so `tight_layout` does not shrink + # the panels to fit them (1.1 release review, feature-tour + # 9.8: three 10-entry legends left three 1.3 in cubes). An + # explicit `size=` is honored verbatim. + _cols = ncols if n_panels > 1 else 1 + _extra = 0.0 + if any(a.get_legend() is not None for a in panel_axes): + _extra += 1.1 * _cols + if len(fig.axes) > len(axes): # colorbar axes beside panels + _extra += 1.1 * _cols + if _extra: + _w, _h = fig.get_size_inches() + fig.set_size_inches(_w + _extra, _h) + fig.tight_layout() + + #: the bundle's ``'colors'``: the one scale the panels share + grid_colors = None + if return_model or animated: + _scales = ([m.get('colors') for m in panel_models] if return_model + else [cell['colors'] for cell in cells]) + grid_colors = (_scales[0] if _scales and meanings_differ + else _merge_panel_color_scales( + _scales, dataset_mode=not per_panel_reduce, + names=color_names)) if animated: return _animate_panel_grid( @@ -4901,7 +5567,8 @@ def _plot_panels(x, panels, call_kwargs, _name='panels'): dynamic_caption=dynamic_caption, font=call_kwargs.get('font'), save_path=save_path, show=show, return_model=return_model, shared_pipeline=shared_pipeline, - resize=call_kwargs.get('size') is None, _name=_name) + resize=call_kwargs.get('size') is None, _name=_name, + strip=strip, grid_colors=grid_colors) if caption is not None or dynamic_caption is not None: # a static grid's caption: fixed text, or the dynamic forms @@ -4909,6 +5576,9 @@ def _plot_panels(x, panels, call_kwargs, _name='panels'): # a static plot) _add_grid_caption(fig, caption, dynamic_caption, panel_axes, call_kwargs.get('font')) + # the caption's room was added under the grid: re-center the + # shared legend/colorbar on the panels + _place_shared_furniture(fig, strip) if save_path is not None: fig.savefig(save_path) @@ -4938,7 +5608,7 @@ def _plot_panels(x, panels, call_kwargs, _name='panels'): 'panel_models': panel_models, 'xform_data': [m['xform_data'][0] if len(m['xform_data']) == 1 else m['xform_data'] for m in panel_models], - 'colors': panel_models[0].get('colors') if panel_models else None, + 'colors': grid_colors, 'pipeline': shared_pipeline, } return bundle @@ -5187,7 +5857,8 @@ def _fit_cube(cell, target): def _animate_panel_grid(fig, cells, panel_axes, panel_models, grid, grid_hooks, caption, dynamic_caption, font, save_path, show, return_model, shared_pipeline, - resize=True, _name='panels'): + resize=True, _name='panels', strip=None, + grid_colors=None): """Turn a drawn grid of animated panels into ONE animation (GH #295). Every panel call left its frame function in `cells` (a @@ -5200,6 +5871,13 @@ def _animate_panel_grid(fig, cells, panel_axes, panel_models, grid, and returns exactly as an animated single-axes call does: a `HyperAnimation`, or the panel bundle with ``'animation'`` added when `return_model=True`. + + `strip` is the grid's shared legend/colorbar (`_add_shared_furniture`), + static across every frame: it sits in its own strip right of the + cells, which every rotating cube is fitted inside, and is re-placed + here after the cube fit and the caption resized the figure. + `grid_colors` is the color scale the panels share (the bundle's + ``'colors'`` and `HyperAnimation.colors`). """ from .animate import HyperFuncAnimation from .hyper_animation import HyperAnimation, mark_draw_started @@ -5224,6 +5902,7 @@ def _abandon(): interval = cells[0]['stub']._interval try: _fit_rotating_cubes(fig, cells, resize=resize, _name=_name) + _place_shared_furniture(fig, strip) except Exception: _abandon() raise @@ -5243,6 +5922,7 @@ def _draw_panels(num): fig, caption, dynamic_caption, panel_axes, font, context=(_draw_panels(0) if dynamic_caption is not None else None)) + _place_shared_furniture(fig, strip) except Exception: _abandon() raise @@ -5303,24 +5983,33 @@ def _grid_frame(num, *_): 'panel_models': panel_models, 'xform_data': [m['xform_data'][0] if len(m['xform_data']) == 1 else m['xform_data'] for m in panel_models], - 'colors': panel_models[0].get('colors') if panel_models else None, + 'colors': grid_colors, 'pipeline': shared_pipeline, 'animation': line_ani, } anim = HyperAnimation(fig, line_ani, frame_hooks=grid_hooks) - anim.colors = cells[0]['colors'] if cells else None + anim.colors = grid_colors return anim def _plot_panels_plotly(panel_data, panel_kwargs, titles, nrows, ncols, ndims, call_kwargs, shared_pipeline=None, - panel_pipelines=None): + panel_pipelines=None, panel_shared=None, + consolidate=False, scale_order=None, + color_names=None, dataset_mode=False): """`panels=` under the plotly backend: the same grid, built with `plotly.subplots.make_subplots` (3-D panels get ``type='scene'`` cells). Each panel is drawn by an ordinary `plot()` call and its traces (plus its scene/axis configuration) are transplanted into the cell. + With `consolidate` the grid shows ONE legend and ONE colorbar for the + figure, as the matplotlib grid does (see `_plot_panels`): + `panel_shared` is each panel's ``_panel_shared``, `scale_order` the + grid color scale's category order, and `color_names`/`dataset_mode` + what `_merge_panel_color_scales` builds the bundle's ``'colors'`` + from. + `return_model=True` gets the SAME bundle shape the matplotlib panel path returns -- ``fig``, ``axes``, ``panels``, ``panel_models``, ``xform_data``, ``colors`` (GH #285). Before this, every inner call was @@ -5337,30 +6026,61 @@ def _plot_panels_plotly(panel_data, panel_kwargs, titles, nrows, ncols, ``transform=``), both recorded in the bundle exactly as the matplotlib grid records them. """ - from .plotly_backend import (make_panel_grid, panel_gutter_px, + import plotly.graph_objects as go + from .plotly_backend import (PANEL_COLORBAR_PX, PANEL_GUTTER_PAD_PX, + PANEL_LEGEND_PX, PanelFurnitureConflict, + _colorbar_trace, _explicit_legend_position, + make_panel_grid, merge_panel_legends, + panel_gutter_px, place_shared_furniture, transplant_panel) return_model = bool(call_kwargs.get('return_model', False)) - # draw every panel FIRST (each an ordinary single-axes plotly call), so - # the grid can reserve room beside each cell for the legend/colorbar - # the panels actually carry - panel_models = [] - panel_figs = [] - for data, kw, title in zip(panel_data, panel_kwargs, titles): - kw = dict(kw) - # each panel's title goes through the ordinary single-axes title - # path (newlines, `title_wrap=`, `title_kwargs=`, validation) and - # `transplant_panel` turns the result into the cell's title -- the - # matplotlib grid formats its titles the same way (round 2) - kw.update(show=False, save_path=None, return_model=return_model, - title=title, size=None, backend='plotly') - result = plot(data, **kw) - panel_figs.append(result['fig'] if return_model else result) - if return_model: - if panel_pipelines is not None: - result['pipeline'] = panel_pipelines[len(panel_models)] - elif shared_pipeline is not None: - result['pipeline'] = shared_pipeline - panel_models.append(result) + + def _draw_panels(consolidate): + """Draw every panel (each an ordinary single-axes plotly call); + with `consolidate` the panels hand their colorbars to the grid + instead of drawing them. Returns the figures, the panel bundles + and those colorbars.""" + models, figs, colorbars = [], [], [] + for i, (data, kw, title) in enumerate( + zip(panel_data, panel_kwargs, titles)): + kw = dict(kw) + # each panel's title goes through the ordinary single-axes + # title path (newlines, `title_wrap=`, `title_kwargs=`, + # validation) and `transplant_panel` turns the result into the + # cell's title -- the matplotlib grid formats its titles the + # same way (round 2) + kw.update(show=False, save_path=None, return_model=return_model, + title=title, size=None, backend='plotly') + kw['_panel_shared'] = dict( + panel_shared[i] if panel_shared is not None else {}, + **({'colorbars': colorbars} if consolidate else {})) + result = plot(data, **kw) + figs.append(result['fig'] if return_model else result) + if return_model: + if panel_pipelines is not None: + result['pipeline'] = panel_pipelines[len(models)] + elif shared_pipeline is not None: + result['pipeline'] = shared_pipeline + models.append(result) + return figs, models, colorbars + + # draw every panel FIRST, so the grid can reserve room for the + # legend/colorbar the panels actually carry: ONE strip right of the + # grid for the shared ones (1.2), or a gutter beside each cell where + # they stay per panel (colors that mean something different in every + # panel; see `_plot_panels`) + panel_figs, panel_models, colorbars = _draw_panels(consolidate) + shared_legend = False + colorbar_info = None + if consolidate: + try: + shared_legend = (merge_panel_legends(panel_figs) + and bool(call_kwargs.get('legend'))) + colorbar_info = _merge_panel_colorbars(colorbars, scale_order) + except (PanelFurnitureConflict, _PanelFurnitureConflict): + consolidate = False + shared_legend, colorbar_info = False, None + panel_figs, panel_models, colorbars = _draw_panels(False) legend_present = call_kwargs.get('legend') is not None colorbar_present = any( getattr(getattr(trace, 'marker', None), 'showscale', None) @@ -5372,17 +6092,38 @@ def _plot_panels_plotly(panel_data, panel_kwargs, titles, nrows, ncols, title_px = max([0] + [max(0, int(panel.layout.margin.t or 0) - 10) for panel, title in zip(panel_figs, titles) if title]) + strip_px = 0 + if consolidate: + if shared_legend: + strip_px += PANEL_LEGEND_PX + if colorbar_info is not None \ + and colorbar_info.get('location', 'right') == 'right': + strip_px += PANEL_COLORBAR_PX + strip_px += PANEL_GUTTER_PAD_PX if strip_px else 0 fig = make_panel_grid(nrows, ncols, ndims, size=call_kwargs.get('size'), - gutter_px=panel_gutter_px(legend_present, - colorbar_present), - title_px=title_px) + gutter_px=(0 if consolidate else panel_gutter_px( + legend_present, colorbar_present)), + title_px=title_px, strip_px=strip_px) panel_axes = [] for i, panel in enumerate(panel_figs): keys = transplant_panel(fig, panel, i // ncols + 1, i % ncols + 1, i, ndims) panel_axes.append(keys['scene'] if ndims >= 3 else (keys['xaxis'], keys['yaxis'])) + if consolidate and (shared_legend or colorbar_info is not None): + _first_legend = (panel_figs[0].layout.legend.to_plotly_json() + if panel_figs[0].layout.legend is not None else {}) + _position = _explicit_legend_position(_first_legend) + place_shared_furniture( + fig, shared_legend, + (None if colorbar_info is None else _colorbar_trace( + go, colorbar_info, ndims, shared_legend)), + ndims, + legend_position=(None if _position is None else + {'x': _position['lx'], 'y': _position['ly']}), + font=(panel_figs[0].layout.font.to_plotly_json() + if panel_figs[0].layout.font is not None else None)) fig.update_layout(showlegend=bool(call_kwargs.get('legend'))) # the SAME figure class the single-axes plotly path returns, displayed # through the same one-shot end-of-cell queue: a bare `go.Figure` shown @@ -5417,7 +6158,11 @@ def _plot_panels_plotly(panel_data, panel_kwargs, titles, nrows, ncols, 'panel_models': panel_models, 'xform_data': [m['xform_data'][0] if len(m['xform_data']) == 1 else m['xform_data'] for m in panel_models], - 'colors': panel_models[0].get('colors') if panel_models else None, + 'colors': ( + (panel_models[0].get('colors') if panel_models else None) + if not consolidate else _merge_panel_color_scales( + [m.get('colors') for m in panel_models], + dataset_mode=dataset_mode, names=color_names)), 'pipeline': shared_pipeline, } return fig @@ -8449,6 +9194,17 @@ def plot( # function, frame hooks and axes to (`_plot_animated_panels` collects # them into the grid's single animation). Internal, never a user kwarg. _panel_animation = kwargs.pop('_panel_animation', None) + # ...and what a `panels=` grid shares across its panels (see + # `_plot_panels`): ``'limits'``, the grid-wide ``(vmin, vmax)`` of a + # continuous `hue=`, which this panel's value-to-color mapping must use + # so a color is the same value in every panel; and ``'colorbars'``, a + # list this call appends its resolved colorbar to INSTEAD of drawing it + # (the grid draws one for the figure, and one legend, so the panel's + # own legend is not fitted either). Internal, never a user kwarg. + _panel_shared = kwargs.pop('_panel_shared', None) + _hue_limits = (_panel_shared or {}).get('limits') + _grid_furniture = (_panel_shared is not None + and 'colorbars' in _panel_shared) # early kwarg validation (release-1.0 audit): catch renamed/misspelled/ # unknown keyword arguments HERE, with a clear TypeError naming the @@ -8478,7 +9234,9 @@ def plot( _panel_call = {k: v for k, v in locals().items() if k not in ('x', 'kwargs', 'panels', 'subplots', '_panels_spec', '_panels_name', - '_panel_lift', '_panel_animation')} + '_panel_lift', '_panel_animation', + '_panel_shared', '_hue_limits', + '_grid_furniture')} _panel_call.update(kwargs) return _plot_panels(x, _panels_spec, _panel_call, _name=_panels_name) @@ -12071,7 +12829,7 @@ def _compute_forecasts(datasets): colorbar_info = _build_colorbar_info( colorbar, hue, multicolor_hue, cluster, n_clusters, xform, mpl_kwargs, legend, palette, hue_group_labels=hue_group_labels, - hierarchy_labels=_mi_colorbar_labels) + hierarchy_labels=_mi_colorbar_labels, limits=_hue_limits) # GH #285: the same mapping, always resolved (never raising) and never # gated on colorbar=, for `return_model=True`'s bundle['colors'] and @@ -12082,7 +12840,7 @@ def _compute_forecasts(datasets): hue, multicolor_hue, cluster, n_clusters, xform, mpl_kwargs, legend, palette, hue_group_labels=hue_group_labels, hierarchy_labels=_mi_colorbar_labels, - legend_entries=_final_legend_entries) + legend_entries=_final_legend_entries, limits=_hue_limits) # ...which, for datasets colored from the palette CYCLE (no color=, # hue=, cluster=, palette mapping), reads the palette's fresh sampling; # the colors actually drawn differ when a composed `ax=` continues the @@ -12228,7 +12986,7 @@ def _finite_before(trace_index): if multicolor_hue is not None: line_colors = _multicolor_line_colors( multicolor_hue, pre_interp_lengths, xform, palette, - is_rgb=multicolor_hue_is_rgb) + is_rgb=multicolor_hue_is_rgb, limits=_hue_limits) # handle explore flag (a real ValueError, not an assert -- asserts are # stripped under `python -O`, F01-016/F10-013) @@ -13101,6 +13859,10 @@ def _plotly_before_show(drawn): if _legend_order: _rank_plotly_legend(drawn, _n_traces_before, _legend_order) + if colorbar_info is not None and _grid_furniture: + # a `panels=` grid draws ONE colorbar for the figure + _panel_shared['colorbars'].append( + dict(colorbar_info, font=_artist_font)) fig = plotly_draw( xform, into=_plotly_into, @@ -13148,7 +13910,7 @@ def _plotly_before_show(drawn): # backends read one table instead of two transcriptions of it forecast_schedule=forecast_schedule, forecast_trail=_n_forecast_trail, - colorbar_info=colorbar_info, + colorbar_info=(None if _grid_furniture else colorbar_info), surface=surface_list, surface_colors=surface_colors, surface_point_colors=surface_point_colors, @@ -13841,7 +14603,7 @@ def _fill(art, pts): palette, is_rgb=multicolor_hue_is_rgb, # the line colors above already warned about # any non-finite hue observation - warn_non_finite=False) + warn_non_finite=False, limits=_hue_limits) _apply_multicolor_markers(ax, raw_xform, _marker_colors, kwargs_list, fmt=fmt) else: @@ -14001,7 +14763,11 @@ def _hyp_frame_with_hooks(num, *fargs, # via matplotlib's own `make_axes` machinery, which can discard # an EARLIER legend fit; fitting the legend last, against # whatever the current layout actually is, sidesteps that. - if colorbar_info is not None and ax is not None: + if colorbar_info is not None and _grid_furniture: + # a `panels=` grid draws ONE colorbar for the figure + _panel_shared['colorbars'].append( + dict(colorbar_info, font=_artist_font)) + elif colorbar_info is not None and ax is not None: _add_colorbar(fig, ax, colorbar_info, font=_artist_font, attached=_user_supplied_ax) @@ -14023,7 +14789,10 @@ def _hyp_frame_with_hooks(num, *fargs, # `fig.tight_layout()` (measured: the last panel's legend ends # up clipped) (GH #291). if ((legend is not None or _final_legend_entries is not None) - and ax is not None and not _caller_figure): + and ax is not None and not _caller_figure + # (a `panels=` grid moves this legend's entries into + # the figure's one shared legend and fits that) + and not _grid_furniture): _fit_right_legend(fig, ax) # ...but what hypertools added to the caller's axes (the legend # hanging off its right edge, the title above it) must still end @@ -14414,7 +15183,8 @@ def _update_caption(ctx, _fn=_dynamic_caption, def _build_colorbar_info(colorbar, hue, multicolor_hue, cluster, n_clusters, xform, mpl_kwargs, legend, palette, - hue_group_labels=None, hierarchy_labels=None): + hue_group_labels=None, hierarchy_labels=None, + limits=None): """Resolve `colorbar=` into a backend-agnostic color-mapping dict, or None if no colorbar was requested (GH #100). @@ -14457,10 +15227,14 @@ def _build_colorbar_info(colorbar, hue, multicolor_hue, cluster, n_clusters, raise ValueError( "hue= has no finite values (every entry is NaN/inf), so " "there is no value range to put on a colorbar.") + # `limits`: the value range of a whole `panels=` grid, which every + # panel maps its own values over (see `_multicolor_line_colors`) + _vmin, _vmax = ((float(np.min(finite)), float(np.max(finite))) + if limits is None else limits) return { 'kind': 'continuous', - 'vmin': float(np.min(finite)), - 'vmax': float(np.max(finite)), + 'vmin': float(_vmin), + 'vmax': float(_vmax), 'palette': palette, 'label': label, 'ticks': ticks, @@ -14562,7 +15336,8 @@ def _build_colorbar_info(colorbar, hue, multicolor_hue, cluster, n_clusters, def _build_colors_info(hue, multicolor_hue, cluster, n_clusters, xform, mpl_kwargs, legend, palette, hue_group_labels=None, - hierarchy_labels=None, legend_entries=None): + hierarchy_labels=None, legend_entries=None, + limits=None): """The RESOLVED color scale this figure draws with (GH #285). `_build_colorbar_info` already computes exactly this mapping, but only @@ -14593,7 +15368,7 @@ def _build_colors_info(hue, multicolor_hue, cluster, n_clusters, xform, info = _build_colorbar_info( {}, hue, multicolor_hue, cluster, n_clusters, xform, mpl_kwargs, legend, palette, hue_group_labels=hue_group_labels, - hierarchy_labels=hierarchy_labels) + hierarchy_labels=hierarchy_labels, limits=limits) except ValueError: info = None @@ -14608,8 +15383,23 @@ def _build_colors_info(hue, multicolor_hue, cluster, n_clusters, xform, 'colors': None, 'labels': None, 'categories': {str(label): tuple(to_rgb(color)) for label, color in (legend_entries or [])}} - # no grouping at all: one dataset, one color + # no grouping at all: one dataset, one color -- the explicit + # `color=` it was drawn in when there is one (the palette's first + # color was reported for ``color='k'``, and for a `panels=` cell, + # which is handed its dataset's color this way) colors = np.asarray(dataset_colors(palette, max(len(xform), 1))) + _explicit = mpl_kwargs.get('color') + if _explicit is not None: + from matplotlib.colors import to_rgba_array + try: + _drawn = to_rgba_array( + [_explicit] if (isinstance(_explicit, str) + or _is_single_color(_explicit)) + else list(_explicit))[:, :3] + except (TypeError, ValueError): + _drawn = None + if _drawn is not None and len(_drawn) == len(colors): + colors = _drawn return {'kind': 'discrete', 'palette': palette, 'cmap': ListedColormap(colors), 'norm': None, 'vmin': None, 'vmax': None, 'colors': colors, @@ -15637,7 +16427,7 @@ def _contains_string(el): def _multicolor_line_colors(hue_src, orig_lengths, xform, palette, is_rgb=False, - warn_non_finite=True): + warn_non_finite=True, limits=None): """Per-point RGB colors for multicolored lines. Non-finite hue values are drawn gray (`colors.mat2colors`); one @@ -15649,7 +16439,10 @@ def _multicolor_line_colors(hue_src, orig_lengths, xform, palette, is_rgb=False, trajectories in xform have since been interpolated to a higher temporal resolution, so each dataset's hue values are linearly re-interpolated to its new length before color mapping. Colors are mapped over the - CONCATENATED hue values so the scale is shared across datasets. + CONCATENATED hue values so the scale is shared across datasets -- and, + with `limits` (``(vmin, vmax)``, a 1-D hue only), over that range + instead of the values' own: a `panels=` grid passes the range of every + panel's values, so a color is the same value in every panel. When `is_rgb` is True, `hue_src` already holds literal per-point RGB values (e.g. a matrix hue reduced to 3 columns via `plot`'s `color_reduce=`), so @@ -15691,9 +16484,17 @@ def _multicolor_line_colors(hue_src, orig_lengths, xform, palette, is_rgb=False, warnings.filterwarnings( 'ignore', message=r'\d+ observation\(s\) have non-finite', category=UserWarning) - colors = mat2colors( - stacked.ravel() if stacked.shape[1] == 1 else stacked, - palette=palette) + if limits is not None and stacked.shape[1] == 1: + # `mat2colors` maps over the finite values' own range: + # two extra values pin that range to `limits` + colors = mat2colors( + np.concatenate([stacked.ravel(), + np.asarray(limits, dtype=np.float64)]), + palette=palette)[:-2] + else: + colors = mat2colors( + stacked.ravel() if stacked.shape[1] == 1 else stacked, + palette=palette) if warn_non_finite: _n_bad = int(np.count_nonzero(~np.isfinite(hue_src).all(axis=1))) if _n_bad: diff --git a/hypertools/plot/plotly_backend.py b/hypertools/plot/plotly_backend.py index 421fdd624..4faec5e48 100644 --- a/hypertools/plot/plotly_backend.py +++ b/hypertools/plot/plotly_backend.py @@ -3159,7 +3159,8 @@ def __repr__(self): def make_panel_grid(nrows, ncols, ndims, titles=None, size=None, - gutter_px=0, title_px=None, **make_subplots_kw): + gutter_px=0, title_px=None, strip_px=0, + **make_subplots_kw): """The empty plotly grid `panels=` and `hyp.subplots(backend='plotly')` fill: a `plotly.subplots.make_subplots` figure with ``'scene'`` cells for 3-D and ``'xy'`` cells otherwise, sized like the matplotlib grid @@ -3167,7 +3168,9 @@ def make_panel_grid(nrows, ncols, ndims, titles=None, size=None, reserved to the right of EVERY cell (and in the right margin) for a per-panel legend/colorbar (see `panel_gutter_px`). When `size` is not given the figure is widened by the gutters, so the default grid stays - as roomy as it is without them. + as roomy as it is without them. `strip_px` reserves ONE strip right of + the whole grid instead (a `panels=` grid's shared legend/colorbar, see + `place_shared_furniture`), widening the default figure the same way. The cells are laid out the way matplotlib's `tight_layout` lays out the matplotlib grid (1.1 release review: the plotly grid used @@ -3190,8 +3193,10 @@ def make_panel_grid(nrows, ncols, ndims, titles=None, size=None, if size is not None: width, height = int(size[0] * 100), int(size[1] * 100) else: - width = int(DEFAULT_FIGSIZE[0] * 100) + gutter_px * ncols + width = int(DEFAULT_FIGSIZE[0] * 100) + gutter_px * ncols + strip_px height = int(DEFAULT_FIGSIZE[1] * 100) + # the strip is taken off the right; the grid is laid out in the rest + full_width, width = width, max(width - int(strip_px), 1) titles = list(titles) if titles is not None else [] if title_px is None: title_px = PANEL_TITLE_PX if any(t for t in titles) else 0 @@ -3212,7 +3217,7 @@ def make_panel_grid(nrows, ncols, ndims, titles=None, size=None, side = max((width - plot_w - gutter_px) / 2, 0.0) vert = max((height - plot_h - title_px) / 2, 0.0) margin = dict(l=int(round(side)), t=int(round(vert)) + title_px) - margin['r'] = max(int(width - plot_w - margin['l']), 0) + margin['r'] = max(int(full_width - plot_w - margin['l']), 0) margin['b'] = max(int(height - plot_h - margin['t']), 0) make_kw = {} if ncols > 1: @@ -3229,11 +3234,143 @@ def make_panel_grid(nrows, ncols, ndims, titles=None, size=None, fig = make_subplots(rows=nrows, cols=ncols, specs=[[dict(cell) for _ in range(ncols)] for _ in range(nrows)], **make_kw) - fig.update_layout(width=width, height=height, margin=margin, + fig.update_layout(width=full_width, height=height, margin=margin, paper_bgcolor='white', plot_bgcolor='white') return fig +class PanelFurnitureConflict(Exception): + """One legend label looks different in two panels of a `panels=` + grid, so a single shared entry would be wrong for one of them.""" + + +def _legend_trace_look(trace, color=True): + """What a legend-listed trace's key LOOKS like, as a comparable + value: mode, dash, width, marker symbol and (with `color`) its line + and marker colors.""" + line = trace.line.to_plotly_json() if trace.line is not None else {} + marker = (trace.marker.to_plotly_json() + if getattr(trace, 'marker', None) is not None else {}) + mode = trace.mode or 'lines' + look = [type(trace).__name__, mode, line.get('dash'), + marker.get('symbol') if 'markers' in mode else None] + if color: + def _plain(value): + return value if (value is None or isinstance(value, str)) \ + else repr(np.asarray(value).tolist()) + look += [_plain(line.get('color')) if 'lines' in mode else None, + _plain(marker.get('color')) if 'markers' in mode else None, + trace.opacity] + return repr(look) + + +def merge_panel_legends(panels): + """Make the drawn panel figures `panels` list every legend entry + ONCE between them -- the plotly twin of + `hypertools.plot.plot._merge_panel_legends`, under the same rule: two + entries with the same name and the same look are one (the later + traces keep their name but leave the legend); a forecast/truth key + (``meta['hyp_legend_entry']``) that differs between panels only in + color becomes one key in the neutral `FORECAST_LEGEND_COLOR`; any + other name that looks different in two panels raises + `PanelFurnitureConflict`. Same-named traces share a ``legendgroup``, + so clicking the one entry toggles them in every panel, and the + forecast/truth keys are ranked after the data entries. Returns whether + any entry is listed.""" + from .forecast import FORECAST_LEGEND_COLOR + kept = {} + for panel in panels: + for trace in panel.data: + if not trace.showlegend: + continue + name = str(trace.name) + overlay = bool((trace.meta or {}).get('hyp_legend_entry')) \ + if isinstance(trace.meta, dict) else False + look = _legend_trace_look(trace) + shape = _legend_trace_look(trace, color=False) + if trace.legendgroup is None: + trace.legendgroup = f'hyp-shared-{name}' + if overlay and trace.legendrank is None: + trace.legendrank = 2000 + same = kept.setdefault(name, []) + match = [e for e in same if e['look'] == look] + if match: + trace.showlegend = False + trace.legendgroup = match[0]['trace'].legendgroup + continue + neutral = [e for e in same if overlay and e['overlay'] + and e['shape'] == shape] + if neutral: + first = neutral[0]['trace'] + alpha = _color_alpha(first.line.color) + first.line.color = _to_plotly_color(FORECAST_LEGEND_COLOR, + alpha) + if first.marker is not None and first.marker.color is not None: + first.marker.color = first.line.color + trace.showlegend = False + trace.legendgroup = first.legendgroup + continue + if same: + raise PanelFurnitureConflict(name) + same.append({'look': look, 'shape': shape, 'overlay': overlay, + 'trace': trace}) + return bool(kept) + + +def _color_alpha(color): + """The alpha of a plotly ``rgba(...)`` color string (1.0 for any + other form).""" + if isinstance(color, str) and color.strip().lower().startswith('rgba'): + try: + return float(color.strip()[5:-1].split(',')[3]) + except (IndexError, ValueError): + return 1.0 + return 1.0 + + +def place_shared_furniture(target, legend, colorbar_trace, ndims, + legend_position=None, font=None): + """Give a filled `panels=` grid ONE legend and/or ONE colorbar, in + the strip `make_panel_grid` reserved right of the whole grid + (`strip_px`). With `legend`, every trace is attached to the figure's + single ``layout.legend`` (the per-cell ``legendN`` that + `transplant_panel` gave each panel is dropped), which is placed just + right of the last column, vertically centered -- or at + `legend_position` (``{'x', 'y'}``, paper fractions), a caller's own + `legend_kwargs` placement. `colorbar_trace` (`_colorbar_trace`'s + phantom trace, carrying the merged colorbar) is added to the first + cell and, when vertical on the right, placed right of the legend; + `font` is the panels' inherited text font.""" + plot_w = max((target.layout.width or int(DEFAULT_FIGSIZE[0] * 100)) + - (target.layout.margin.l or 0) + - (target.layout.margin.r or 0), 1) + if legend: + style = target.layout.legend.to_plotly_json() + for trace in target.data: + trace.legend = 'legend' + for key in [k for k in target.layout.to_plotly_json() + if k.startswith('legend') and k != 'legend']: + target.layout[key] = None + if legend_position is not None: + style.update(x=legend_position['x'], y=legend_position['y']) + else: + style.update(x=1.0 + PANEL_GUTTER_PAD_PX / plot_w, y=0.5, + xanchor='left', yanchor='middle') + target.layout.legend = style + if colorbar_trace is not None: + cb = colorbar_trace.marker.colorbar + if cb.orientation in (None, 'v') and cb.xanchor != 'right': + offset = PANEL_GUTTER_PAD_PX + (PANEL_LEGEND_PX if legend else 0) + cb.update(x=1.0 + offset / plot_w, xanchor='left', y=0.5, + yanchor='middle') + if font: + cb.tickfont = _with_base_font(cb.tickfont.to_plotly_json(), font) + if cb.title is not None and cb.title.text: + cb.title.font = _with_base_font( + cb.title.font.to_plotly_json(), font) + target.add_trace(colorbar_trace, row=1, col=1) + + def _grid_spec(target): """The `make_panel_grid` arguments a `hyp.subplots(backend='plotly')` grid was built with (kept in ``layout.meta['hyp_grid']``), or None diff --git a/tests/test_panels_shared_legend_colors.py b/tests/test_panels_shared_legend_colors.py new file mode 100644 index 000000000..c4a1e6352 --- /dev/null +++ b/tests/test_panels_shared_legend_colors.py @@ -0,0 +1,487 @@ +"""`panels=` grids: color means one thing across the whole figure, and the +legend and colorbar are drawn once for the figure (owner decision +2026-11-22, for 1.2.0). + +Every test draws a real grid and reads the real artists (or plotly traces) +back; the layout tests measure window extents after a real draw. +""" +import warnings + +import matplotlib +import matplotlib.pyplot as plt +import numpy as np +import pytest +from matplotlib.colors import to_rgb, to_rgba + +import hypertools as hyp +from hypertools.plot.plot import (CAPTION_GID, SHARED_COLORBAR_GID, + SHARED_LEGEND_GID) + + +@pytest.fixture(autouse=True) +def _close_figures(): + yield + plt.close('all') + + +def _walks(n=4, rows=30, cols=5, seed=0): + rng = np.random.default_rng(seed) + return [rng.normal(size=(rows, cols)).cumsum(axis=0) for _ in range(n)] + + +def _quiet_plot(*args, **kwargs): + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + return hyp.plot(*args, show=False, **kwargs) + + +def _shared_legend(fig): + found = [lg for lg in fig.legends if lg.get_gid() == SHARED_LEGEND_GID] + assert len(found) <= 1 + return found[0] if found else None + + +def _shared_colorbars(fig): + return [a for a in fig.axes if a.get_gid() == SHARED_COLORBAR_GID] + + +def _entries(legend): + """``[(label, rgb)]`` of a legend's entries, rounded for comparison.""" + out = [] + for handle, text in zip(legend.legend_handles, legend.get_texts()): + color = (handle.get_color() if hasattr(handle, 'get_color') + else handle.get_facecolor()) + color = np.asarray(color, dtype=object) + rgb = (to_rgb(color.tolist()) if color.ndim <= 1 + else to_rgb(np.asarray(color[0], dtype=float))) + out.append((text.get_text(), tuple(np.round(rgb, 4)))) + return out + + +def _line_colors(ax): + return [tuple(np.round(to_rgb(line.get_color()), 4)) for line in ax.lines] + + +def _assert_strip_clear(fig, panel_axes): + """The shared legend/colorbar overlap no panel, title or caption and lie + inside the canvas (window extents after a real draw).""" + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + canvas = fig.bbox + strip = [] + legend = _shared_legend(fig) + if legend is not None: + strip.append(legend.get_window_extent(renderer)) + for cax in _shared_colorbars(fig): + strip.append(cax.get_tightbbox(renderer)) + assert strip, "no shared legend or colorbar to measure" + others = [] + for ax in panel_axes: + others.append(ax.get_window_extent(renderer)) + if ax.get_title(): + title = ax.title.get_window_extent(renderer) + # the grid is laid out exactly as it is without the strip, so + # every title stays on the canvas + assert title.y1 <= canvas.y1 + 0.5 and title.x0 >= canvas.x0 + others.append(title) + others += [t.get_window_extent(renderer) for t in fig.texts + if t.get_gid() == CAPTION_GID] + for box in strip: + assert box.x0 >= canvas.x0 - 0.5 and box.x1 <= canvas.x1 + 0.5, box + assert box.y0 >= canvas.y0 - 0.5 and box.y1 <= canvas.y1 + 0.5, box + for other in others: + assert not box.overlaps(other), (box, other) + for a, b in zip(strip, strip[1:]): + assert not a.overlaps(b) + return strip + + +# -- per-dataset colors ------------------------------------------------------ + +@pytest.mark.parametrize('panel_fit', ['shared', 'independent']) +@pytest.mark.parametrize('ndims', [2, 3]) +def test_each_dataset_keeps_its_single_axes_color(panel_fit, ndims): + x = _walks() + single = _quiet_plot(x, ndims=ndims, return_model=True) + expected = _line_colors(single['fig'].axes[0]) + assert len(set(expected)) == 4 + grid = _quiet_plot(x, ndims=ndims, panels=True, panel_fit=panel_fit, + return_model=True) + drawn = [_line_colors(ax)[0] for ax in grid['axes']] + assert drawn == expected + # the bundle reports what was drawn: each panel its own color, the grid + # every dataset's + for model, color in zip(grid['panel_models'], expected): + assert np.allclose(model['colors']['colors'], [color], atol=1e-3) + assert np.allclose(grid['colors']['colors'], expected, atol=1e-3) + + +def test_explicit_colors_and_fmt_letters_are_honored_as_on_one_axes(): + x = _walks(3) + for kw in (dict(fmt=['r-', '-', 'b--']), + dict(color=['k', 'orange', 'purple']), + dict(palette='viridis'), + dict(palette=['#111111', '#22aa22', '#3333ff'])): + single = _quiet_plot(x, ndims=2, **kw) + expected = _line_colors(single.axes[0]) + grid = _quiet_plot(x, ndims=2, panels=True, return_model=True, **kw) + assert [_line_colors(ax)[0] for ax in grid['axes']] == expected, kw + + +# -- one legend --------------------------------------------------------------- + +def test_one_legend_for_the_figure_with_every_dataset(): + x = _walks() + names = ['a', 'b', 'c', 'd'] + single = _quiet_plot(x, legend=names) + expected = _entries(single.axes[0].get_legend()) + grid = _quiet_plot(x, legend=names, panels=True, return_model=True) + fig = grid['fig'] + assert all(ax.get_legend() is None for ax in grid['axes']) + legend = _shared_legend(fig) + assert legend is not None + assert _entries(legend) == expected + assert [label for label, _ in _entries(legend)] == names + + +def test_legend_false_or_absent_adds_nothing(): + x = _walks() + for kw in ({}, dict(legend=False), dict(legend=None)): + fig = _quiet_plot(x, panels=True, **kw) + assert fig.legends == [] + assert all(ax.get_legend() is None for ax in fig.axes) + assert _shared_colorbars(fig) == [] + assert len(fig.axes) == 4 + + +def test_single_panel_grid_has_one_shared_legend(): + x = _walks(2) + grid = _quiet_plot(x, reduce=['PCA'], panels=True, legend=['a', 'b'], + return_model=True) + assert len(grid['axes']) == 1 + legend = _shared_legend(grid['fig']) + assert [label for label, _ in _entries(legend)] == ['a', 'b'] + assert grid['axes'][0].get_legend() is None + _assert_strip_clear(grid['fig'], grid['axes']) + + +def test_reducer_list_grid_has_one_legend(): + x = _walks() + names = ['a', 'b', 'c', 'd'] + grid = _quiet_plot(x, reduce=['PCA', 'IncrementalPCA', 'FastICA'], + panels=True, legend=names, return_model=True) + legend = _shared_legend(grid['fig']) + assert [label for label, _ in _entries(legend)] == names + assert all(ax.get_legend() is None for ax in grid['axes']) + # every panel draws every dataset in the legend's colors + colors = [color for _, color in _entries(legend)] + for ax in grid['axes']: + assert _line_colors(ax)[:4] == colors + _assert_strip_clear(grid['fig'], grid['axes']) + + +def test_forecast_and_truth_entries_are_listed_once(): + x = _walks(3, rows=40, cols=2) + rng = np.random.default_rng(1) + truth = [xi[-1] + rng.normal(size=(5, 2)).cumsum(axis=0) for xi in x] + kw = dict(predict='ARIMA', t=5, truth=truth, legend=['a', 'b', 'c'], + ndims=2) + single = _quiet_plot(x, **kw) + expected = _entries(single.axes[0].get_legend()) + grid = _quiet_plot(x, panels=True, return_model=True, **kw) + legend = _shared_legend(grid['fig']) + assert all(ax.get_legend() is None for ax in grid['axes']) + labels = [label for label, _ in _entries(legend)] + assert labels == ['a', 'b', 'c', 'ARIMA', 'truth'] + # the forecast/truth keys stand for every dataset's, so they wear the + # neutral glyph the single-axes legend gives them + assert _entries(legend) == expected + + +# -- continuous hue: one norm, one colorbar ---------------------------------- + +@pytest.mark.parametrize('panel_fit', ['shared', 'independent']) +def test_continuous_hue_shares_one_norm_and_one_colorbar(panel_fit): + x = _walks(3, rows=21) + # panel k's values run k..k+2, so 2.0 is the last point of panel 0, the + # middle of panel 1 and the first of panel 2 + hue = [np.linspace(k, k + 2, 21) for k in range(3)] + grid = _quiet_plot(x, hue=hue, colorbar=True, panels=True, fmt='o', + ndims=2, panel_fit=panel_fit, return_model=True) + fig = grid['fig'] + bars = _shared_colorbars(fig) + assert len(bars) == 1 + assert len(fig.axes) == 3 + 1 # no per-panel colorbar axes + for model in grid['panel_models']: + assert model['colors']['vmin'] == pytest.approx(0.0) + assert model['colors']['vmax'] == pytest.approx(4.0) + assert grid['colors']['vmin'] == pytest.approx(0.0) + assert grid['colors']['vmax'] == pytest.approx(4.0) + + def _point_colors(ax): + return np.vstack([c.get_facecolors() for c in ax.collections + if len(c.get_facecolors()) > 1]) + + c0, c1, c2 = (_point_colors(ax) for ax in grid['axes']) + assert np.allclose(c0[-1], c1[10], atol=1e-6) + assert np.allclose(c1[10], c2[0], atol=1e-6) + # ...and it is the color the single-axes call gives that value + single = _quiet_plot(x, hue=hue, fmt='o', ndims=2, return_model=True) + cmap, norm = single['colors']['cmap'], single['colors']['norm'] + assert (norm.vmin, norm.vmax) == (0.0, 4.0) + assert np.allclose(c0[-1][:3], cmap(norm(2.0))[:3], atol=0.02) + # different values are different colors + assert not np.allclose(c0[0], c2[-1], atol=0.05) + _assert_strip_clear(fig, grid['axes']) + + +# -- categorical hue ---------------------------------------------------------- + +@pytest.mark.parametrize('panel_fit', ['shared', 'independent']) +def test_categorical_hue_mapping_is_shared(panel_fit): + x = _walks(4) + hue = [['p'] * 15 + ['q'] * 15, ['q'] * 30, + ['r'] * 10 + ['p'] * 20, ['q'] * 30] + single = _quiet_plot(x, hue=hue, fmt='o', legend=True, return_model=True) + expected = {k: tuple(np.round(v, 4)) + for k, v in single['colors']['categories'].items()} + assert list(expected) == ['p', 'q', 'r'] + grid = _quiet_plot(x, hue=hue, fmt='o', legend=True, panels=True, + panel_fit=panel_fit, return_model=True) + for model in grid['panel_models']: + for label, color in model['colors']['categories'].items(): + assert tuple(np.round(color, 4)) == expected[label] + legend = _shared_legend(grid['fig']) + assert _entries(legend) == list(expected.items()) + assert all(ax.get_legend() is None for ax in grid['axes']) + assert {k: tuple(np.round(v, 4)) for k, v + in grid['colors']['categories'].items()} == expected + + +def test_categorical_hue_colorbar_is_one_bar_with_every_category(): + x = _walks(3) + hue = [['p'] * 30, ['q'] * 30, ['r'] * 15 + ['p'] * 15] + grid = _quiet_plot(x, hue=hue, fmt='o', colorbar=True, panels=True, + return_model=True) + bars = _shared_colorbars(grid['fig']) + assert len(bars) == 1 + assert len(grid['fig'].axes) == 4 + assert [t.get_text() for t in bars[0].get_yticklabels()] == ['p', 'q', + 'r'] + _assert_strip_clear(grid['fig'], grid['axes']) + + +# -- clusters ----------------------------------------------------------------- + +def test_shared_fit_clusters_have_one_legend(): + x = _walks(3) + grid = _quiet_plot(x, n_clusters=3, fmt='o', legend=True, panels=True, + random_state=0, return_model=True) + legend = _shared_legend(grid['fig']) + assert legend is not None + assert all(ax.get_legend() is None for ax in grid['axes']) + labels = [label for label, _ in _entries(legend)] + assert len(labels) == len(set(labels)) == 3 + + +def test_independently_fit_clusters_keep_per_panel_legends(): + """The exception: clusters fit per panel are different clusters in every + panel, so one shared legend would claim a meaning that is false.""" + x = _walks(3) + grid = _quiet_plot(x, n_clusters=2, fmt='o', legend=True, colorbar=True, + panels=True, panel_fit='independent', random_state=0, + return_model=True) + fig = grid['fig'] + assert _shared_legend(fig) is None and fig.legends == [] + assert _shared_colorbars(fig) == [] + assert all(ax.get_legend() is not None for ax in grid['axes']) + assert len(fig.axes) == 3 + 3 # one colorbar per panel + # a reducer list clusters each panel's own embedding: also per panel + grid = _quiet_plot(x, n_clusters=2, fmt='o', legend=True, panels=True, + reduce=['PCA', 'FastICA'], random_state=0, + return_model=True) + assert _shared_legend(grid['fig']) is None + assert all(ax.get_legend() is not None for ax in grid['axes']) + + +# -- layout ------------------------------------------------------------------- + +@pytest.mark.parametrize('ndims', [2, 3]) +@pytest.mark.parametrize('size', [None, (9, 4)]) +def test_shared_legend_colorbar_caption_and_titles_do_not_overlap(ndims, + size): + x = _walks(3) + hue = [['alpha'] * 30, ['beta'] * 30, ['gamma'] * 15 + ['alpha'] * 15] + grid = _quiet_plot( + x, hue=hue, fmt='o', legend=True, colorbar=True, panels=(1, 3), + ndims=ndims, size=size, title=['one', 'two', 'three'], + caption='a caption under the whole grid', return_model=True) + fig = grid['fig'] + assert _shared_legend(fig) is not None + assert len(_shared_colorbars(fig)) == 1 + strip = _assert_strip_clear(fig, grid['axes']) + # right of every panel, and vertically centered on the grid + renderer = fig.canvas.get_renderer() + boxes = [ax.get_window_extent(renderer) for ax in grid['axes']] + right = max(b.x1 for b in boxes) + middle = 0.5 * (min(b.y0 for b in boxes) + max(b.y1 for b in boxes)) + for box in strip: + assert box.x0 >= right + assert abs(0.5 * (box.y0 + box.y1) - middle) <= 0.12 * fig.bbox.height + if size is not None: + assert tuple(fig.get_size_inches()[:1]) == (9.0,) + + +def test_default_figure_reserves_one_strip_not_one_per_column(): + x = _walks(4) + plain = _quiet_plot(x, panels=(1, 4), ndims=2) + with_legend = _quiet_plot(x, panels=(1, 4), ndims=2, + legend=['a', 'b', 'c', 'd']) + extra = with_legend.get_size_inches()[0] - plain.get_size_inches()[0] + assert 0.3 < extra < 2.0 # was 1.1 in per column (4.4 in) + assert with_legend.get_size_inches()[1] == plain.get_size_inches()[1] + _assert_strip_clear(with_legend, with_legend.axes[:4]) + + +def test_2x2_grid_legend_is_clear(): + x = _walks(4) + grid = _quiet_plot(x, panels=(2, 2), ndims=2, + legend=['first', 'second', 'third', 'fourth'], + title=['a', 'b', 'c', 'd'], return_model=True) + _assert_strip_clear(grid['fig'], grid['axes']) + + +# -- animated grids ----------------------------------------------------------- + +def test_animated_grid_shared_legend_is_static_and_clear_of_the_cubes(): + x = _walks(4, rows=40) + names = ['a', 'b', 'c', 'd'] + single = _quiet_plot(x, legend=names) + expected = _entries(single.axes[0].get_legend()) + grid = _quiet_plot(x, panels=(1, 4), animate=True, legend=names, + duration=2, frame_rate=10, rotations=1, + caption='caption', return_model=True) + fig, anim = grid['fig'], grid['animation'] + legend = _shared_legend(fig) + assert legend is not None + assert _entries(legend) == expected + assert [_line_colors(ax)[0] for ax in grid['axes']] == [ + color for _, color in expected] + n_frames = int(anim._save_count) + assert n_frames == 20 + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + box0 = legend.get_window_extent(renderer) + for frame in range(n_frames): + anim._func(frame) + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + assert _shared_legend(fig) is legend + assert legend.get_visible() + box = legend.get_window_extent(renderer) + assert np.allclose(box.extents, box0.extents, atol=0.5) + assert all(ax.get_legend() is None for ax in grid['axes']) + for ax in grid['axes']: + # everything the cube draws (its panes, lines and data) + for artist in (list(ax.lines) + list(ax.collections) + + [ax.xaxis.pane, ax.yaxis.pane, ax.zaxis.pane]): + if not artist.get_visible(): + continue + extent = artist.get_window_extent(renderer) + if not np.all(np.isfinite(extent.extents)): + continue + assert extent.x1 <= box.x0, (frame, artist) + _assert_strip_clear(fig, grid['axes']) + + +def test_animated_grid_colorbar_is_shared(): + x = _walks(3, rows=30) + hue = [np.linspace(k, k + 2, 30) for k in range(3)] + grid = _quiet_plot(x, hue=hue, colorbar=True, panels=(1, 3), + animate=True, duration=1, frame_rate=5, + return_model=True) + fig = grid['fig'] + assert len(_shared_colorbars(fig)) == 1 + assert len(fig.axes) == 4 + assert grid['colors']['vmin'] == pytest.approx(0.0) + assert grid['colors']['vmax'] == pytest.approx(4.0) + _assert_strip_clear(fig, grid['axes']) + + +# -- plotly ------------------------------------------------------------------- + +def _plotly_legend_names(fig): + return [t.name for t in fig.data if t.showlegend] + + +def _plotly_rgb(color): + import re + if color.startswith('#'): + return tuple(np.round(to_rgb(color), 2)) + nums = [float(v) for v in re.findall(r'[\d.]+', color)[:3]] + return tuple(np.round(np.asarray(nums) / 255.0, 2)) + + +def test_plotly_grid_shows_each_legend_entry_once_in_dataset_colors(): + x = _walks() + names = ['a', 'b', 'c', 'd'] + single = _quiet_plot(x, legend=names, return_model=True) + expected = [tuple(np.round(c, 2)) for c in single['colors']['colors']] + fig = _quiet_plot(x, legend=names, panels=True, backend='plotly') + assert _plotly_legend_names(fig) == names + shown = [t for t in fig.data if t.showlegend] + assert [_plotly_rgb(t.line.color) for t in shown] == expected + # one legend for the figure, right of the grid + assert {t.legend for t in shown} <= {None, 'legend'} + assert fig.layout.legend.x >= 1.0 + assert fig.layout.showlegend is True + + +def test_plotly_grid_has_one_colorbar_and_a_shared_color_range(): + x = _walks(3, rows=21) + hue = [np.linspace(k, k + 2, 21) for k in range(3)] + grid = _quiet_plot(x, hue=hue, colorbar=True, panels=True, fmt='o', + ndims=2, backend='plotly', return_model=True) + fig = grid['fig'] + scales = [t for t in fig.data + if getattr(getattr(t, 'marker', None), 'showscale', None)] + assert len(scales) == 1 + assert (scales[0].marker.cmin, scales[0].marker.cmax) == (0.0, 4.0) + assert scales[0].marker.colorbar.x >= 1.0 + for model in grid['panel_models']: + assert (model['colors']['vmin'], model['colors']['vmax']) == (0.0, + 4.0) + # hue value 2.0 is one color in all three panels + points = [t for t in fig.data if t.mode == 'markers' + and t.marker.color is not None and len(t.x) == 21] + assert len(points) == 3 + assert points[0].marker.color[-1] == points[1].marker.color[10] + assert points[1].marker.color[10] == points[2].marker.color[0] + + +def test_plotly_grid_categorical_hue_and_legend_false(): + x = _walks(3) + hue = [['p'] * 30, ['q'] * 30, ['r'] * 15 + ['p'] * 15] + single = _quiet_plot(x, hue=hue, fmt='o', legend=True, + return_model=True) + expected = {k: tuple(np.round(v, 2)) + for k, v in single['colors']['categories'].items()} + fig = _quiet_plot(x, hue=hue, fmt='o', legend=True, panels=True, + backend='plotly') + assert _plotly_legend_names(fig) == ['p', 'q', 'r'] + for trace in fig.data: + if trace.name in expected and trace.marker.color is not None \ + and isinstance(trace.marker.color, str): + assert _plotly_rgb(trace.marker.color) == expected[trace.name] + bare = _quiet_plot(x, panels=True, backend='plotly') + assert not any(t.showlegend for t in bare.data) + assert not bare.layout.showlegend + + +def test_plotly_independent_clusters_keep_per_panel_legends(): + x = _walks(3) + fig = _quiet_plot(x, n_clusters=2, fmt='o', legend=True, panels=True, + panel_fit='independent', random_state=0, + backend='plotly') + shown = [t for t in fig.data if t.showlegend] + assert len({t.legend for t in shown}) == 3 From 09f69af3f606b4e5f15a3186e543232a7a0face7 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 05:35:22 -0500 Subject: [PATCH 14/58] test+docs: shared panel colors, legend and colorbar (GH #295) Rewrites the tests that asserted per-panel legends, colorbars and first-palette-color panels (owner decision 2026-11-22 for 1.2.0), adds tests for legend=True numbering, palette dicts, colorbar sides, label conflicts and the plotly grid, places a plotly colorbar on any side of the whole grid, and documents the behavior (plot() docstring, docs/animation.rst, CHANGELOG, session notes). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- CHANGELOG.md | 48 ++++++++ docs/animation.rst | 12 +- hypertools/plot/plot.py | 98 ++++++++++++++-- hypertools/plot/plotly_backend.py | 47 +++++++- ...sion_2026-11-22_feat295-animated-panels.md | 38 ++++++ tests/test_animated_panels.py | 39 ++++--- tests/test_figure_review_gaps.py | 18 ++- tests/test_palette_compose_review.py | 31 +++-- tests/test_panels_shared_legend_colors.py | 110 ++++++++++++++++++ tests/test_plot_panels.py | 73 +++++++----- tests/test_plot_panels_audit.py | 13 ++- tests/test_plot_panels_fit.py | 27 ++++- tests/test_plot_review_round3.py | 42 ++++--- tests/test_plot_review_round9.py | 39 ++++++- tests/test_plotly_cells_review.py | 15 ++- tests/test_polars_inputs.py | 14 ++- 16 files changed, 557 insertions(+), 107 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 467aefb02..86e74739e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,6 +45,54 @@ draws into a figure the caller built, found by executing notebooks with drawn once. Matplotlib only: `backend='plotly'` raises `NotImplementedError`, and a caller-supplied `ax=` raises `ValueError`. +### Changed + +- **Panel grids share their colors, one legend and one colorbar.** In a + `panels=` (alias `subplots=`) grid, color now means one thing across the + whole figure, and what explains it is drawn once. This changes how + static grids look compared with 1.1.0, on both backends, and applies to + the new animated grids too. + - *Colors.* With one panel per dataset, each dataset is drawn in the + color the equivalent single-axes call of all the datasets gives it + (palette position i of n). In 1.1.0 every panel restarted the palette, + so every dataset was drawn in the same first color. An explicit + `color=`, a color letter in `fmt=` and a per-dataset `palette=` are + honored as before. A continuous `hue=` is mapped over one value range + (the range of every panel's values), so a color is the same value in + every panel; a categorical `hue=` uses one category-to-color mapping + (in 1.1.0 each panel mapped its own values and its own categories, so + the same color could mean different things in neighboring panels). + Clusters from a shared fit already used one mapping. + - *Legend and colorbar.* The grid draws one legend (the union of the + panels' entries, in dataset order, each once; `predict=`/`truth=` + entries are listed once too) and/or one colorbar, in a strip to the + right of the grid, vertically centered, clear of every panel, title + and `caption=`. In 1.1.0 every panel carried its own. The default + figure is widened by that one strip instead of 1.1 in per column; an + explicit `size=` is honored. `legend=True` numbers the datasets 1..n + (every panel used to say `1`). No legend or colorbar appears that the + call did not ask for. On the matplotlib figure they are a figure-level + legend (gid `'hypertools-shared-legend'`) and a colorbar axes (gid + `'hypertools-shared-colorbar'`); on plotly, `layout.legend` and one + colorbar trace. + - *Where panels keep their own.* Clusters fit separately per panel + (`cluster=`/`n_clusters=` with `panel_fit='independent'` or with a + list-valued `reduce=`), `forecast_cluster=`/`forecast_n_clusters=`, + and a legend label that would look different in two panels: there the + colors mean something different in every panel, so each panel keeps + its own legend and colorbar. + - *`return_model=True`.* The grid bundle's `'colors'` is the one scale + the panels share (every dataset's color in panel order, the grid-wide + range of a continuous `hue=`, or the union of the categories) instead + of the first panel's, and each `panel_models[i]['colors']` reports the + colors that panel drew. A single dataset drawn with an explicit + `color=` now reports that color in `'colors'` (it reported the + palette's first color). + - A `palette=` dict naming every category of a categorical `hue=` now + works in a one-panel-per-dataset grid whose panels each hold only some + of the categories (it raised "names a category this plot does not + have"). + ### Fixed - **`labels=` in a panel grid stay with their own panel.** The annotations' diff --git a/docs/animation.rst b/docs/animation.rst index eb8232711..a42d2e40b 100644 --- a/docs/animation.rst +++ b/docs/animation.rst @@ -717,8 +717,8 @@ figure, so one ``save_path=`` writes one video of all the panels: title=['A', 'B', 'C', 'D'], save_path='grid.mp4') Each panel is animated exactly as the single-axes call for its data is: -every ``animate=`` style and ``order=`` value, the trail flags, ``predict=``, -per-frame titles, legends and colorbars apply per panel. The ordering is per +every ``animate=`` style and ``order=`` value, the trail flags, ``predict=`` +and per-frame titles apply per panel. The ordering is per panel too, not a sequence across panels: ``order='serial'`` reveals the datasets *within* each panel one after another, and the panels never take turns. ``panel_fit=`` and a list-valued ``reduce=`` (one panel per reducer) @@ -738,6 +738,14 @@ A few things are specific to a grid: cube but not enlarge it past its cell. With ``xlabel=``/``ylabel=``/ ``zlabel=`` the figure is enlarged so the rotating axis labels fit too; an explicit ``size=`` too small for them raises, naming a size that fits. +* Colors, the legend and the colorbar belong to the whole grid, as in a + static grid: each dataset keeps the color the single-axes call of all the + datasets gives it, ``hue=`` is mapped through one scale, and one legend + and/or one colorbar is drawn in a strip right of the panels. They are + static across frames, and every rotating cube stays clear of the strip. + (Clusters fit per panel -- ``panel_fit='independent'`` or a list-valued + ``reduce=`` with ``cluster=``/``n_clusters=`` -- keep a legend per panel, + because their colors mean something different in each one.) * ``on_frame=`` is called once per frame for the whole figure. Its ``FrameContext`` has ``axes`` as a tuple of the panel axes, ``artists`` and ``datasets`` as every panel's in panel order, and ``panels`` as one diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index 4acb42d59..43d7ba66c 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -4669,6 +4669,8 @@ def _hue_label_strings(hue): out = [] def _walk(value): + """Collect the labels of `value`, a label or a (nested) + sequence of them, in first-appearance order.""" if isinstance(value, (str, bytes)) or np.ndim(value) == 0: if not is_missing_label(value) and str(value) not in out: out.append(str(value)) @@ -4720,6 +4722,7 @@ def _legend_handle_signature(handle, color=True): from matplotlib.colors import to_rgba_array def _plain(value): + """`value` as plain rounded numbers, or its repr.""" try: return np.round(np.asarray(value, dtype=float), 4).tolist() except (TypeError, ValueError): @@ -4999,6 +5002,7 @@ def _add_shared_furniture(fig, panel_axes, legend_spec, colorbar_info, in_strip = mappable is not None and colorbar_info['location'] == 'right' def _finish(cbar): + """Label, style and tag the shared colorbar `cbar`.""" if ticklabels is not None: cbar.set_ticklabels(ticklabels) if colorbar_info['label']: @@ -5009,6 +5013,8 @@ def _finish(cbar): # first group at the top, as the legend reads (`_add_colorbar`) cbar.ax.invert_yaxis() cbar.ax.set_gid(SHARED_COLORBAR_GID) + # matplotlib's own label for a colorbar's axes + cbar.ax.set_label('') strip['colorbar'] = cbar if in_strip: @@ -5348,7 +5354,8 @@ def _plot_panels(x, panels, call_kwargs, _name='panels'): kw = panel_kwargs[i] if own_colors[i] is not None: kw['color'] = [own_colors[i]] - if kw.get('legend') is True and ungrouped and panel_ndims != 1: + if (kw.get('legend') is True and ungrouped and panel_ndims != 1 + and kw.get('names') is None): # the single-axes call numbers its datasets 1..n; every # panel numbered its own dataset 1 kw['legend'] = [i + 1] @@ -6123,7 +6130,8 @@ def _draw_panels(consolidate): legend_position=(None if _position is None else {'x': _position['lx'], 'y': _position['ly']}), font=(panel_figs[0].layout.font.to_plotly_json() - if panel_figs[0].layout.font is not None else None)) + if panel_figs[0].layout.font is not None else None), + title_px=title_px, widen=call_kwargs.get('size') is None) fig.update_layout(showlegend=bool(call_kwargs.get('legend'))) # the SAME figure class the single-axes plotly path returns, displayed # through the same one-shot end-of-cell queue: a bare `go.Figure` shown @@ -6789,7 +6797,11 @@ def plot( the None-labeled points are drawn in the same de-emphasized neutral gray, get no legend entry, and do not consume a palette slot (the named categories keep the first palette colors, in - first-appearance order). + first-appearance order). In a `panels=` grid the mapping is the + whole figure's: a continuous hue is mapped over the range of + every panel's values and a categorical hue through one + category-to-color mapping, exactly as the single-axes call of + all the datasets maps them (see `panels=`). The categorical-vs-continuous choice: string labels always take the CATEGORICAL path (one trace per category, legend-able, @@ -6948,6 +6960,8 @@ def plot( item); the list must have exactly one entry per drawn dataset/ group (``ValueError`` naming legend otherwise). A bare string is treated as a single-entry list (valid only for a single dataset). + A `panels=` grid draws ONE legend for the whole figure, right of + the grid (see `panels=`). Under a MultiIndex HIERARCHY the drawn traces are leaves plus derived per-level means, and only the TOP-level groups carry a @@ -6999,9 +7013,9 @@ def plot( swatches). Mixing the two forms raises ``ValueError``. Under `panels=`, a plain list naming the datasets (one color per dataset, then one per shared entry such as a forecast model or - ``truth``) is split so each panel's legend gets its own dataset's - color followed by the shared ones; a pair list is drawn whole in - every panel. Default None. + ``truth``) recolors those entries of the grid's one shared + legend; a pair list defines that one legend outright. Default + None. colorbar : bool or dict If True, draws a colorbar reflecting the color mapping in use @@ -7021,7 +7035,9 @@ def plot( a right-side colorbar are shown, the figure is widened so neither is clipped or overlaps the other). Raises ``ValueError`` if requested with no color mapping available at all (e.g. a single - dataset with no `hue`/`cluster`). Default None (no colorbar). + dataset with no `hue`/`cluster`). A `panels=` grid draws ONE + colorbar for the whole figure, over one color scale shared by + every panel (see `panels=`). Default None (no colorbar). title : str or list of str A title for the plot. Normally a single string. For serial-style @@ -8581,10 +8597,67 @@ def plot( `names=`, `color=`, `fmt=`, `alpha=`, `marker(s)=`, `linestyle(s)=`, `surface=`, `density=`, `truth=`, a per-dataset `palette=` list such as ``['viridis', 'magma']``, ...) are - narrowed to each panel's own dataset, in either `panel_fit=` mode; - `legend=`/`colorbar=` are drawn per panel, and a `legend=` LIST - naming the datasets (no `hue=`/`cluster=` grouping) gives each - panel its own entry. Forecast arguments partition the same way: + narrowed to each panel's own dataset, in either `panel_fit=` mode. + + COLORS, THE LEGEND AND THE COLORBAR ARE SHARED BY THE WHOLE GRID + (1.2; a static grid looks different from 1.1, where every panel + restarted the palette and carried its own legend and colorbar). + Color means one thing across the figure. With one panel per + dataset, dataset i is drawn in the color the equivalent + single-axes call of ALL the datasets gives it (palette position i + of n -- not the first palette color in every panel); an explicit + `color=`, a color letter in `fmt=` and a per-dataset `palette=` + are honored exactly as that call honors them. A continuous `hue=` + is mapped over ONE value range, the range of every panel's + values, so a color is the same value in every panel; a categorical + `hue=`, and clusters from a shared fit, use ONE label-to-color + mapping. (A list-valued `reduce=` grid draws every dataset in + every panel and always colored them alike.) + + The legend and the colorbar are then drawn ONCE for the figure: + one legend holding the union of the panels' entries without + duplicates -- the data entries in dataset order, then the + `predict=`/`truth=` entries, where two entries are one when they + have the same label and look the same (a forecast or truth key + that differs between panels only in color is one key in the + neutral gray the single-axes legend uses for a model that + continues several datasets) -- and/or one colorbar. They sit in + a strip to the right of the grid, vertically centered on it, + clear of every panel, title and `caption=`; the default figure + is widened by the strip's width (an explicit `size=` is honored + and the grid is laid out beside the strip), and in an animated + grid they are static across frames. ``legend=True`` numbers the + datasets ``1..n`` as the single-axes call does, and a `legend=` + LIST naming the datasets (no `hue=`/`cluster=` grouping) gives + one entry per dataset. `legend_kwargs=` styles the one legend; a + ``loc``/``bbox_to_anchor`` (plotly: ``x``/``y``) in it places + that legend in FIGURE coordinates and no strip is reserved for + it. A `colorbar=` ``location`` other than ``'right'`` attaches + the one colorbar to that side of the whole grid. No legend or + colorbar is added that the call did not ask for. On the returned + matplotlib figure the shared legend is a figure-level legend + (``fig.legends``, gid ``'hypertools-shared-legend'``) and the + colorbar an axes with gid ``'hypertools-shared-colorbar'``; on + plotly they are ``layout.legend`` and one colorbar trace. + + The exception is a grid whose colors do NOT mean the same thing + in every panel: clusters (`cluster=`/`n_clusters=`) fit + separately per panel -- under ``panel_fit='independent'``, or + with a list-valued `reduce=`, where each panel clusters its own + embedding -- and `forecast_cluster=`/`forecast_n_clusters=`, + which group each panel's own forecasts. Cluster 1 of one panel is + then not cluster 1 of the next, so every panel keeps its own + legend and colorbar beside it (as does a grid in which one legend + label would look different in two panels); one shared key would + claim a meaning that is false. With `return_model=True` the + bundle's ``'colors'`` is the one scale the panels share (every + dataset's color, in panel order, for a one-panel-per-dataset + grid; the grid-wide range of a continuous `hue=`; the union of + the categories), and each ``panel_models[i]['colors']`` holds + the colors that panel drew. In the exception above ``'colors'`` + is the first panel's own scale, as before. + + Forecast arguments partition the same way: `forecast_fmt=` and `forecast_hue=` given per forecast (per dataset for one `predict=` model, model-major for a collection -- see `predict=`) reach each panel as its own forecasts' entries (a @@ -8598,7 +8671,8 @@ def plot( reused rather than refit -- a forecaster fitted on a different number of datasets than there are panels raises ``ValueError``. `forecast_cluster=` groups each panel's own forecast endpoints - (with a single model, one per panel -- it then warns and inherits). + (with a single model, one per panel -- it then warns and inherits), + which is why its panels keep their own legends (above). ANIMATED GRIDS (matplotlib only). With a truthy `animate=` the whole grid is ONE animation: every panel runs on the same clock diff --git a/hypertools/plot/plotly_backend.py b/hypertools/plot/plotly_backend.py index 4faec5e48..ba2c436d9 100644 --- a/hypertools/plot/plotly_backend.py +++ b/hypertools/plot/plotly_backend.py @@ -3256,6 +3256,7 @@ def _legend_trace_look(trace, color=True): marker.get('symbol') if 'markers' in mode else None] if color: def _plain(value): + """A color as a comparable plain value.""" return value if (value is None or isinstance(value, str)) \ else repr(np.asarray(value).tolist()) look += [_plain(line.get('color')) if 'lines' in mode else None, @@ -3328,8 +3329,15 @@ def _color_alpha(color): return 1.0 +#: room (pixels) a `panels=` grid reserves above or below itself for a +#: shared HORIZONTAL colorbar (``location='top'``/``'bottom'``): the bar, +#: its tick labels and its title +PANEL_COLORBAR_ROW_PX = 70 + + def place_shared_furniture(target, legend, colorbar_trace, ndims, - legend_position=None, font=None): + legend_position=None, font=None, title_px=0, + widen=True): """Give a filled `panels=` grid ONE legend and/or ONE colorbar, in the strip `make_panel_grid` reserved right of the whole grid (`strip_px`). With `legend`, every trace is attached to the figure's @@ -3339,11 +3347,32 @@ def place_shared_furniture(target, legend, colorbar_trace, ndims, `legend_position` (``{'x', 'y'}``, paper fractions), a caller's own `legend_kwargs` placement. `colorbar_trace` (`_colorbar_trace`'s phantom trace, carrying the merged colorbar) is added to the first - cell and, when vertical on the right, placed right of the legend; - `font` is the panels' inherited text font.""" + cell and, when vertical on the right, placed right of the legend. A + colorbar on another side (``location='left'``/``'top'``/``'bottom'``) + is placed on that side of the WHOLE grid, in room added to that + margin -- and to the figure's size with `widen` (no explicit `size=`) + -- above the `title_px` of title room when on top. `font` is the + panels' inherited text font.""" + side = None + if colorbar_trace is not None: + cb = colorbar_trace.marker.colorbar + if cb.orientation in (None, 'v'): + side = 'l' if cb.xanchor == 'right' else None + else: + side = 't' if (cb.y is not None and cb.y > 0.5) else 'b' + if side is not None: + extra = PANEL_COLORBAR_PX if side == 'l' else PANEL_COLORBAR_ROW_PX + target.layout.margin[side] = (target.layout.margin[side] or 0) + extra + if widen and side == 'l': + target.layout.width = target.layout.width + extra + elif widen: + target.layout.height = target.layout.height + extra plot_w = max((target.layout.width or int(DEFAULT_FIGSIZE[0] * 100)) - (target.layout.margin.l or 0) - (target.layout.margin.r or 0), 1) + plot_h = max((target.layout.height or int(DEFAULT_FIGSIZE[1] * 100)) + - (target.layout.margin.t or 0) + - (target.layout.margin.b or 0), 1) if legend: style = target.layout.legend.to_plotly_json() for trace in target.data: @@ -3358,11 +3387,19 @@ def place_shared_furniture(target, legend, colorbar_trace, ndims, xanchor='left', yanchor='middle') target.layout.legend = style if colorbar_trace is not None: - cb = colorbar_trace.marker.colorbar - if cb.orientation in (None, 'v') and cb.xanchor != 'right': + if side is None: offset = PANEL_GUTTER_PAD_PX + (PANEL_LEGEND_PX if legend else 0) cb.update(x=1.0 + offset / plot_w, xanchor='left', y=0.5, yanchor='middle') + elif side == 'l': + cb.update(x=-PANEL_GUTTER_PAD_PX / plot_w, xanchor='right', + y=0.5, yanchor='middle') + elif side == 't': + cb.update(x=0.5, xanchor='center', yanchor='bottom', + y=1.0 + (title_px + PANEL_GUTTER_PAD_PX) / plot_h) + else: + cb.update(x=0.5, xanchor='center', yanchor='top', + y=-PANEL_GUTTER_PAD_PX / plot_h) if font: cb.tickfont = _with_base_font(cb.tickfont.to_plotly_json(), font) if cb.title is not None and cb.title.text: diff --git a/notes/session_2026-11-22_feat295-animated-panels.md b/notes/session_2026-11-22_feat295-animated-panels.md index aca69a355..003ad0ee9 100644 --- a/notes/session_2026-11-22_feat295-animated-panels.md +++ b/notes/session_2026-11-22_feat295-animated-panels.md @@ -51,3 +51,41 @@ old-refusal tests in `tests/test_plot_panels.py` and `tests/test_plot_panels_audit.py` now assert the new behavior. The full suite was not run (about 25 minutes); the panel, animation, hook, title, docs and example test files were. + +## Shared colors, legend and colorbar for panel grids (branch feat/295-shared-legend) + +Owner requirement (2026-11-22): "Legends and colorbars should be consolidated +(shown once across panels) and coloring should not be repeated to mean +different things across panels". + +What was built (all in `hypertools/plot/plot.py` unless noted): + +- `_plot_panels` resolves what the single-axes call of every dataset draws and + hands each panel its share: `_panel_dataset_colors` (dataset i = palette + position i of n, passed as `color=`), `legend=True` -> `[i + 1]`, and the + grid's `hue=` scale (`_panel_apply_hue_scale`: `_panel_shared['limits']` for + a continuous hue, a narrowed `{category: color}` palette for a categorical + one). The scale is the shared probe's `'colors'` (`_panel_probe` now returns + it) or, for `panel_fit='independent'`, `_panel_color_probe`. +- `plot()` takes an internal `_panel_shared` dict: `'limits'` pins the + continuous hue range (`_multicolor_line_colors(limits=)`, + `_build_colorbar_info(limits=)`), and `'colorbars'` collects the panel's + colorbar instead of drawing it (and skips `_fit_right_legend`). +- After the panels are drawn: `_merge_panel_legends`, `_merge_panel_colorbars`, + `_add_shared_furniture` (strip right of the grid; grid laid out without the + strip, then `_grow_figure_rightward`), `_place_shared_furniture` (re-run + after the caption and the animated cube fit). +- Per-panel legends/colorbars remain when `_panel_meanings_differ` (clusters + fit per panel, forecast clusters) or on `_PanelFurnitureConflict` (a label + that looks different in two panels: the grid is drawn again per panel). +- Plotly: `merge_panel_legends`, `place_shared_furniture` and + `make_panel_grid(strip_px=)` in `plotly_backend.py`. +- Bundle `'colors'`: `_merge_panel_color_scales`. + +Gotchas met: `tight_layout(rect=...)` and a single `tight_layout()` pass after +removing the panels' own legends both under-reserve a 3-D panel's title room +(titles left the canvas); three passes on a strip-less figure settle it. + +Tests: `tests/test_panels_shared_legend_colors.py` (new); the tests that +asserted per-panel legends/colorbars/colors were rewritten, each with a +"CHANGED for 1.2.0" comment. diff --git a/tests/test_animated_panels.py b/tests/test_animated_panels.py index 56c0dd0f9..a2237a4fe 100644 --- a/tests/test_animated_panels.py +++ b/tests/test_animated_panels.py @@ -284,21 +284,30 @@ def test_a_callable_title_is_updated_per_panel_every_frame(): ['frame 5'] * 4) -def test_every_panel_gets_its_legend(): +def test_the_grid_gets_one_legend_naming_every_panel(): + # CHANGED for 1.2.0 (owner decision 2026-11-22; was + # `test_every_panel_gets_its_legend`): every panel carried a one-entry + # legend. An animated grid now draws ONE legend for the figure, listing + # every dataset once, as a static grid does. anim = _grid(legend=['a', 'b', 'c', 'd']) - legends = [ax.get_legend() for ax in _panel_axes(anim.figure)] - assert all(legend is not None for legend in legends) - assert [legend.get_texts()[0].get_text() for legend in legends] == ( + assert all(ax.get_legend() is None for ax in _panel_axes(anim.figure)) + (legend,) = anim.figure.legends + assert [text.get_text() for text in legend.get_texts()] == ( ['a', 'b', 'c', 'd']) -def test_every_panel_gets_its_colorbar(): +def test_the_grid_gets_one_colorbar(): + # CHANGED for 1.2.0 (owner decision 2026-11-22; was + # `test_every_panel_gets_its_colorbar`): every panel carried its own + # colorbar (six axes). The panels share one color scale, so the grid + # draws ONE colorbar for the figure. hue = [np.arange(len(d), dtype=float) for d in DATA[:3]] anim = _grid(DATA[:3], panels=(1, 3), hue=hue, colorbar=True) fig = anim.figure - # three panels and three colorbar axes - assert len(fig.axes) == 6 + # three panels and one colorbar axes + assert len(fig.axes) == 4 assert sum(ax.name == '3d' for ax in fig.axes) == 3 + assert sum(ax.get_label() == '' for ax in fig.axes) == 1 # --- fits --------------------------------------------------------------- @@ -424,24 +433,26 @@ def test_titles_and_legends_stay_on_the_canvas_and_clear_of_the_cubes(): frame_rate=6) fig = anim.figure axes = _panel_axes(fig) + # CHANGED for 1.2.0 (owner decision 2026-11-22): every panel had its + # own legend, which had to sit right of its own cube and short of the + # next panel's. The grid now draws ONE legend, which must sit right of + # EVERY panel's cube, on the canvas, at every frame. + (shared,) = fig.legends for frame in (0, anim.n_frames // 2, anim.n_frames - 1): anim.draw_frame(frame) fig.canvas.draw() renderer = fig.canvas.get_renderer() canvas = fig.bbox + legend = shared.get_window_extent(renderer) + assert _inside(legend, canvas), (frame, 'legend') for i, ax in enumerate(axes): + assert ax.get_legend() is None title = ax.title.get_window_extent(renderer) - legend = ax.get_legend().get_window_extent(renderer) assert _inside(title, canvas), (frame, i, 'title') - assert _inside(legend, canvas), (frame, i, 'legend') corners = _cube_corners_px(ax) - # the title is above the cube, the legend to its right + # the title is above the cube, the legend right of every cube assert title.y0 >= corners[:, 1].max(), (frame, i) assert legend.x0 >= corners[:, 0].max(), (frame, i) - # ...and the legend stops short of the next panel's cube - if i + 1 < len(axes): - next_corners = _cube_corners_px(axes[i + 1]) - assert legend.x1 <= next_corners[:, 0].min(), (frame, i) def test_axis_labels_enlarge_the_figure_and_stay_inside_their_cells(): diff --git a/tests/test_figure_review_gaps.py b/tests/test_figure_review_gaps.py index c8cf19a2b..4e1d7cc2e 100644 --- a/tests/test_figure_review_gaps.py +++ b/tests/test_figure_review_gaps.py @@ -61,9 +61,15 @@ def test_caller_axes_draw_in_the_palette(): def test_panels_draw_in_the_palette(): fig = hyp.plot(_walks(3), panels=True, show=False) - first = _own_colors(1)[0] - for ax in fig.axes[:3]: - assert to_rgb(_data_lines(ax)[0].get_color()) == first + # CHANGED for 1.2.0 (owner decision 2026-11-22): every panel drew its + # dataset in the palette's FIRST color, so one color named three + # different datasets. Each panel still draws in the palette (not + # matplotlib's C0/C1 cycle, the point of this test), but dataset i now + # takes the color the single-axes call of all three gives it. + expected = [tuple(c) for c in _own_colors(3)] + assert len(set(expected)) == 3 + for ax, color in zip(fig.axes[:3], expected): + assert to_rgb(_data_lines(ax)[0].get_color()) == pytest.approx(color) def test_explicit_palette_reaches_a_caller_axes(): @@ -229,8 +235,12 @@ def test_plotly_legend_keys_use_a_constant_item_size(): assert fig.layout.legend.itemsizing == 'constant' grid = hyp.plot(_walks(2), '.', panels=True, legend=True, show=False, backend='plotly') + # CHANGED for 1.2.0 (owner decision 2026-11-22): each cell had its own + # legend (`layout.legend`, `layout.legend2`). The grid now has ONE, + # `layout.legend`, which keeps the constant item size. assert grid.layout.legend.itemsizing == 'constant' - assert grid.layout.legend2.itemsizing == 'constant' + assert 'legend2' not in grid.layout.to_plotly_json() + assert {t.legend for t in grid.data if t.showlegend} <= {None, 'legend'} # --- G9: a plotly hyp.subplots grid grows its gutters only when needed --- diff --git a/tests/test_palette_compose_review.py b/tests/test_palette_compose_review.py index 99fddf148..134c02528 100644 --- a/tests/test_palette_compose_review.py +++ b/tests/test_palette_compose_review.py @@ -255,6 +255,15 @@ def _legend_colours(ax): for t, h in zip(legend.get_texts(), legend.legend_handles)] +def _grid_legend_colours(fig): + """The entries of a `panels=` grid's ONE figure-wide legend (1.2.0), + after checking no panel carries a legend of its own.""" + assert all(ax.get_legend() is None for ax in fig.axes) + (legend,) = fig.legends + return [(t.get_text(), _r3(h.get_color())) + for t, h in zip(legend.get_texts(), legend.legend_handles)] + + @pytest.mark.parametrize('panel_fit', ['shared', 'independent']) def test_panels_split_a_plain_legend_colors_list(panel_fit): data = _walks(2, rows=30) @@ -264,8 +273,11 @@ def test_panels_split_a_plain_legend_colors_list(panel_fit): ('b', _r3('b'))] fig = hyp.plot(data, legend=['a', 'b'], legend_colors=['r', 'b'], panels=True, panel_fit=panel_fit, show=False) - assert _legend_colours(fig.axes[0]) == [('a', _r3('r'))] - assert _legend_colours(fig.axes[1]) == [('b', _r3('b'))] + # CHANGED for 1.2.0 (owner decision 2026-11-22): each panel had its + # own one-entry legend, so the list was split one color per panel. The + # grid now draws ONE legend for the figure, and the list recolors its + # entries exactly as it recolors the single-axes legend's. + assert _grid_legend_colours(fig) == _legend_colours(single.axes[0]) def test_panels_keep_the_shared_legend_colours_after_the_datasets(): @@ -276,17 +288,20 @@ def test_panels_keep_the_shared_legend_colours_after_the_datasets(): assert _legend_colours(single.axes[0]) == [ ('a', _r3('r')), ('b', _r3('b')), ('Kalman', _r3('k'))] fig = hyp.plot(data, panels=True, **kw) - assert _legend_colours(fig.axes[0]) == [('a', _r3('r')), - ('Kalman', _r3('k'))] - assert _legend_colours(fig.axes[1]) == [('b', _r3('b')), - ('Kalman', _r3('k'))] + # CHANGED for 1.2.0 (owner decision 2026-11-22): each panel's legend + # listed its own dataset and then the shared forecast entry. The grid + # now draws ONE legend, with the forecast entry once, after the + # datasets -- the single-axes legend. + assert _grid_legend_colours(fig) == _legend_colours(single.axes[0]) def test_panels_forward_legend_colour_pairs_whole(): fig = hyp.plot(_walks(2, rows=30), legend=True, legend_colors=[('Key', 'k')], panels=True, show=False) - for ax in fig.axes[:2]: - assert _legend_colours(ax) == [('Key', _r3('k'))] + # CHANGED for 1.2.0 (owner decision 2026-11-22): the pair list was + # drawn whole in EVERY panel's legend; it now defines the grid's one + # figure-wide legend, drawn once. + assert _grid_legend_colours(fig) == [('Key', _r3('k'))] # --- 5: two-column data into a 2-D ax= at the default ndims ---------------- diff --git a/tests/test_panels_shared_legend_colors.py b/tests/test_panels_shared_legend_colors.py index c4a1e6352..89547fad3 100644 --- a/tests/test_panels_shared_legend_colors.py +++ b/tests/test_panels_shared_legend_colors.py @@ -144,6 +144,49 @@ def test_one_legend_for_the_figure_with_every_dataset(): assert [label for label, _ in _entries(legend)] == names +def test_legend_true_numbers_the_datasets_as_the_single_axes_call_does(): + x = _walks() + single = _quiet_plot(x, legend=True) + grid = _quiet_plot(x, legend=True, panels=True, return_model=True) + legend = _shared_legend(grid['fig']) + assert _entries(legend) == _entries(single.axes[0].get_legend()) + assert [label for label, _ in _entries(legend)] == ['1', '2', '3', '4'] + + +def test_a_label_that_looks_different_in_two_panels_keeps_panel_legends(): + """One shared entry would be wrong for one of the panels, so the grid + does not claim one.""" + x = _walks(2) + grid = _quiet_plot(x, legend=['same', 'same'], panels=True, + return_model=True) + fig = grid['fig'] + assert fig.legends == [] + assert [[t.get_text() for t in ax.get_legend().get_texts()] + for ax in grid['axes']] == [['same'], ['same']] + # ...and the datasets still keep their own colors + assert _line_colors(grid['axes'][0]) != _line_colors(grid['axes'][1]) + + +def test_legend_kwargs_style_the_one_legend_and_can_place_it(): + x = _walks(3) + fig = _quiet_plot(x, legend=['a', 'b', 'c'], panels=True, + legend_kwargs={'title': 'who', 'fontsize': 14}) + legend = _shared_legend(fig) + assert legend.get_title().get_text() == 'who' + assert legend.get_texts()[0].get_fontsize() == 14 + _assert_strip_clear(fig, fig.axes[:3]) + placed = _quiet_plot(x, legend=['a', 'b', 'c'], panels=True, + legend_kwargs={'loc': 'lower center', 'ncol': 3}) + legend = _shared_legend(placed) + placed.canvas.draw() + box = legend.get_window_extent(placed.canvas.get_renderer()) + # figure coordinates: centered under the whole grid, and no strip + assert abs(0.5 * (box.x0 + box.x1) - 0.5 * placed.bbox.width) < 2 + assert box.y0 < 0.1 * placed.bbox.height + assert placed.get_size_inches()[0] == pytest.approx( + _quiet_plot(x, panels=True).get_size_inches()[0]) + + def test_legend_false_or_absent_adds_nothing(): x = _walks() for kw in ({}, dict(legend=False), dict(legend=None)): @@ -271,6 +314,37 @@ def test_categorical_hue_colorbar_is_one_bar_with_every_category(): _assert_strip_clear(grid['fig'], grid['axes']) +def test_palette_dict_names_every_category_of_the_grid(): + """A `palette=` dict names the whole grid's categories; a panel that + holds only some of them used to refuse the others' keys.""" + x = _walks(3) + hue = [['p'] * 30, ['q'] * 30, ['r'] * 15 + ['p'] * 15] + palette = {'p': 'red', 'q': 'green', 'r': 'blue'} + grid = _quiet_plot(x, hue=hue, fmt='o', legend=True, palette=palette, + panels=True, return_model=True) + assert _entries(_shared_legend(grid['fig'])) == [ + ('p', (1.0, 0.0, 0.0)), ('q', (0.0, 0.502, 0.0)), + ('r', (0.0, 0.0, 1.0))] + + +@pytest.mark.parametrize('location', ['left', 'top', 'bottom']) +def test_colorbar_on_another_side_is_still_one_bar(location): + x = _walks(3, rows=21) + hue = [np.linspace(k, k + 2, 21) for k in range(3)] + grid = _quiet_plot(x, hue=hue, colorbar={'location': location}, + panels=True, ndims=2, return_model=True) + fig = grid['fig'] + (bar,) = _shared_colorbars(fig) + assert len(fig.axes) == 4 + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + box = bar.get_tightbbox(renderer) + assert box.x0 >= 0 and box.x1 <= fig.bbox.x1 + assert box.y0 >= 0 and box.y1 <= fig.bbox.y1 + for ax in grid['axes']: + assert not box.overlaps(ax.get_window_extent(renderer)) + + # -- clusters ----------------------------------------------------------------- def test_shared_fit_clusters_have_one_legend(): @@ -478,6 +552,42 @@ def test_plotly_grid_categorical_hue_and_legend_false(): assert not bare.layout.showlegend +@pytest.mark.parametrize('location', ['right', 'left', 'top', 'bottom']) +def test_plotly_shared_colorbar_stays_on_the_canvas(location): + x = _walks(3, rows=21) + hue = [np.linspace(k, k + 2, 21) for k in range(3)] + fig = _quiet_plot(x, hue=hue, colorbar={'location': location}, + panels=True, backend='plotly', + title=['one', 'two', 'three']) + (bar,) = [t.marker.colorbar for t in fig.data + if getattr(getattr(t, 'marker', None), 'showscale', None)] + margin = fig.layout.margin + plot_w = fig.layout.width - margin.l - margin.r + plot_h = fig.layout.height - margin.t - margin.b + if location == 'right': + assert bar.x >= 1.0 and (bar.x - 1.0) * plot_w + 60 <= margin.r + elif location == 'left': + assert bar.x <= 0.0 and -bar.x * plot_w + 60 <= margin.l + elif location == 'top': + assert bar.y >= 1.0 and (bar.y - 1.0) * plot_h + 50 <= margin.t + else: + assert bar.y <= 0.0 and -bar.y * plot_h + 50 <= margin.b + + +def test_plotly_forecast_keys_are_listed_once(): + x = _walks(3, rows=40, cols=2) + kw = dict(predict='ARIMA', t=5, legend=['a', 'b', 'c'], ndims=2, + backend='plotly') + single = _quiet_plot(x, **kw) + fig = _quiet_plot(x, panels=True, **kw) + assert sorted(_plotly_legend_names(fig)) == sorted( + _plotly_legend_names(single)) == ['ARIMA', 'a', 'b', 'c'] + key = [t for t in fig.data if t.showlegend and t.name == 'ARIMA'][0] + ref = [t for t in single.data if t.showlegend and t.name == 'ARIMA'][0] + # one model continuing three datasets: the neutral key, as on one axes + assert _plotly_rgb(key.line.color) == _plotly_rgb(ref.line.color) + + def test_plotly_independent_clusters_keep_per_panel_legends(): x = _walks(3) fig = _quiet_plot(x, n_clusters=2, fmt='o', legend=True, panels=True, diff --git a/tests/test_plot_panels.py b/tests/test_plot_panels.py index 11a5a5010..9806af797 100644 --- a/tests/test_plot_panels.py +++ b/tests/test_plot_panels.py @@ -216,9 +216,13 @@ def test_panels_names_are_narrowed_per_panel(): data = _datasets(3, rows=20) fig = hyp.plot(data, panels=(1, 3), names=['a', 'b', 'c'], legend=True, reduce='PCA', show=False) - got = [[t.get_text() for t in ax.get_legend().get_texts()] - for ax in fig.axes] - assert got == [['a'], ['b'], ['c']] + # CHANGED for 1.2.0 (owner decision 2026-11-22): each panel carried a + # one-entry legend naming its own dataset. `names=` is still narrowed + # per panel (each dataset is named once, by its own name), but the + # entries are now listed in ONE legend for the whole figure. + assert all(ax.get_legend() is None for ax in fig.axes) + (legend,) = fig.legends + assert [t.get_text() for t in legend.get_texts()] == ['a', 'b', 'c'] def test_panels_color_list_is_narrowed_per_panel(): @@ -502,14 +506,17 @@ def test_plotly_panels_get_one_legend_each_with_their_own_entries(): for trace in fig.data: if trace.showlegend: by_legend.setdefault(trace.legend, []).append(trace.name) - assert by_legend == {'legend': ['p'], 'legend2': ['q'], - 'legend3': ['r']} - # each legend sits just right of its own cell, not at the figure edge - for key, scene in (('legend', 'scene'), ('legend2', 'scene2'), - ('legend3', 'scene3')): - x1 = fig.layout[scene].domain.x[1] - assert fig.layout[key].x > x1 - assert fig.layout[key].x < x1 + 0.2 + # CHANGED for 1.2.0 (owner decision 2026-11-22): each cell had its own + # one-entry legend beside it (`legend`, `legend2`, `legend3`). The grid + # now lists every dataset in ONE legend, right of the last cell, in the + # strip reserved for it in the right margin. + assert by_legend == {'legend': ['p', 'q', 'r']} + assert not [key for key in fig.layout.to_plotly_json() + if key.startswith('legend') and key != 'legend'] + assert fig.layout.legend.x > fig.layout.scene3.domain.x[1] + assert fig.layout.legend.xanchor == 'left' + plot_w = fig.layout.width - fig.layout.margin.l - fig.layout.margin.r + assert (fig.layout.legend.x - 1.0) * plot_w + 100 <= fig.layout.margin.r assert fig.layout.showlegend is True @@ -523,7 +530,10 @@ def test_plotly_panels_hue_legend_lists_each_group_once_per_panel(): for trace in fig.data: if trace.showlegend: names.setdefault(trace.legend, []).append(trace.name) - assert names == {'legend': ['x', 'y'], 'legend2': ['x', 'y']} + # CHANGED for 1.2.0 (owner decision 2026-11-22): both panels listed + # 'x' and 'y' in a legend of their own. The categories mean the same + # thing in both panels, so each is listed once, in the grid's legend. + assert names == {'legend': ['x', 'y']} def test_plotly_panels_without_legend_have_none(): @@ -541,11 +551,12 @@ def test_plotly_panels_place_each_colorbar_beside_its_own_panel(): backend='plotly', show=False) colorbars = [t.marker.colorbar for t in fig.data if t.marker is not None and t.marker.showscale] - assert len(colorbars) == 2 - assert colorbars[0].x < colorbars[1].x - assert colorbars[0].x > fig.layout.scene.domain.x[1] - assert colorbars[1].x > fig.layout.scene2.domain.x[1] - assert colorbars[0].x < fig.layout.scene2.domain.x[0] + # CHANGED for 1.2.0 (owner decision 2026-11-22): each panel had its + # own colorbar beside its own cell. Both panels share one color scale, + # so the grid draws ONE colorbar, right of the last cell. + assert len(colorbars) == 1 + assert colorbars[0].x > fig.layout.scene2.domain.x[1] + assert colorbars[0].xanchor == 'left' def test_plotly_panels_reserve_a_gutter_only_when_needed(): @@ -618,14 +629,17 @@ def test_matplotlib_panels_draw_one_colorbar_per_panel_without_warnings(): try: panels = [ax for ax in fig.axes if ax.get_label() != ''] cbars = [ax for ax in fig.axes if ax.get_label() == ''] - assert len(panels) == 2 and len(cbars) == 2 - # each colorbar sits to the right of its own panel and left of the - # next panel: no two share a position - xs = sorted(ax.get_position().x0 for ax in panels + cbars) - assert len(set(round(x, 3) for x in xs)) == 4 + # CHANGED for 1.2.0 (owner decision 2026-11-22): this asserted one + # colorbar per panel, each right of its own panel. Both panels + # share one color scale, so the grid draws ONE colorbar, right of + # both panels -- still without a layout warning. + assert len(panels) == 2 and len(cbars) == 1 order = sorted(panels + cbars, key=lambda ax: ax.get_position().x0) assert [ax.get_label() == '' for ax in order] == [ - False, True, False, True] + False, False, True] + assert cbars[0].get_position().x0 > max( + ax.get_position().x1 for ax in panels) + assert cbars[0].get_position().x1 < 1.0 finally: matplotlib.pyplot.close(fig) @@ -669,11 +683,14 @@ def test_plotly_panels_keep_a_left_colorbar_on_the_left(): show=False) colorbars = [t.marker.colorbar for t in fig.data if t.marker is not None and t.marker.showscale] - assert len(colorbars) == 2 + # CHANGED for 1.2.0 (owner decision 2026-11-22): each panel had its + # own colorbar on its own left. The grid now draws ONE colorbar, on + # the LEFT of the whole grid, in room reserved in the left margin. + assert len(colorbars) == 1 assert colorbars[0].xanchor == 'right' assert colorbars[0].x <= fig.layout.scene.domain.x[0] - assert colorbars[1].xanchor == 'right' - assert colorbars[1].x <= fig.layout.scene2.domain.x[0] + plot_w = fig.layout.width - fig.layout.margin.l - fig.layout.margin.r + assert -colorbars[0].x * plot_w + 60 <= fig.layout.margin.l def test_plotly_panel_titles_go_through_the_title_path(): @@ -702,8 +719,10 @@ def test_plotly_panels_carry_the_font_into_the_grid(): single = hyp.plot(_datasets(1, rows=20)[0], legend=True, names=['p'], font='DejaVu Serif', backend='plotly', show=False) assert fig.layout.font.family == single.layout.font.family + # CHANGED for 1.2.0 (owner decision 2026-11-22): the grid has ONE + # legend (`layout.legend`), not one per cell; it carries the font. assert fig.layout.legend.font.family == single.layout.font.family - assert fig.layout.legend2.font.family == single.layout.font.family + assert 'legend2' not in fig.layout.to_plotly_json() def test_plotly_grid_png_draws_something_in_every_cell(tmp_path): diff --git a/tests/test_plot_panels_audit.py b/tests/test_plot_panels_audit.py index 40c81a5bb..78b5474a6 100644 --- a/tests/test_plot_panels_audit.py +++ b/tests/test_plot_panels_audit.py @@ -247,9 +247,16 @@ def test_legend_list_naming_the_datasets_is_partitioned(backend): artists = data_artists(grid, i, backend) assert [a[3] for a in artists] == [name] if backend == 'matplotlib': - legend = grid['axes'][i].get_legend() - assert legend is not None - assert [t.get_text() for t in legend.get_texts()] == [name] + # CHANGED for 1.2.0 (owner decision 2026-11-22): each + # panel carried a one-entry legend with its own name. The + # list is still partitioned (each panel's artist is + # labeled with its own name, above), and the names are + # listed in ONE legend for the figure. + assert grid['axes'][i].get_legend() is None + if backend == 'matplotlib': + (legend,) = grid['fig'].legends + assert [t.get_text() for t in legend.get_texts()] == [ + 'alpha', 'beta', 'gamma'] finally: close_all() diff --git a/tests/test_plot_panels_fit.py b/tests/test_plot_panels_fit.py index a0ce6855f..8399a4368 100644 --- a/tests/test_plot_panels_fit.py +++ b/tests/test_plot_panels_fit.py @@ -379,11 +379,30 @@ def test_P3_nested_per_dataset_hue_is_narrowed_per_panel(panel_fit): show=False) try: assert len(bundle['axes']) == 2 - # each panel's colour scale spans ITS OWN hue values - for model, values in zip(bundle['panel_models'], hue): + # CHANGED for 1.2.0 (owner decision 2026-11-22): this asserted that + # each panel's color scale spans ITS OWN hue values, so one color + # meant 1.0 in the first panel and 9.0 in the second. A grid now + # maps every panel over ONE range -- all the panels' values -- so + # a color is the same value in every panel. The hue is still + # narrowed per panel (the point of P3): each panel draws its own + # dataset's values, read here off the colors it drew. + for model in bundle['panel_models']: colors = model['colors'] - assert colors['vmin'] == pytest.approx(values.min()) - assert colors['vmax'] == pytest.approx(values.max()) + assert colors['vmin'] == pytest.approx(0.0) + assert colors['vmax'] == pytest.approx(9.0) + assert bundle['colors']['vmin'] == pytest.approx(0.0) + assert bundle['colors']['vmax'] == pytest.approx(9.0) + cmap, norm = bundle['colors']['cmap'], bundle['colors']['norm'] + for ax, values in zip(bundle['axes'], hue): + drawn = np.vstack([np.asarray(c.get_colors()) + for c in ax.collections + if len(c.get_colors()) > 1])[:, :3] + # the panel's first and last drawn colors are its OWN first + # and last values under the shared scale + assert np.allclose(drawn[0], cmap(norm(values[0]))[:3], + atol=0.03) + assert np.allclose(drawn[-1], cmap(norm(values[-1]))[:3], + atol=0.03) finally: plt.close(bundle['fig']) diff --git a/tests/test_plot_review_round3.py b/tests/test_plot_review_round3.py index fb24e7b50..a0882cd4e 100644 --- a/tests/test_plot_review_round3.py +++ b/tests/test_plot_review_round3.py @@ -237,13 +237,22 @@ def test_panel_legend_and_colorbar_do_not_overlap(ndims): 'kwargs': {'n_clusters': 2, 'random_state': 0}}) fig.canvas.draw() renderer = fig.canvas.get_renderer() - panels = [a for a in fig.axes if a.get_legend() is not None] - bars = [a for a in fig.axes if a.get_label() == ''] - assert len(panels) == len(bars) == 2 - for panel, bar in zip(panels, bars): - legend_box = panel.get_legend().get_window_extent(renderer) - assert Bbox.intersection(legend_box, - bar.get_window_extent(renderer)) is None + # CHANGED for 1.2.0 (owner decision 2026-11-22): each of the two panels + # had its own legend and its own colorbar, which must not overlap. The + # clusters come from ONE shared fit, so the grid now draws one legend + # and one colorbar for the figure -- which must not overlap each + # other, or either panel. + assert not [a for a in fig.axes if a.get_legend() is not None] + (legend,) = fig.legends + (bar,) = [a for a in fig.axes if a.get_label() == ''] + legend_box = legend.get_window_extent(renderer) + bar_box = bar.get_tightbbox(renderer) + assert Bbox.intersection(legend_box, bar_box) is None + for panel in [a for a in fig.axes if a is not bar and a.get_visible()]: + panel_box = panel.get_window_extent(renderer) + assert Bbox.intersection(legend_box, panel_box) is None + assert Bbox.intersection(bar_box, panel_box) is None + assert bar_box.x1 <= fig.bbox.x1 and legend_box.x0 >= 0 # --- 9 and 10: plotly cells keep title room and explicit legend positions -- @@ -266,14 +275,17 @@ def test_plotly_panels_keep_an_explicit_legend_position(): fig = hyp.plot([x, x + 2], panels=True, legend=True, show=False, legend_kwargs={'x': .02, 'y': .98, 'xanchor': 'left', 'yanchor': 'top'}, backend='plotly') - from hypertools.plot.plotly_backend import cell_layout_keys - for i in range(2): - keys = cell_layout_keys(i) - d = fig.layout[keys['scene']].domain - legend = fig.layout[keys['legend']] - assert legend.x == pytest.approx(d.x[0] + .02 * (d.x[1] - d.x[0])) - assert legend.y == pytest.approx(d.y[0] + .98 * (d.y[1] - d.y[0])) - assert legend.yanchor == 'top' + # CHANGED for 1.2.0 (owner decision 2026-11-22): each panel had its + # own legend, placed at the explicit position INSIDE its own cell. A + # `panels=` grid now has ONE legend, and an explicit position places + # it in the FIGURE's paper coordinates, as on a single plot. (A + # `hyp.subplots` cell, below, still keeps its own legend in the cell.) + assert not [key for key in fig.layout.to_plotly_json() + if key.startswith('legend') and key != 'legend'] + assert fig.layout.legend.x == pytest.approx(.02) + assert fig.layout.legend.y == pytest.approx(.98) + assert fig.layout.legend.yanchor == 'top' + assert [t.name for t in fig.data if t.showlegend] == ['1', '2'] fig, cells = hyp.subplots(1, 2, backend='plotly') hyp.plot(x, ax=cells[0], legend=True, names=['a'], show=False, backend='plotly', diff --git a/tests/test_plot_review_round9.py b/tests/test_plot_review_round9.py index ab251bc27..71ab4cb71 100644 --- a/tests/test_plot_review_round9.py +++ b/tests/test_plot_review_round9.py @@ -90,17 +90,31 @@ def _labelled_colors(fig, backend, models): out = [] if backend == 'matplotlib': cells = [ax for ax in fig.axes if ax.get_visible() and ax.lines] + # CHANGED for 1.2.0 (owner decision 2026-11-22): every cell of a + # `panels=` grid had its own legend. A shared-fit grid now draws + # ONE legend for the figure, so a cell's legend is read as the + # figure legend's entries for the clusters that cell draws (a + # single-axes figure still has its legend on the axes). for ax, m in zip(cells, models): + labels = sorted(set(np.asarray( + m['models']['cluster_labels']).tolist())) legend = ax.get_legend() + if legend is None: + (legend,) = fig.legends + keep = {str(label) for label in labels} + else: + keep = None names = [t.get_text() for t in legend.get_texts()] handles = [_rgb255(h.get_color()) for h in legend.legend_handles] out.append({ - 'labels': sorted(set(np.asarray( - m['models']['cluster_labels']).tolist())), - 'legend': dict(zip(names, handles)), + 'labels': labels, + 'legend': {name: color for name, color + in zip(names, handles) + if keep is None or name in keep}, 'lines': [_rgb255(ln.get_color()) for ln in ax.lines], }) return out + by_scene = {} for tr in _plotly_data_traces(fig): by_scene.setdefault(tr.scene, []).append(tr) @@ -116,6 +130,20 @@ def _labelled_colors(fig, backend, models): return out +def _shared_legend_map(fig, backend): + """{label: colour} of a `panels=` grid's ONE figure-wide legend, and + a check that no panel carries a legend of its own (1.2.0).""" + if backend == 'matplotlib': + (legend,) = fig.legends + assert all(ax.get_legend() is None for ax in fig.axes) + return {t.get_text(): _rgb255(h.get_color()) for t, h + in zip(legend.get_texts(), legend.legend_handles)} + shown = [tr for tr in fig.data if tr.showlegend] + assert {tr.legend for tr in shown} <= {None, 'legend'} + assert len({tr.name for tr in shown}) == len(shown) + return {tr.name: _rgb255(_trace_color(tr)) for tr in shown} + + @pytest.mark.parametrize('backend', BACKENDS) @pytest.mark.parametrize('fmt', ('o', '-')) @pytest.mark.parametrize('palette', ('hls', ['red', 'blue', 'green'])) @@ -150,6 +178,9 @@ def test_shared_panels_colour_each_cluster_as_the_joint_figure_does( # the three panels draw three DIFFERENT colours (no two clusters # collapsed onto the first palette entry) assert len({cell['lines'][0] for cell in cells}) == 3 + # 1.2.0 (owner decision 2026-11-22): the grid's ONE legend is the + # joint figure's legend, every cluster once + assert _shared_legend_map(grid['fig'], backend) == joint_map @pytest.mark.parametrize('backend', BACKENDS) @@ -171,6 +202,8 @@ def test_shared_panel_missing_a_cluster_keeps_the_others_colours(backend): assert cell['legend'] == {str(label): joint_map[str(label)]} assert {cell['lines'][0] for cell in cells} == { _rgb255('red'), _rgb255('blue')} + # 1.2.0 (owner decision 2026-11-22): one legend for the figure + assert _shared_legend_map(grid['fig'], backend) == joint_map @pytest.mark.parametrize('backend', BACKENDS) diff --git a/tests/test_plotly_cells_review.py b/tests/test_plotly_cells_review.py index ade00b788..bfd209b38 100644 --- a/tests/test_plotly_cells_review.py +++ b/tests/test_plotly_cells_review.py @@ -69,11 +69,16 @@ def test_panels_colorbars_do_not_land_on_the_next_panel(): X = _walks(k=2) fig = hyp.plot(X, panels=True, backend='plotly', show=False, hue=[np.linspace(0, 1, 40)] * 2, colorbar=True) - cbs = {t.scene: t.marker.colorbar for t in _colorbar_traces(fig)} - x1 = fig.layout.scene.domain.x[1] - assert cbs['scene'].x == pytest.approx( - x1 + PANEL_GUTTER_PAD_PX / _plot_w(fig)) - assert cbs['scene'].x + 60 / _plot_w(fig) < fig.layout.scene2.domain.x[0] + # CHANGED for 1.2.0 (owner decision 2026-11-22): each panel carried + # its own colorbar, which had to sit beside its own cell rather than + # on the next one. A `panels=` grid now draws ONE colorbar for the + # figure, right of the LAST panel -- so it lands on no panel at all. + (cb,) = [t.marker.colorbar for t in _colorbar_traces(fig)] + assert cb.x == pytest.approx(1.0 + PANEL_GUTTER_PAD_PX / _plot_w(fig)) + assert cb.xanchor == 'left' + assert cb.x > fig.layout.scene2.domain.x[1] + # ...inside the canvas: the strip reserved in the right margin holds it + assert (cb.x - 1.0) * _plot_w(fig) + 60 <= fig.layout.margin.r def test_colorbar_after_a_legend_in_the_same_cell_still_moves_right(): diff --git a/tests/test_polars_inputs.py b/tests/test_polars_inputs.py index e7e3d2534..75d24d833 100644 --- a/tests/test_polars_inputs.py +++ b/tests/test_polars_inputs.py @@ -635,11 +635,15 @@ def call(backend): ref = hyp.plot([pdf3, other], panels=True, ndims=1, reduce=None, legend=True, show=False) _assert_same_figure(out, ref, 'matplotlib') - legends = [[t.get_text() for t in ax.get_legend().get_texts()] - for ax in out.axes if ax.get_legend()] - assert legends == [['a', 'b', 'c'], ['a', 'b', 'c']] - assert legends == [[t.get_text() for t in ax.get_legend().get_texts()] - for ax in ref.axes if ax.get_legend()] + # CHANGED for 1.2.0 (owner decision 2026-11-22): both panels carried + # the same three-entry legend. The columns are colored alike in every + # panel, so the grid now draws that legend ONCE for the figure. + assert not any(ax.get_legend() for ax in out.axes) + legends = [[t.get_text() for t in legend.get_texts()] + for legend in out.legends] + assert legends == [['a', 'b', 'c']] + assert legends == [[t.get_text() for t in legend.get_texts()] + for legend in ref.legends] def test_plot_series_mode_names_polars_columns_like_pandas(frame3): From 6892a7d034dc8afadcccf01b4fd5f3c87136fd02 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 05:39:45 -0500 Subject: [PATCH 15/58] fix: shared panel strip clears the last column's axis labels (GH #295) The strip now starts right of what the last column draws (a 3-D panel's z-axis label hangs outside its box), and the hue range is only passed to the multicolor-line helper when a grid pins it. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/plot/plot.py | 77 ++++++++++++++++++----- tests/test_panels_shared_legend_colors.py | 23 +++++++ 2 files changed, 83 insertions(+), 17 deletions(-) diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index 43d7ba66c..c2694b372 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -5035,23 +5035,43 @@ def _finish(cbar): # (`_grow_figure_rightward`), so the layout is exactly the legend-less # grid's. (`tight_layout(rect=...)` is not: it drops the room a 3-D # panel's title needs, which then pokes out of the top of the canvas.) - grid_in = width_in if widen else max(width_in - strip_in, - 0.3 * width_in) - strip_in = (width_in + strip_in if widen else width_in) - grid_in - fig.set_size_inches(grid_in, height_in) - with warnings.catch_warnings(): - # the colorbar's axes is placed by hand (below), which - # `tight_layout` reports as an axes it cannot lay out - warnings.filterwarnings( - 'ignore', message='This figure includes Axes that are not ' - 'compatible with tight_layout') - # the panels were last laid out around their own legends, which - # are gone: one pass from there under-reserves a 3-D panel's - # title room (its box is aspect-constrained), a second settles it + total_in = width_in + strip_in if widen else width_in + grid_in = max(total_in - strip_in, 0.3 * total_in) + + def _lay_out(width): + """Lay the panels out in a `width`-inch figure and return how far + (inches) what they draw reaches past its right edge.""" + fig.set_size_inches(width, height_in) + with warnings.catch_warnings(): + # the colorbar's axes is placed by hand (below), which + # `tight_layout` reports as an axes it cannot lay out + warnings.filterwarnings( + 'ignore', message='This figure includes Axes that are not ' + 'compatible with tight_layout') + # the panels were last laid out around their own legends, + # which are gone: one pass from there under-reserves a 3-D + # panel's title room (its box is aspect-constrained), a second + # settles it + for _ in range(3): + fig.tight_layout() + return max(0.0, _panels_right_edge_in(fig, panel_axes) - width) + + # what the last column draws right of its own box (a 3-D panel's + # z-axis label hangs in its right margin) must stay clear of the + # strip: the strip starts right of it + overhang_in = _lay_out(grid_in) if strip_in else 0.0 + if not strip_in: + _lay_out(grid_in) + elif widen: + total_in += overhang_in + else: for _ in range(3): - fig.tight_layout() - _grow_figure_rightward(fig, strip_in) - strip['rect_right'] = grid_in / (grid_in + strip_in) + if overhang_in <= 0.01 or grid_in <= 0.3 * total_in: + break + grid_in = max(grid_in - overhang_in, 0.3 * total_in) + overhang_in = _lay_out(grid_in) + _grow_figure_rightward(fig, total_in - grid_in) + strip['rect_right'] = (total_in - strip_in) / total_in if mappable is not None and not in_strip: _finish(fig.colorbar( mappable, ax=list(panel_axes), @@ -5062,6 +5082,27 @@ def _finish(cbar): return strip +def _panels_right_edge_in(fig, panel_axes): + """How far right (inches from the figure's left edge) the panels + `panel_axes` draw, measured on a real draw: each visible panel's box + and its axis labels (a 3-D panel's hang outside the box).""" + renderer = _measurement_renderer(fig) + right = 0.0 + for ax in panel_axes: + if not ax.get_visible(): + continue + boxes = [ax.get_window_extent(renderer)] + axis_map = getattr(ax, '_axis_map', None) or { + 'x': ax.xaxis, 'y': ax.yaxis} + for axis in axis_map.values(): + label = axis.label + if label.get_text() and label.get_visible(): + boxes.append(label.get_window_extent(renderer)) + right = max([right] + [float(box.x1) for box in boxes + if np.isfinite(box.x1)]) + return right / fig.dpi + + def _place_shared_furniture(fig, strip): """Position a grid's shared legend and colorbar (`strip`, from `_add_shared_furniture`) in the strip right of the panels: the legend @@ -13060,7 +13101,9 @@ def _finite_before(trace_index): if multicolor_hue is not None: line_colors = _multicolor_line_colors( multicolor_hue, pre_interp_lengths, xform, palette, - is_rgb=multicolor_hue_is_rgb, limits=_hue_limits) + is_rgb=multicolor_hue_is_rgb, + # only a `panels=` grid pins the range (its shared scale) + **({} if _hue_limits is None else {'limits': _hue_limits})) # handle explore flag (a real ValueError, not an assert -- asserts are # stripped under `python -O`, F01-016/F10-013) diff --git a/tests/test_panels_shared_legend_colors.py b/tests/test_panels_shared_legend_colors.py index 89547fad3..69128751e 100644 --- a/tests/test_panels_shared_legend_colors.py +++ b/tests/test_panels_shared_legend_colors.py @@ -187,6 +187,29 @@ def test_legend_kwargs_style_the_one_legend_and_can_place_it(): _quiet_plot(x, panels=True).get_size_inches()[0]) +def test_shared_legend_clears_a_3d_panels_axis_labels(): + """A 3-D panel's z-axis label hangs right of its box: the strip starts + right of the last column's label, not on top of it.""" + import pandas as pd + rng = np.random.default_rng(3) + x = [pd.DataFrame(rng.normal(size=(40, 3)).cumsum(0), + columns=['first axis', 'second axis', 'third axis']) + for _ in range(3)] + grid = _quiet_plot(x, reduce=None, legend=['a', 'b', 'c'], + panels=(1, 3), return_model=True) + fig = grid['fig'] + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + legend = _shared_legend(fig).get_window_extent(renderer) + assert legend.x1 <= fig.bbox.x1 + labels = [axis.label.get_window_extent(renderer) + for ax in grid['axes'] for axis in ax._axis_map.values() + if axis.label.get_text()] + assert len(labels) == 9 + for box in labels: + assert not box.overlaps(legend) + + def test_legend_false_or_absent_adds_nothing(): x = _walks() for kw in ({}, dict(legend=False), dict(legend=None)): From 916b81a05229b2a7334dee3aed706e5c204323d2 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 05:53:34 -0500 Subject: [PATCH 16/58] fix: internal analyze() calls are silent about a display ndims the data is below (GH #295) The Pipeline path of analyze() (return_model=True, manip=, cluster=) warned 'ndims/n_components was set to 3 but the data only has 2 feature(s)' for plot()'s own default ndims, so every panels= grid of 2-column data (and hyp.plot(two_column_data, return_model=True)) warned where the plain single-axes call is silent. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/tools/analyze.py | 67 ++++++++++++++++++++++++------------- 1 file changed, 44 insertions(+), 23 deletions(-) diff --git a/hypertools/tools/analyze.py b/hypertools/tools/analyze.py index 6d13b6497..c78120229 100644 --- a/hypertools/tools/analyze.py +++ b/hypertools/tools/analyze.py @@ -88,6 +88,32 @@ def pipeline_cluster_labels(pipeline, data): return labels, type(model), fitted, categories +def _fit_steps_capturing_data(pipe, data): + """Fit `pipe` (a Pipeline ending in a cluster step) on `data` and + return the data as it stood BEFORE the cluster step.""" + # analyze returns the TRANSFORMED DATA, not cluster labels, even + # when cluster= is given -- the labels live in the fitted + # 'cluster' step of the returned Pipeline (see `analyze`'s + # docstring). Fit the steps one at a time (exactly what + # Pipeline.fit_transform does), CAPTURING the pre-cluster data + # along the way: re-deriving it afterwards via .transform breaks + # for embedding models with no transform method (TSNE / MDS / + # SpectralEmbedding -- QC 2026-07: these crashed with + # "'TSNE' object has no attribute 'transform'" after all the + # fitting work was done). + result = data + for name, step in pipe.steps: + if name == 'cluster': + step.fit(result) + else: + result = step.fit_transform(result) + # every step is now fitted; mark the Pipeline itself fitted the + # same way Pipeline.fit_transform does, so it is reusable via + # .transform / pipeline= (there is no public "mark fitted" API) + pipe._is_fitted = True + return result + + def analyze(data, manip=None, normalize=None, reduce=None, ndims=None, align=None, cluster=None, pipeline=None, return_model=False, internal=False, impute=None, random_state=None): @@ -359,29 +385,24 @@ def analyze(data, manip=None, normalize=None, reduce=None, ndims=None, align=Non pipe = build_pipeline(manip=manip, normalize=normalize, reduce=reduce, ndims=ndims, align=align, cluster=cluster, random_state=random_state) - if cluster is None: - result = pipe.fit_transform(data) - else: - # analyze returns the TRANSFORMED DATA, not cluster labels, even - # when cluster= is given -- the labels live in the fitted - # 'cluster' step of the returned Pipeline (see this function's - # docstring). Fit the steps one at a time (exactly what - # Pipeline.fit_transform does), CAPTURING the pre-cluster data - # along the way: re-deriving it afterwards via .transform breaks - # for embedding models with no transform method (TSNE / MDS / - # SpectralEmbedding -- QC 2026-07: these crashed with - # "'TSNE' object has no attribute 'transform'" after all the - # fitting work was done). - result = data - for name, step in pipe.steps: - if name == 'cluster': - step.fit(result) - else: - result = step.fit_transform(result) - # every step is now fitted; mark the Pipeline itself fitted the - # same way Pipeline.fit_transform does, so it is reusable via - # .transform / pipeline= (there is no public "mark fitted" API) - pipe._is_fitted = True + with warnings.catch_warnings(): + if internal: + # an internal (display-path) call legitimately no-ops on + # data already at or below the display dimensionality, and + # the legacy chain below is silent about it + # (`reducer(..., internal=True)`); this Pipeline path -- + # taken for return_model=True, manip= or cluster= -- warned + # "ndims/n_components was set to 3 but the data only has 2 + # feature(s)" for an ndims= the caller never passed (every + # `hyp.plot(..., panels=)` grid of 2-column data, and + # `hyp.plot(two_column_data, return_model=True)`) + warnings.filterwarnings( + 'ignore', message=r'ndims/n_components was set to .* ' + r'but the data only has', category=UserWarning) + if cluster is None: + result = pipe.fit_transform(data) + else: + result = _fit_steps_capturing_data(pipe, data) if internal and not isinstance(result, list): result = [result] return (result, pipe) if return_model else result From ed5ff26f1dbcc68e1e88c1f7cad1a10a5f5b081d Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 05:53:34 -0500 Subject: [PATCH 17/58] fix: animated panel grids and caption=, review round 1 (GH #295) - animate={...} is resolved once, by the resolver plot() itself uses, before a grid splits its kwargs per panel: per-dataset values inside the dict are narrowed per panel and {'style': False} is a static grid - no datatype isinstance in the grid code (tests/test_datatype_gate.py) - a failed panels= call closes every figure it registered with pyplot - caption (and animated 3-D title) callables get the real frame-0 context; a static grid's caption gets the finished grid's (datasets, artists, axes, panels) - a grid caption's {index} is the reveal head of the panel drawing the first indexed dataset, so it matches that panel's title in every style - captions are wrapped to the figure width, per frame, with room for the first, middle and last frames' lines; an empty caption adds nothing - per-frame panel titles get their room in the grid layout Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/plot/plot.py | 620 ++++++++++++++++++--------- tests/test_animated_panels_review.py | 517 ++++++++++++++++++++++ 2 files changed, 943 insertions(+), 194 deletions(-) create mode 100644 tests/test_animated_panels_review.py diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index c2694b372..a40a10cdc 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -2054,6 +2054,130 @@ def _validate_extra_plot_kwargs(extra_kwargs): _INHERENTLY_SERIAL_STYLES = ('serial', 'morph') +#: the flat animation kwargs an ``animate={...}`` dict may carry, with each +#: one's literal default in `plot`'s signature +_ANIMATE_DICT_DEFAULTS = { + 'duration': 30, + 'tail_duration': 2, + 'rotations': 1, + 'zoom': 1, + 'chemtrails': False, + 'precog': False, + 'bullettime': False, + 'frame_rate': 30, + 'focused': None, + 'morph_samples': None, +} + + +def _resolve_animate_argument(animate, flat): + """Resolve `plot`'s ``animate=`` into ``(animate, flat)``: the style + (True/False/None, a style string, or a per-dataset morph list) and the + flat animation kwargs it implies. + + `flat` holds the call's own flat animation kwargs (the keys of + `_ANIMATE_DICT_DEFAULTS`); a copy is returned with an ``animate={...}`` + dict's entries and the trail-effect sugar styles + (``animate='chemtrails'`` etc.) folded in. This is the ONE place the + forms of ``animate=`` are understood: `plot` calls it at its top, and a + `panels=` grid calls it before it splits its kwargs per panel, so the + grid decides "animated" -- and narrows per-dataset values given inside + the dict -- exactly as the single-axes call does. + """ + flat = dict(flat) + # animate= dict form (GH #154 resolution): unpacked into the flat + # animation kwargs HERE, at the very top of the function, before + # anything else runs -- so every downstream code path (all of which + # predates this feature) only ever sees the flat kwargs it already + # understands; `animate` itself becomes the resolved style string/ + # bool/list from here on. `'style'` plays the role of `model` in + # hypertools' usual spec-dict grammar; every other key must be one of + # the flat animation kwargs below. A dict key CONFLICTING with the + # same flat kwarg passed explicitly (a different value) is almost + # certainly a mistake -- raise rather than silently pick one; compared + # against each flat kwarg's own LITERAL default (mirroring the + # pipeline=/stage-kwarg conflict check below) since there is no other + # way to tell "explicitly passed, coincidentally equal to the default" + # from "never passed" from inside the function body. + if isinstance(animate, dict): + if 'style' not in animate: + raise ValueError( + "animate= dict form requires a 'style' key naming the " + "animation style (e.g. animate={'style': 'spin', " + "'rotations': 2, 'duration': 15}); got a dict with keys " + f"{sorted(animate.keys())}." + ) + _animate_dict = dict(animate) + _animate_style = _animate_dict.pop('style') + _unknown_animate_keys = set(_animate_dict) - set(_ANIMATE_DICT_DEFAULTS) + if _unknown_animate_keys: + raise ValueError( + f"animate= dict got unknown key(s) " + f"{sorted(_unknown_animate_keys)}; valid keys are 'style' " + f"plus {sorted(_ANIMATE_DICT_DEFAULTS)}." + ) + _animate_flat_locals = dict(flat) + for _key, _dict_value in _animate_dict.items(): + _default_value = _ANIMATE_DICT_DEFAULTS[_key] + _flat_value = _animate_flat_locals[_key] + if _flat_value != _default_value and _flat_value != _dict_value: + raise ValueError( + f"animate= dict specifies {_key}={_dict_value!r} but " + f"{_key}={_flat_value!r} was also passed explicitly as " + f"a flat kwarg with a different value; pass {_key}= in " + "only one place (either inside animate= or as its own " + "kwarg)." + ) + for _key, _dict_value in _animate_dict.items(): + flat[_key] = _dict_value + animate = _animate_style + + # animate='chemtrails'/'precog'/'bullettime' sugar (QC 2026-07): these are + # trail EFFECTS, not animation styles. Historically, passing one as the + # animate STYLE silently produced a STATIC plot (the style whitelist in the + # matplotlib backend did not recognize them). Map each to animate='parallel' + # with the matching trail flag on -- what the effect actually needs (trails + # apply to animate=True/'parallel'). + if isinstance(animate, str) and animate in ('chemtrails', 'precog', + 'bullettime'): + flat[animate] = True + animate = 'parallel' + + # validate the animate style: an unrecognized string used to fall through + # to a silent static plot (QC 2026-07). Fail fast with a clear message. + if isinstance(animate, str) and animate not in ('parallel', 'spin', + 'serial', 'morph', 'window'): + raise ValueError( + f"unknown animate style {animate!r}; valid styles are 'parallel', " + "'spin', 'serial', 'morph', 'window' (or True/False). The trail " + "effects 'chemtrails'/'precog'/'bullettime' are boolean kwargs, not " + "styles -- e.g. animate='parallel', chemtrails=True.") + + # non-bool/non-string scalars (release-1.0 audit, F04-006/F05-004): + # anything ==True/==False (np.True_, 1, 0, ...) is normalized to a real + # bool; every OTHER scalar (e.g. animate=2 -- perhaps meant as + # "2 rotations"?) used to slip past the string whitelist above, silently + # render a STATIC plot (the backend dispatch is `animate in [True, + # 'parallel', ...]`), and then crash with `AttributeError: 'NoneType' + # object has no attribute 'save'` if save_path= was also set. + if isinstance(animate, np.ndarray): + animate = animate.tolist() # per-dataset morph tags as an array + if animate is not None and not isinstance(animate, (bool, str, dict, + list, tuple)): + if animate == True or animate == False: # noqa: E712 (np.bool_/0/1) + animate = bool(animate) + else: + raise ValueError( + f"animate={animate!r} is not a recognized animate value; " + "use True/False, a style string ('parallel', 'spin', " + "'serial', 'morph', 'window', or the sugar styles " + "'chemtrails'/'precog'/'bullettime'), the dict form " + "(animate={'style': ..., ...}), or a per-dataset list for " + "animate='morph'. For extra camera rotations, pass " + "rotations= instead.") + return animate, flat + + def _raw_animate_style(animate): """The STYLE `animate=` names, before dataset-count-dependent resolution. @@ -2912,9 +3036,27 @@ def _make_title_pattern_resolver(pattern, row_indices, name='title'): if row_indices is not None: index = next((i for i in row_indices if i is not None), None) + #: which input carries that index: in a one-panel-per-dataset grid, + #: the panel that draws it + position = 0 + if row_indices is not None: + position = next((k for k, i in enumerate(row_indices) + if i is not None), 0) + def _resolve(ctx): if index is None: return pattern + if ctx.panels: + # a `panels=` grid's own context (a grid-level `caption=`): + # the reveal head is a PANEL's, so the pattern shows the index + # that panel's own `title='{index}'` shows. The panel read is + # the one drawing the dataset whose index this is (the first + # dataset that carries one) -- or the first panel, when every + # panel draws every dataset (a list-valued `reduce=`). Panels + # whose own indexes or lengths differ therefore never make + # this ambiguous: one panel is read, by this rule. + ctx = ctx.panels[position + if len(ctx.panels) == len(row_indices) else 0] value = index[_title_head_row(ctx, len(index))] try: return pattern.format(index=value) @@ -4329,6 +4471,10 @@ def _validate_caption(caption, row_indices, backend_name, ax=None): return None, None if isinstance(caption, bytes): caption = caption.decode('utf-8') + if isinstance(caption, str) and not caption.strip(): + # an empty caption is no caption: nothing is drawn and no room is + # made for it + return None, None if not (isinstance(caption, str) or callable(caption)): raise TypeError( "caption= must be a string, a '{index...}' format pattern, or a " @@ -4413,18 +4559,107 @@ def _blank_bottom_in(fig): return max(0.0, bottom) -def _add_caption(fig, text, font=None, family=None): +#: blank room (inches) kept between the caption and the canvas' side edges +_CAPTION_SIDE_PAD_IN = 0.1 + + +def _caption_sample_frames(n_frames): + """The frames whose captions size an animated caption's room: the + first, the middle and the last (see `_add_caption`).""" + n_frames = max(int(n_frames), 1) + return sorted({0, n_frames // 2, n_frames - 1}) + + +def _static_axes_artists(ax): + """The data artists a finished static axes holds (its lines, then its + collections): a static plot's ``FrameContext.artists``.""" + if ax is None: + return () + return tuple(ax.lines) + tuple(ax.collections) + + +def _wrap_caption(artist, text): + """`text` broken into lines no wider than the caption's figure (less + `_CAPTION_SIDE_PAD_IN` on each side), measured in the caption's own + font on the figure's renderer. + + Lines break at spaces; a single word wider than the figure is broken + between characters. The caller's own ``'\n'`` line breaks are kept. A + line holding mathtext (``$...$``) is left whole: breaking it could + split a formula. + """ + fig = artist.figure + renderer = _measurement_renderer(fig) + room_px = (fig.get_size_inches()[0] - 2 * _CAPTION_SIDE_PAD_IN) * fig.dpi + shown, visible = artist.get_text(), artist.get_visible() + # (an invisible Text reports no extent) + artist.set_visible(True) + + def _fits(candidate): + artist.set_text(candidate) + return artist.get_window_extent(renderer).width <= room_px + + lines = [] + try: + for paragraph in str(text).split('\n'): + if paragraph.count('$') >= 2 or _fits(paragraph): + lines.append(paragraph) + continue + current = '' + for word in paragraph.split(' '): + trial = word if not current else current + ' ' + word + if _fits(trial): + current = trial + continue + if current: + lines.append(current) + while len(word) > 1 and not _fits(word): + # the longest leading piece of the word that fits + low, high = 1, len(word) - 1 + while low < high: + middle = (low + high + 1) // 2 + if _fits(word[:middle]): + low = middle + else: + high = middle - 1 + lines.append(word[:low]) + word = word[low:] + current = word + lines.append(current) + finally: + artist.set_text(shown) + artist.set_visible(visible) + return '\n'.join(lines) + + +def _set_caption_text(artist, text): + """Show `text` in the caption `artist`, wrapped to its figure's width + (`_wrap_caption`): how every frame of a per-frame caption is set.""" + artist.set_text(_wrap_caption(artist, text)) + + +def _add_caption(fig, text, font=None, family=None, samples=()): """Draw `text` as `fig`'s caption (GH #295) and return its ``Text``. The caption is centered under everything the figure holds, a small gap - below the lowest thing drawn (`_blank_bottom_in`). Where the figure has - no blank room there for it -- an animated 3-D plot fills its canvas -- - the figure grows downward by what is missing + below the lowest thing drawn (`_blank_bottom_in`). It is WRAPPED to + the figure's width (`_wrap_caption`), so it never leaves the canvas at + the sides however long it is. Where the figure has no blank room + under its content for the wrapped text -- an animated 3-D plot fills + its canvas -- the figure grows downward by what is missing (`_grow_figure_downward`), so the caption never overlaps a panel, a legend, a colorbar or a companion panel and always lies inside the - canvas. The room is sized for the number of lines `text` has; a - per-frame caption should keep that many lines (or fewer) on every - frame. + canvas. + + HOW THE ROOM'S HEIGHT IS DECIDED. The room holds as many lines as the + tallest of `text` and `samples` has once wrapped. `text` is what the + figure shows now: a fixed caption, a static figure's resolved one, or + frame 0's. `samples` are a per-frame caption's texts on the frames + `_caption_sample_frames` names (first, middle, last), so a caption + that gets longer as the animation runs has its room from the start. A + frame in between whose caption wraps to MORE lines than all three is + still wrapped to the figure's width, and its extra lines run below the + reserved room. `font` is the resolved explicit ``font=`` (a ``FontProperties``), and `family` the fallback font stack used without one -- the caption is @@ -4437,7 +4672,15 @@ def _add_caption(fig, text, font=None, family=None): else: props = FontProperties(family=family or sans_serif_stack()) props.set_size(plt.rcParams['font.size']) - n_lines = text.count('\n') + 1 + # placed for good below, once its wrapped height is known + artist = fig.text(0.5, 0.0, '', ha='center', va='top', + fontproperties=props, gid=CAPTION_GID) + # excluded from the "lowest thing drawn" measurement + artist.set_visible(False) + wrapped = _wrap_caption(artist, text) + n_lines = max(candidate.count('\n') + 1 for candidate in + [wrapped] + [_wrap_caption(artist, str(sample)) + for sample in samples]) line_in = 1.2 * props.get_size_in_points() / 72.0 strip_in = n_lines * line_in + 2 * _CAPTION_PAD_IN blank_in = _blank_bottom_in(fig) @@ -4445,9 +4688,9 @@ def _add_caption(fig, text, font=None, family=None): _grow_figure_downward(fig, strip_in - blank_in) blank_in = strip_in _, h_in = fig.get_size_inches() - artist = fig.text(0.5, (blank_in - _CAPTION_PAD_IN) / h_in, text, - ha='center', va='top', fontproperties=props, - gid=CAPTION_GID) + artist.set_position((0.5, (blank_in - _CAPTION_PAD_IN) / h_in)) + artist.set_text(wrapped) + artist.set_visible(True) return artist @@ -4675,7 +4918,9 @@ def _walk(value): if not is_missing_label(value) and str(value) not in out: out.append(str(value)) return - for item in (value.tolist() if isinstance(value, np.ndarray) + # (numpy and pandas containers give plain Python labels) + for item in (value.tolist() if callable(getattr(value, 'tolist', + None)) else list(value)): _walk(item) @@ -5129,6 +5374,24 @@ def _place_shared_furniture(fig, strip): def _plot_panels(x, panels, call_kwargs, _name='panels'): + """`_plot_panels_impl` (the `panels=` implementation), leaving no figure + behind when it fails: whatever the reason a grid call raises -- a + refused combination, a panel's own error, a caption or title callable + that raises, a failed save -- every figure the call registered with + pyplot on the way is closed before the exception leaves, with + ``show=True`` as with ``show=False``. ``plt.get_fignums()`` after a + failed call is what it was before it.""" + before = set(plt.get_fignums()) + try: + return _plot_panels_impl(x, panels, call_kwargs, _name=_name) + except BaseException: + for number in plt.get_fignums(): + if number not in before: + plt.close(number) + raise + + +def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): """Draw one panel per dataset (or per `reduce=` entry) in a single figure -- the implementation behind `hyp.plot(..., panels=)`. With `animate=` the panels are animated together, on one clock, by a single @@ -5147,9 +5410,18 @@ def _plot_panels(x, panels, call_kwargs, _name='panels'): Each panel's box is scaled to its own contents, exactly as a per-panel `hyp.plot(..., ax=ax)` call is today. """ - _animate = call_kwargs.get('animate') - animated = (isinstance(_animate, (list, tuple, dict, np.ndarray)) - or bool(_animate)) + # `animate=` is resolved the way `plot()` itself resolves it, BEFORE the + # kwargs are split per panel: an ``animate={...}`` dict is unpacked into + # the flat animation kwargs (so a per-dataset value inside it, e.g. + # ``'chemtrails': [True, False]``, is narrowed per panel like the flat + # kwarg), and ``{'style': False}`` is the static grid it asks for + call_kwargs = dict(call_kwargs) + _animate, _animate_flat = _resolve_animate_argument( + call_kwargs.get('animate'), + {key: call_kwargs.get(key, default) + for key, default in _ANIMATE_DICT_DEFAULTS.items()}) + call_kwargs.update(_animate_flat, animate=_animate) + animated = isinstance(_animate, (list, tuple)) or bool(_animate) backend = resolve_backend(call_kwargs.get('backend', 'auto')) if animated and backend == 'plotly': raise NotImplementedError( @@ -5622,8 +5894,11 @@ def _draw_grid(consolidate): # a static grid's caption: fixed text, or the dynamic forms # resolved once for the finished figure (as a dynamic title= is on # a static plot) - _add_grid_caption(fig, caption, dynamic_caption, panel_axes, - call_kwargs.get('font')) + _add_grid_caption( + fig, caption, dynamic_caption, call_kwargs.get('font'), + context=(_static_grid_context( + fig, panel_axes, panel_xforms, order='parallel') + if dynamic_caption is not None else None)) # the caption's room was added under the grid: re-center the # shared legend/colorbar on the panels _place_shared_furniture(fig, strip) @@ -5691,21 +5966,54 @@ def _grid_caption_font(font, text): extra=resolved.get_name() if resolved is not None else None) -def _add_grid_caption(fig, caption, dynamic_caption, panel_axes, font, - context=None): +def _add_grid_caption(fig, caption, dynamic_caption, font, context, + sample_contexts=()): """Draw a panel grid's caption and return its ``Text``. A dynamic caption (pattern or callable) is resolved for `context` -- frame 0 of - an animated grid -- or, without one, for the finished static figure.""" - text = caption + an animated grid (`_panel_grid_context`), or the finished static + figure (`_static_grid_context`) -- and its room is sized for that text + and for `sample_contexts`' (see `_add_caption`).""" + text, samples = caption, [] if dynamic_caption is not None: - if context is None: - context = FrameContext( - frame=None, n_frames=None, figure=fig, - axes=tuple(panel_axes), style=False, progress=1.0) text = _resolve_dynamic_title_text(dynamic_caption, context, name='caption') + samples = [_resolve_dynamic_title_text(dynamic_caption, sample, + name='caption') + for sample in sample_contexts] resolved_font, family = _grid_caption_font(font, text) - return _add_caption(fig, text, font=resolved_font, family=family) + return _add_caption(fig, text, font=resolved_font, family=family, + samples=samples) + + +def _static_grid_context(fig, panel_axes, panel_rows, order=None): + """The `FrameContext` of a FINISHED static panel grid, for a dynamic + `caption=`: the static counterpart of `_panel_grid_context`. + + `panel_rows` holds, per panel, the analyzed rows of every dataset the + panel draws. As for any static plot, ``frame``/``n_frames`` are None + and ``progress`` is 1.0; ``panels`` holds one such context per panel + (its own ``axes``, its data ``artists``, its ``datasets``, and every + row revealed), and the grid's own ``axes``/``artists``/``datasets``/ + ``revealed_counts``/``window_bounds`` are the panels' in panel order. + """ + def _context(axes, artists, datasets, panels=()): + return FrameContext( + frame=None, n_frames=None, figure=fig, axes=axes, + artists=tuple(artists), datasets=tuple(datasets), style=False, + order=order, + revealed_counts=tuple(len(d) for d in datasets), + window_bounds=tuple((0, len(d)) for d in datasets), + progress=1.0, panels=tuple(panels)) + + panel_contexts = [ + _context(ax, _static_axes_artists(ax), + [np.asarray(rows) for rows in datasets]) + for ax, datasets in zip(panel_axes, panel_rows)] + return _context( + tuple(panel_axes), + [artist for ctx in panel_contexts for artist in ctx.artists], + [rows for ctx in panel_contexts for rows in ctx.datasets], + panels=panel_contexts) def _panel_grid_context(fig, cells, frame, n_frames): @@ -5963,13 +6271,19 @@ def _draw_panels(num): caption_artist = None if caption is not None or dynamic_caption is not None: try: - # frame 0's text sizes the caption strip, and is what a still - # of the figure shows; the panels are drawn at frame 0 to get - # its context (frames are idempotent, see `FrameContext`) + # frame 0's text is what a still of the figure shows, and with + # the middle and last frames' it sizes the caption's room; the + # panels are drawn at each to get its real context (frames are + # idempotent, see `FrameContext`) + contexts = ([_draw_panels(frame) + for frame in _caption_sample_frames(n_frames)] + if dynamic_caption is not None else [None]) caption_artist = _add_grid_caption( - fig, caption, dynamic_caption, panel_axes, font, + fig, caption, dynamic_caption, font, context=(_draw_panels(0) if dynamic_caption is not None - else None)) + else None), + sample_contexts=contexts if dynamic_caption is not None + else ()) _place_shared_furniture(fig, strip) except Exception: _abandon() @@ -5978,7 +6292,7 @@ def _draw_panels(num): def _grid_frame(num, *_): context = _draw_panels(num) if dynamic_caption is not None: - caption_artist.set_text(_resolve_dynamic_title_text( + _set_caption_text(caption_artist, _resolve_dynamic_title_text( dynamic_caption, context, name='caption')) for callback in grid_hooks.callbacks: callback(context) @@ -9556,132 +9870,28 @@ def plot( # that drops the drawn legend (a continuous hue; `_plotly_hover_names`) _legend_user_labels = list(legend) if _legend_user_list else None - # animate= dict form (GH #154 resolution): unpacked into the flat - # animation kwargs HERE, at the very top of the function, before - # anything else runs -- so every downstream code path (all of which - # predates this feature) only ever sees the flat kwargs it already - # understands; `animate` itself becomes the resolved style string/ - # bool/list from here on. `'style'` plays the role of `model` in - # hypertools' usual spec-dict grammar; every other key must be one of - # the flat animation kwargs below. A dict key CONFLICTING with the - # same flat kwarg passed explicitly (a different value) is almost - # certainly a mistake -- raise rather than silently pick one; compared - # against each flat kwarg's own LITERAL default (mirroring the - # pipeline=/stage-kwarg conflict check below) since there is no other - # way to tell "explicitly passed, coincidentally equal to the default" - # from "never passed" from inside the function body. - if isinstance(animate, dict): - _ANIMATE_DICT_DEFAULTS = { - 'duration': 30, - 'tail_duration': 2, - 'rotations': 1, - 'zoom': 1, - 'chemtrails': False, - 'precog': False, - 'bullettime': False, - 'frame_rate': 30, - 'focused': None, - 'morph_samples': None, - } - if 'style' not in animate: - raise ValueError( - "animate= dict form requires a 'style' key naming the " - "animation style (e.g. animate={'style': 'spin', " - "'rotations': 2, 'duration': 15}); got a dict with keys " - f"{sorted(animate.keys())}." - ) - _animate_dict = dict(animate) - _animate_style = _animate_dict.pop('style') - _unknown_animate_keys = set(_animate_dict) - set(_ANIMATE_DICT_DEFAULTS) - if _unknown_animate_keys: - raise ValueError( - f"animate= dict got unknown key(s) " - f"{sorted(_unknown_animate_keys)}; valid keys are 'style' " - f"plus {sorted(_ANIMATE_DICT_DEFAULTS)}." - ) - _animate_flat_locals = { - 'duration': duration, - 'tail_duration': tail_duration, - 'rotations': rotations, - 'zoom': zoom, - 'chemtrails': chemtrails, - 'precog': precog, - 'bullettime': bullettime, - 'frame_rate': frame_rate, - 'focused': focused, - 'morph_samples': morph_samples, - } - for _key, _dict_value in _animate_dict.items(): - _default_value = _ANIMATE_DICT_DEFAULTS[_key] - _flat_value = _animate_flat_locals[_key] - if _flat_value != _default_value and _flat_value != _dict_value: - raise ValueError( - f"animate= dict specifies {_key}={_dict_value!r} but " - f"{_key}={_flat_value!r} was also passed explicitly as " - f"a flat kwarg with a different value; pass {_key}= in " - "only one place (either inside animate= or as its own " - "kwarg)." - ) - duration = _animate_dict.get('duration', duration) - tail_duration = _animate_dict.get('tail_duration', tail_duration) - rotations = _animate_dict.get('rotations', rotations) - zoom = _animate_dict.get('zoom', zoom) - chemtrails = _animate_dict.get('chemtrails', chemtrails) - precog = _animate_dict.get('precog', precog) - bullettime = _animate_dict.get('bullettime', bullettime) - frame_rate = _animate_dict.get('frame_rate', frame_rate) - focused = _animate_dict.get('focused', focused) - morph_samples = _animate_dict.get('morph_samples', morph_samples) - animate = _animate_style - - # animate='chemtrails'/'precog'/'bullettime' sugar (QC 2026-07): these are - # trail EFFECTS, not animation styles. Historically, passing one as the - # animate STYLE silently produced a STATIC plot (the style whitelist in the - # matplotlib backend did not recognize them). Map each to animate='parallel' - # with the matching trail flag on -- what the effect actually needs (trails - # apply to animate=True/'parallel'). - if isinstance(animate, str) and animate in ('chemtrails', 'precog', - 'bullettime'): - if animate == 'chemtrails': - chemtrails = True - elif animate == 'precog': - precog = True - else: - bullettime = True - animate = 'parallel' - - # validate the animate style: an unrecognized string used to fall through - # to a silent static plot (QC 2026-07). Fail fast with a clear message. - if isinstance(animate, str) and animate not in ('parallel', 'spin', - 'serial', 'morph', 'window'): - raise ValueError( - f"unknown animate style {animate!r}; valid styles are 'parallel', " - "'spin', 'serial', 'morph', 'window' (or True/False). The trail " - "effects 'chemtrails'/'precog'/'bullettime' are boolean kwargs, not " - "styles -- e.g. animate='parallel', chemtrails=True.") - - # non-bool/non-string scalars (release-1.0 audit, F04-006/F05-004): - # anything ==True/==False (np.True_, 1, 0, ...) is normalized to a real - # bool; every OTHER scalar (e.g. animate=2 -- perhaps meant as - # "2 rotations"?) used to slip past the string whitelist above, silently - # render a STATIC plot (the backend dispatch is `animate in [True, - # 'parallel', ...]`), and then crash with `AttributeError: 'NoneType' - # object has no attribute 'save'` if save_path= was also set. - if isinstance(animate, np.ndarray): - animate = animate.tolist() # per-dataset morph tags as an array - if animate is not None and not isinstance(animate, (bool, str, dict, - list, tuple)): - if animate == True or animate == False: # noqa: E712 (np.bool_/0/1) - animate = bool(animate) - else: - raise ValueError( - f"animate={animate!r} is not a recognized animate value; " - "use True/False, a style string ('parallel', 'spin', " - "'serial', 'morph', 'window', or the sugar styles " - "'chemtrails'/'precog'/'bullettime'), the dict form " - "(animate={'style': ..., ...}), or a per-dataset list for " - "animate='morph'. For extra camera rotations, pass " - "rotations= instead.") + # animate= dict form (GH #154 resolution), the trail-effect sugar + # styles and scalar normalization: resolved HERE, at the very top of the + # function, before anything else runs -- so every downstream code path + # only ever sees the flat kwargs it already understands; `animate` + # itself becomes the resolved style string/bool/list from here on (see + # `_resolve_animate_argument`, which a `panels=` grid calls too). + animate, _animate_flat = _resolve_animate_argument(animate, { + 'duration': duration, 'tail_duration': tail_duration, + 'rotations': rotations, 'zoom': zoom, 'chemtrails': chemtrails, + 'precog': precog, 'bullettime': bullettime, + 'frame_rate': frame_rate, 'focused': focused, + 'morph_samples': morph_samples}) + duration = _animate_flat['duration'] + tail_duration = _animate_flat['tail_duration'] + rotations = _animate_flat['rotations'] + zoom = _animate_flat['zoom'] + chemtrails = _animate_flat['chemtrails'] + precog = _animate_flat['precog'] + bullettime = _animate_flat['bullettime'] + frame_rate = _animate_flat['frame_rate'] + focused = _animate_flat['focused'] + morph_samples = _animate_flat['morph_samples'] # fail-fast on hue_mode= for the same reason title= fails fast here: a # typo or a contradictory pair should not survive the reduce pipeline. @@ -14760,6 +14970,16 @@ def _hyp_frame_with_hooks(num, *fargs, line_ani._func = _hyp_frame_with_hooks + def _real_frame_context(frame): + """Draw `frame` of the animation (its updater only: no + internal or user hook runs) and return that frame's REAL + `FrameContext`, the one an `on_frame=` callback receives + for it. Frames are idempotent (see `FrameContext`), so + drawing one here changes nothing a later draw shows.""" + _orig_frame_func(int(frame), *line_ani._args) + return FrameContext(figure=fig, axes=ax, + **_frame_hooks.state) + # title= per-segment sequence (plan 1.1 Task 8): registered on # the SAME `_frame_hooks` registry as `on_frame=` (added last # above, so this callback also only ever sees final artists -- @@ -14791,8 +15011,9 @@ def _hyp_frame_with_hooks(num, *fargs, or _dynamic_title is not None or on_frame is not None)): # a dynamic (callable / `{index...}`) title has no text yet: - # resolve FRAME 0's, purely to count its lines. That is a - # real frame-0 context, not a synthetic one, and the + # resolve FRAME 0's, purely to count its lines. That is the + # real frame-0 context (`_real_frame_context`: the frame is + # drawn to get it), not a synthetic one, and the # resolver is a pure function of the context by contract # (`FrameContext`), so this cannot disagree with what the # per-frame updater will set a moment later -- and if the @@ -14803,16 +15024,7 @@ def _hyp_frame_with_hooks(num, *fargs, try: _probe_title = _wrap_title_text( _resolve_dynamic_title_text( - _dynamic_title, FrameContext( - frame=0, - n_frames=int(line_ani._save_count), - figure=fig, axes=ax, - datasets=tuple(xform), - style=animate, order=order, - current_index=(0 if order == 'serial' - else None), - revealed_counts=tuple( - 1 for _ in xform))), + _dynamic_title, _real_frame_context(0)), _title_wrap, _wrap_break) except Exception: # the user's title raised before the animation @@ -14866,6 +15078,15 @@ def _hyp_frame_with_hooks(num, *fargs, for _artist in (list(ax.lines) + list(ax.collections) + list(ax.patches)): _artist.set_in_layout(False) + if _dynamic_title is not None and line_ani is not None: + # a per-frame title (callable or `{index...}` pattern) + # has no text until a frame is drawn, so the layout + # below reserved no room for it and every frame's + # title was then drawn off the top of the canvas (top + # row) or over the x-axis labels of the row above: + # draw frame 0, whose title the layout then arranges + # like a fixed one + line_ani._func(0, *line_ani._args) if ((not animate or _panel_animation is not None) and not _caller_figure and isinstance(fig, plt.Figure)): @@ -14975,29 +15196,39 @@ def _update_companions(ctx, _drawn=_panels_drawn): if (caption is not None or _dynamic_caption is not None) \ and isinstance(fig, plt.Figure): _caption_text = caption + _caption_samples = () + _animated_caption = bool(animate) and line_ani is not None if _dynamic_caption is not None: - _static_ctx = not animate or line_ani is None try: - _caption_text = _resolve_dynamic_title_text( - _dynamic_caption, FrameContext( - frame=None if _static_ctx else 0, - n_frames=(None if _static_ctx - else int(line_ani._save_count)), - figure=fig, axes=ax, - datasets=tuple(xform), - style=animate if animate else False, - order=order, - current_index=( - 0 if order == 'serial' - and not _static_ctx else None), - revealed_counts=tuple( - len(d) if _static_ctx else 1 - for d in xform), - window_bounds=( - tuple((0, len(d)) for d in xform) - if _static_ctx else None), - progress=1.0 if _static_ctx else None), - name='caption') + if _animated_caption: + # the REAL contexts of the first, middle and + # last frames (each is drawn to get it): frame + # 0's text is what a still shows, and the three + # together size the caption's room + _n = int(line_ani._save_count) + _caption_samples = [ + _resolve_dynamic_title_text( + _dynamic_caption, + _real_frame_context(_frame), + name='caption') + for _frame in _caption_sample_frames(_n)] + _real_frame_context(0) + _caption_text = _caption_samples[0] + else: + # a static plot: the finished figure + _caption_text = _resolve_dynamic_title_text( + _dynamic_caption, FrameContext( + frame=None, n_frames=None, + figure=fig, axes=ax, + artists=_static_axes_artists(ax), + datasets=tuple(xform), + style=False, order=order, + revealed_counts=tuple( + len(d) for d in xform), + window_bounds=tuple( + (0, len(d)) for d in xform), + progress=1.0), + name='caption') except Exception: # see the dynamic-title probe above: the user's # callable raised before any animation was handed @@ -15011,11 +15242,12 @@ def _update_companions(ctx, _drawn=_panels_drawn): raise _caption_artist = _add_caption( fig, _caption_text, font=_artist_font, - family=list(plt.rcParams['font.family'])) - if _dynamic_caption is not None and line_ani is not None: + family=list(plt.rcParams['font.family']), + samples=_caption_samples) + if _dynamic_caption is not None and _animated_caption: def _update_caption(ctx, _fn=_dynamic_caption, _artist=_caption_artist): - _artist.set_text(_resolve_dynamic_title_text( + _set_caption_text(_artist, _resolve_dynamic_title_text( _fn, ctx, name='caption')) _frame_hooks.add_internal(_update_caption) diff --git a/tests/test_animated_panels_review.py b/tests/test_animated_panels_review.py new file mode 100644 index 000000000..1270972aa --- /dev/null +++ b/tests/test_animated_panels_review.py @@ -0,0 +1,517 @@ +"""Review round 1 of animated panel grids and `caption=` (GH #295). + +Every test here reproduces a defect two reviewers and the full suite found +in the first cut of the feature, on real figures and real frames rendered +headless (nothing is mocked or patched): `animate={...}` dictionaries in a +grid, the contexts a caption callable receives, figures left registered +with pyplot after a failed grid call, a grid caption's `{index}` against +its panels' titles, captions wider than the figure, an empty caption, +per-frame panel titles clipped off the canvas, and a warning only the grid +raised. +""" +import warnings + +import matplotlib +matplotlib.use('Agg') + +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +import pytest + +import hypertools as hyp +from hypertools.plot.plot import CAPTION_GID + + +def _walk(seed, rows=20, cols=3): + rng = np.random.default_rng(seed) + return np.cumsum(rng.normal(size=(rows, cols)), axis=0) + + +X = _walk(0) +DATA = [_walk(seed) for seed in range(4)] +DATES = pd.date_range('2024-01-01', periods=20, freq='D') +FRAMES = [pd.DataFrame(d, index=DATES) for d in DATA] +ANIM = dict(animate=True, duration=1, frame_rate=4, show=False) + + +@pytest.fixture(autouse=True) +def _close_figures(): + yield + plt.close('all') + + +def _caption(fig): + found = fig.findobj(lambda a: a.get_gid() == CAPTION_GID) + assert len(found) == 1 + return found[0] + + +def _extent(fig, artist): + """`artist`'s drawn box as figure fractions ``(x0, y0, x1, y1)``.""" + fig.canvas.draw() + box = artist.get_window_extent(fig.canvas.get_renderer()) + width, height = fig.canvas.get_width_height() + return (box.x0 / width, box.y0 / height, box.x1 / width, + box.y1 / height) + + +# -------------------------------------------------------------------------- +# C1 / S1: animate={...} in a grid +# -------------------------------------------------------------------------- + +def test_animate_dict_per_dataset_values_are_split_per_panel(): + """A per-dataset list inside `animate={...}` is narrowed per panel, + exactly as the same list passed as the flat kwarg is.""" + in_dict = hyp.plot( + [X, X], panels=True, duration=1, frame_rate=4, show=False, + animate={'style': True, 'chemtrails': [True, False]}) + flat = hyp.plot([X, X], panels=True, chemtrails=[True, False], **ANIM) + assert in_dict.n_frames == flat.n_frames == 4 + in_dict.draw_frame(3) + flat.draw_frame(3) + for ax_dict, ax_flat in zip(in_dict.figure.axes, flat.figure.axes): + assert len(ax_dict.lines) == len(ax_flat.lines) + # the first panel draws a trail the second does not + counts = [len(ax.lines) for ax in in_dict.figure.axes[:2]] + assert counts[0] > counts[1] + + +def test_animate_dict_with_a_false_style_is_a_static_grid(): + fig = hyp.plot([X, X], panels=True, animate={'style': False}, + show=False) + assert isinstance(fig, plt.Figure) + assert len(fig.axes) == 2 + + +def test_animate_dict_settings_reach_every_panel(): + anim = hyp.plot([X, X], panels=True, show=False, + animate={'style': 'spin', 'duration': 1, + 'frame_rate': 6}) + assert anim.n_frames == 6 + + +def test_animate_dict_conflicting_with_a_flat_kwarg_raises_in_a_grid(): + with pytest.raises(ValueError, match='only one place'): + hyp.plot([X, X], panels=True, show=False, duration=3, + animate={'style': True, 'duration': 1}) + + +# -------------------------------------------------------------------------- +# C2: the context a caption callable receives +# -------------------------------------------------------------------------- + +def test_animated_caption_callable_gets_the_real_first_frame_context(): + """The context a caption is first resolved with (at construction) is + the one frame 0 delivers to an `on_frame=` callback.""" + seen, delivered = [], [] + + def caption(ctx): + seen.append(ctx) + return f'{ctx.window_bounds[0]} {len(ctx.artists)}' + + anim = hyp.plot(X, caption=caption, on_frame=delivered.append, **ANIM) + first = seen[0] + assert first.frame == 0 and first.n_frames == anim.n_frames + assert first.window_bounds is not None and len(first.artists) >= 1 + assert first.figure is anim.figure + delivered.clear() + anim.draw_frame(0) + assert first.window_bounds == delivered[0].window_bounds + assert first.revealed_counts == delivered[0].revealed_counts + assert len(first.artists) == len(delivered[0].artists) + assert first.style == delivered[0].style + + +def test_animated_3d_title_callable_gets_the_real_first_frame_context(): + seen = [] + + def title(ctx): + seen.append(ctx) + return f'{ctx.window_bounds[0][1]}' + + hyp.plot(X, title=title, **ANIM) + assert seen[0].frame == 0 + assert seen[0].window_bounds is not None and seen[0].artists + + +def test_static_grid_caption_callable_gets_the_finished_grid(): + seen = [] + + def caption(ctx): + seen.append(ctx) + return f'{len(ctx.datasets[0])} rows' + + fig = hyp.plot(DATA, panels=(2, 2), caption=caption, show=False) + assert _caption(fig).get_text() == '20 rows' + ctx = seen[0] + assert ctx.frame is None and ctx.n_frames is None + assert ctx.progress == 1.0 + assert ctx.figure is fig + assert list(ctx.axes) == fig.axes[:4] + assert len(ctx.datasets) == 4 + assert all(d.shape == (20, 3) for d in ctx.datasets) + assert ctx.revealed_counts == (20, 20, 20, 20) + assert ctx.window_bounds == ((0, 20),) * 4 + assert len(ctx.panels) == 4 + for panel, ax in zip(ctx.panels, fig.axes): + assert panel.axes is ax + assert len(panel.datasets) == 1 and panel.revealed_counts == (20,) + assert panel.artists and all( + artist.axes is ax for artist in panel.artists) + assert len(ctx.artists) == sum(len(p.artists) for p in ctx.panels) + + +def test_static_single_plot_caption_callable_gets_the_drawn_artists(): + seen = [] + fig = hyp.plot(X, show=False, + caption=lambda ctx: seen.append(ctx) or 'done') + assert seen[0].figure is fig and seen[0].axes is fig.axes[0] + assert seen[0].artists + assert all(a.axes is fig.axes[0] for a in seen[0].artists) + + +def test_animated_grid_caption_first_context_is_frame_zero_of_the_grid(): + seen = [] + + def caption(ctx): + seen.append(ctx) + return str(ctx.frame) + + anim = hyp.plot(DATA, panels=(1, 4), caption=caption, **ANIM) + assert _caption(anim.figure).get_text() == '0' + assert all(len(ctx.panels) == 4 and len(ctx.datasets) == 4 + and ctx.artists for ctx in seen) + + +# -------------------------------------------------------------------------- +# C3: a failed grid call leaves no figure behind +# -------------------------------------------------------------------------- + +def _raises(ctx): + raise RuntimeError('caption failed') + + +FAILING_GRID_CALLS = { + 'morph, one dataset per panel': dict(animate='morph'), + 'caption returns a number': dict(animate=True, caption=lambda ctx: 3), + 'caption raises': dict(animate=True, caption=_raises), + 'static caption raises': dict(caption=_raises), + 'static caption returns a number': dict(caption=lambda ctx: 3), + 'unknown forecaster, animated': dict(animate=True, predict='Nope'), + 'unknown forecaster, static': dict(predict='Nope'), + 'morph with a forecast': dict(animate='morph', predict='Kalman'), + 'title raises, animated': dict(animate=True, title=_raises), + 'title raises, static': dict(title=_raises), + 'on_frame not callable': dict(animate=True, on_frame=3), + 'unknown style': dict(animate='nope'), + 'unknown reducer': dict(reduce='NoSuchReducer'), + 'bad format string': dict(fmt='not-a-format'), + 'per-dataset list too long': dict(animate=True, + chemtrails=[True, False, True]), + 'bad save extension, animated': dict(animate=True, + save_path='grid.notaformat'), + 'pattern without an index': dict(animate=True, caption='{index}'), + 'pattern title without an index': dict(title='{index}'), + 'bad panel_fit': dict(panel_fit='nope'), + 'companion with a grid': dict(animate=True, companion=np.arange(20.0)), + 'explore with a grid': dict(explore=True), + 'legend of the wrong length': dict(legend=['a', 'b', 'c']), + 'hue of the wrong length': dict(hue=[0, 1, 2]), + 'animated plotly grid': dict(animate=True, backend='plotly'), + 'plotly caption': dict(caption='x', backend='plotly'), +} + + +@pytest.mark.parametrize('show', [True, False], ids=['show', 'no-show']) +@pytest.mark.parametrize('name', sorted(FAILING_GRID_CALLS)) +def test_failed_grid_call_leaves_no_figure_registered(name, show, tmp_path, + monkeypatch): + """After ANY exception from a `panels=` call, pyplot's registered + figures are what they were before the call.""" + monkeypatch.chdir(tmp_path) + kwargs = dict(FAILING_GRID_CALLS[name]) + if kwargs.get('animate'): + kwargs.setdefault('duration', 1) + kwargs.setdefault('frame_rate', 4) + keep = plt.figure() + before = plt.get_fignums() + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + with pytest.raises(Exception): + hyp.plot([X, X], panels=True, show=show, **kwargs) + assert plt.get_fignums() == before + assert plt.fignum_exists(keep.number) + + +def test_failed_grid_call_with_axis_labels_too_big_for_size_leaks_nothing(): + frames = [pd.DataFrame(d, columns=list('xyz')) for d in DATA] + before = plt.get_fignums() + with pytest.raises(ValueError, match='size='): + hyp.plot(frames, panels=(1, 4), size=[4, 1], **ANIM) + assert plt.get_fignums() == before + + +def test_successful_grid_call_with_show_keeps_its_figure_registered(): + before = plt.get_fignums() + fig = hyp.plot([X, X], panels=True) + assert plt.get_fignums() == before + [fig.number] + + +# -------------------------------------------------------------------------- +# C4: a grid caption's {index} is the panels' reveal head +# -------------------------------------------------------------------------- + +@pytest.mark.parametrize('style', [ + dict(animate=True), + dict(animate=True, order='serial'), + dict(animate='serial'), + dict(animate='spin'), + dict(animate='window'), + dict(animate='parallel', chemtrails=True), +], ids=['parallel', 'order-serial', 'serial', 'spin', 'window', 'trails']) +def test_grid_caption_index_matches_the_panel_titles(style): + anim = hyp.plot(FRAMES[:2], 'o', reduce=None, panels=True, + duration=1, frame_rate=6, show=False, + title='{index:%Y-%m-%d}', caption='{index:%Y-%m-%d}', + **style) + for frame in range(anim.n_frames): + anim.draw_frame(frame) + titles = {ax.get_title() for ax in anim.figure.axes[:2]} + assert titles == {_caption(anim.figure).get_text()}, frame + + +def test_grid_caption_index_follows_the_first_indexed_panel(): + """Panels whose indexes differ: the caption reads the first dataset + that carries an index, at the reveal head of the panel drawing it.""" + plain = DATA[0] + short = pd.DataFrame(DATA[1][:10], + index=pd.date_range('1999-06-01', periods=10)) + long = FRAMES[2] + anim = hyp.plot([plain, short, long], reduce=None, panels=(1, 3), + duration=1, frame_rate=6, show=False, animate=True, + title=['plain', '{index:%Y-%m-%d}', '{index:%Y-%m-%d}'], + caption='{index:%Y-%m-%d}') + for frame in range(anim.n_frames): + anim.draw_frame(frame) + text = _caption(anim.figure).get_text() + assert text.startswith('1999-06') + assert text == anim.figure.axes[1].get_title(), frame + + +def test_reducer_grid_caption_index_reads_the_first_panel(): + anim = hyp.plot(FRAMES[:2], reduce=['PCA', 'IncrementalPCA'], ndims=2, + panels=True, duration=1, frame_rate=6, show=False, + animate=True, order='serial', caption='{index:%m-%d}', + title=['{index:%m-%d}', 'second']) + for frame in range(anim.n_frames): + anim.draw_frame(frame) + assert (_caption(anim.figure).get_text() + == anim.figure.axes[0].get_title()) + + +def test_static_grid_caption_index_is_the_last_row(): + fig = hyp.plot(FRAMES[:2], reduce=None, panels=True, show=False, + caption='{index:%Y-%m-%d}') + assert _caption(fig).get_text() == '2024-01-20' + + +# -------------------------------------------------------------------------- +# C5: a caption wider than the figure is wrapped +# -------------------------------------------------------------------------- + +SENTENCE = ('A caption sentence that is far too long for one line of a ' + 'small figure, so that it has to be wrapped to the width of ' + 'the figure it is drawn under, and stay there. ') + + +def _assert_caption_on_canvas(fig): + x0, y0, x1, y1 = _extent(fig, _caption(fig)) + assert 0.0 <= x0 < x1 <= 1.0, (x0, x1) + assert 0.0 <= y0 < y1 <= 1.0, (y0, y1) + + +def _assert_caption_below_axes(fig): + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + top = _caption(fig).get_window_extent(renderer).y1 + for ax in fig.axes: + if ax.get_visible(): + assert ax.get_window_extent(renderer).y0 >= top - 1.0 + + +@pytest.mark.parametrize('text', ['W' * 200, SENTENCE * 2, + 'first line\n' + SENTENCE], + ids=['one-word', 'sentence', 'own-breaks']) +@pytest.mark.parametrize('call', [ + dict(x=X), dict(x=X, ndims=2), dict(x=DATA, panels=(2, 2)), + dict(x=DATA, panels=(1, 4), legend=True), + dict(x=X, **ANIM), dict(x=DATA, panels=(2, 2), **ANIM), +], ids=['static-3d', 'static-2d', 'static-grid', 'static-grid-legend', + 'animated', 'animated-grid']) +def test_long_caption_is_wrapped_onto_the_canvas(call, text): + call = dict(call, show=False) + result = hyp.plot(call.pop('x'), caption=text, **call) + fig = getattr(result, 'figure', result) + caption = _caption(fig) + assert '\n' in caption.get_text() + # wrapping only adds line breaks + assert (caption.get_text().replace('\n', '').replace(' ', '') + == text.replace('\n', '').replace(' ', '')) + _assert_caption_on_canvas(fig) + _assert_caption_below_axes(fig) + + +def test_short_caption_is_not_wrapped(): + fig = hyp.plot(X, caption='a short caption', show=False) + assert _caption(fig).get_text() == 'a short caption' + + +@pytest.mark.parametrize('grid', [False, True], ids=['single', 'grid']) +def test_caption_that_grows_over_the_frames_stays_on_the_canvas(grid): + """A per-frame caption longer in later frames is wrapped per frame, + and its room is sized for the first, middle and last frames.""" + def caption(ctx): + return SENTENCE * (1 + ctx.frame) + + data = DATA if grid else X + extra = dict(panels=(2, 2)) if grid else {} + anim = hyp.plot(data, caption=caption, duration=1, frame_rate=5, + animate=True, show=False, **extra) + lines = [] + for frame in range(anim.n_frames): + anim.draw_frame(frame) + lines.append(_caption(anim.figure).get_text().count('\n') + 1) + x0, y0, x1, y1 = _extent(anim.figure, _caption(anim.figure)) + assert 0.0 <= x0 < x1 <= 1.0, frame + assert 0.0 <= y0 < y1 <= 1.0, frame + _assert_caption_below_axes(anim.figure) + assert lines == sorted(lines) and lines[-1] > lines[0] + + +def test_wrapped_caption_room_grows_with_its_lines(): + one = hyp.plot(X, caption='short', show=False, **{ + k: v for k, v in ANIM.items() if k != 'show'}) + many = hyp.plot(X, caption=SENTENCE * 3, show=False, **{ + k: v for k, v in ANIM.items() if k != 'show'}) + assert (many.figure.get_size_inches()[1] + > one.figure.get_size_inches()[1] + 0.3) + assert many.figure.get_size_inches()[0] == pytest.approx( + one.figure.get_size_inches()[0]) + + +def test_mathtext_caption_is_left_whole(): + text = r'$\alpha + \beta = \gamma$ and so on' + fig = hyp.plot(X, caption=text, show=False) + assert _caption(fig).get_text() == text + + +# -------------------------------------------------------------------------- +# T3: an empty caption adds nothing +# -------------------------------------------------------------------------- + +@pytest.mark.parametrize('call', [ + dict(x=X), dict(x=X, **ANIM), dict(x=DATA, panels=(1, 4)), + dict(x=DATA, panels=(1, 4), **ANIM), +], ids=['static', 'animated', 'static-grid', 'animated-grid']) +@pytest.mark.parametrize('empty', ['', ' '], ids=['empty', 'blank']) +def test_empty_caption_adds_nothing(call, empty): + call = dict(call, show=False) + data = call.pop('x') + with_caption = hyp.plot(data, caption=empty, **call) + without = hyp.plot(data, **call) + fig_a = getattr(with_caption, 'figure', with_caption) + fig_b = getattr(without, 'figure', without) + assert not fig_a.findobj(lambda a: a.get_gid() == CAPTION_GID) + assert tuple(fig_a.get_size_inches()) == tuple(fig_b.get_size_inches()) + + +# -------------------------------------------------------------------------- +# T1: per-frame titles of an animated grid stay on the canvas +# -------------------------------------------------------------------------- + +def _per_frame_titles(kind, n): + if kind == 'callable': + return lambda ctx: f'frame {ctx.frame}' + if kind == 'pattern': + return '{index:%Y-%m-%d}' + return [(lambda ctx, i=i: f'panel {i} frame {ctx.frame}') + for i in range(n)] + + +@pytest.mark.parametrize('extras', [ + {}, dict(legend=True, caption='a caption'), + dict(hue=[np.arange(20)] * 4, colorbar=True), +], ids=['bare', 'legend-caption', 'colorbar']) +@pytest.mark.parametrize('kind', ['callable', 'pattern', 'list']) +@pytest.mark.parametrize('ndims', [2, 3]) +@pytest.mark.parametrize('shape', [(1, 4), (2, 2), (3, 1)]) +def test_per_frame_titles_stay_inside_an_animated_grid(shape, ndims, kind, + extras): + n = shape[0] * shape[1] + extras = dict(extras) + if 'hue' in extras: + extras['hue'] = extras['hue'][:n] + anim = hyp.plot(FRAMES[:n], reduce=None if ndims == 3 else 'PCA', + ndims=ndims, panels=shape, title=_per_frame_titles(kind, n), + duration=1, frame_rate=3, animate=True, show=False, + **extras) + fig = anim.figure + for frame in range(anim.n_frames): + anim.draw_frame(frame) + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + width, height = fig.canvas.get_width_height() + panels = fig.axes[:n] + boxes = [ax.get_window_extent(renderer) for ax in panels] + for i, ax in enumerate(panels): + assert ax.get_title(), (frame, i) + title = ax.title.get_window_extent(renderer) + # on the canvas + assert title.y1 <= height + 0.5 and title.y0 >= 0, (frame, i) + assert title.x0 >= -0.5 and title.x1 <= width + 0.5, (frame, i) + # ...and clear of every OTHER panel's box and x-axis label + for j, other in enumerate(panels): + if j == i: + continue + assert not title.overlaps(boxes[j]), (frame, i, j) + label = other.xaxis.label + if label.get_text(): + assert not title.overlaps( + label.get_window_extent(renderer)), (frame, i, j) + + +# -------------------------------------------------------------------------- +# T4: a grid warns only where the single-axes call does +# -------------------------------------------------------------------------- + +TWO_COLUMNS = [d[:, :2] for d in DATA] + + +@pytest.mark.parametrize('extra', [ + dict(panels=(2, 2)), dict(panels=(2, 2), panel_fit='independent'), + dict(panels=(1, 4), animate=True, duration=1, frame_rate=4), + dict(panels=True, reduce=['PCA', 'IncrementalPCA']), + dict(return_model=True), dict(n_clusters=2), dict(manip='ZScore'), +], ids=['grid', 'independent', 'animated', 'reducers', 'return_model', + 'clusters', 'manip']) +def test_two_column_data_draws_without_an_ndims_warning(extra): + """The single-axes call of 2-column data is silent about `ndims`, + which the caller never passed: so is every other form of the call.""" + with warnings.catch_warnings(record=True) as single: + warnings.simplefilter('always') + hyp.plot(TWO_COLUMNS, show=False) + assert not [w for w in single if 'ndims' in str(w.message)] + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + hyp.plot(TWO_COLUMNS, show=False, **extra) + assert not [str(w.message) for w in caught + if 'ndims' in str(w.message)] + + +def test_an_explicit_reduce_to_too_many_dimensions_still_warns(): + """The public `hyp.reduce`/`hyp.analyze` warning is untouched.""" + with pytest.warns(UserWarning, match='no reduction was performed'): + hyp.reduce(TWO_COLUMNS, reduce='PCA', ndims=3) + with pytest.warns(UserWarning, match='no reduction was performed'): + hyp.analyze(TWO_COLUMNS, reduce='PCA', ndims=3, return_model=True) From a103bf5c22982b6d2a36d6113430d02d9287625f Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 06:31:07 -0500 Subject: [PATCH 18/58] fix: panel grid layout, review round 1 (GH #295) - 3-D axis labels stay inside their own panel, static and animated: the label offset scales with the cube, so the cube is fitted smaller and the figure grows only where a cube would fall under 70% (static: 65%) of its unlabeled size, in the limiting direction, in small re-fitted steps - an explicit size= on an animated labeled grid is honored down to cubes half their unlabeled size; a refusal names a size that works and xlabel='', ylabel='', zlabel=''; rotations=0 is fitted for its one view - legend_kwargs loc picks the side of the grid the shared legend's strip is on (room reserved on that side only); bbox_to_anchor, loc='center' and plotly x/y reserve no strip - a panel's transient legend no longer drives its cell's layout (one 'Tight layout not applied' warning per panel in a many-panel grid) Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/plot/matplotlib_backend.py | 2 +- hypertools/plot/plot.py | 761 ++++++++++++++++++-------- hypertools/plot/plotly_backend.py | 3 +- tests/test_panel_layout_review.py | 476 ++++++++++++++++ 4 files changed, 1009 insertions(+), 233 deletions(-) create mode 100644 tests/test_panel_layout_review.py diff --git a/hypertools/plot/matplotlib_backend.py b/hypertools/plot/matplotlib_backend.py index ee1d80be5..3c5d3409b 100644 --- a/hypertools/plot/matplotlib_backend.py +++ b/hypertools/plot/matplotlib_backend.py @@ -725,7 +725,7 @@ class PanelAnimationStub: `zoom_scale` is the panel's handle on its own 3-D camera zoom: the grid lowers ``zoom_scale[0]`` until the panel's rotating cube fits its cell - (`plot._fit_rotating_cubes`). + (`plot._fit_panel_cubes`). """ def __init__(self, func, args, n_frames, interval, zoom_scale=None): diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index a40a10cdc..3eee952f7 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -4498,14 +4498,15 @@ def _validate_caption(caption, row_indices, backend_name, ax=None): name='caption') -def _grow_figure_downward(fig, extra_in): - """Make `fig` taller by `extra_in` inches, adding the room at the - BOTTOM: every axes keeps its absolute size and its distance from the - top and side edges, so nothing already drawn moves relative to anything - else or changes size (a 3-D axes' cube included -- its viewport is - derived from the axes' size in inches, which is unchanged).""" +def _grow_figure(fig, left=0.0, right=0.0, top=0.0, bottom=0.0): + """Make `fig` larger by the given inches on each side: every axes + keeps its absolute size and its distance from the edges that do not + move, so nothing already drawn moves relative to anything else or + changes size (a 3-D axes' cube included -- its viewport is derived + from the axes' size in inches, which is unchanged).""" w_in, h_in = fig.get_size_inches() - new_h_in = h_in + float(extra_in) + new_w_in = w_in + float(left) + float(right) + new_h_in = h_in + float(top) + float(bottom) # a persistent layout engine would undo the positions set below on the # next draw (see `_fit_right_legend`) try: @@ -4514,32 +4515,20 @@ def _grow_figure_downward(fig, extra_in): pass placed = [(axis, axis.get_position(original=True), axis.get_position()) for axis in fig.axes] - fig.set_size_inches(w_in, new_h_in) + fig.set_size_inches(new_w_in, new_h_in) for axis, original, active in placed: for which, pos in (('original', original), ('active', active)): axis.set_position( - [pos.x0, (pos.y0 * h_in + extra_in) / new_h_in, - pos.width, pos.height * h_in / new_h_in], which=which) + [(pos.x0 * w_in + left) / new_w_in, + (pos.y0 * h_in + bottom) / new_h_in, + pos.width * w_in / new_w_in, + pos.height * h_in / new_h_in], which=which) -def _grow_figure_rightward(fig, extra_in): - """Make `fig` wider by `extra_in` inches, adding the room on the - RIGHT: every axes keeps its absolute size and its distance from the - left, top and bottom edges (`_grow_figure_downward`'s twin).""" - w_in, h_in = fig.get_size_inches() - new_w_in = w_in + float(extra_in) - try: - fig.set_layout_engine('none') - except Exception: - pass - placed = [(axis, axis.get_position(original=True), axis.get_position()) - for axis in fig.axes] - fig.set_size_inches(new_w_in, h_in) - for axis, original, active in placed: - for which, pos in (('original', original), ('active', active)): - axis.set_position( - [pos.x0 * w_in / new_w_in, pos.y0, - pos.width * w_in / new_w_in, pos.height], which=which) +def _grow_figure_downward(fig, extra_in): + """Make `fig` taller by `extra_in` inches, adding the room at the + BOTTOM (`_grow_figure`).""" + _grow_figure(fig, bottom=extra_in) def _blank_bottom_in(fig): @@ -5147,74 +5136,166 @@ def _merge_panel_color_scales(scales, dataset_mode=False, names=None): if named else {})) +#: matplotlib's integer legend location codes +_LEGEND_LOC_CODES = { + 0: 'best', 1: 'upper right', 2: 'upper left', 3: 'lower left', + 4: 'lower right', 5: 'right', 6: 'center left', 7: 'center right', + 8: 'lower center', 9: 'upper center', 10: 'center'} + + +def _shared_legend_side(loc): + """Where a grid's shared legend goes for a caller's ``loc``: + ``(side, align)``, or None for a location that is not one of the + named ones (a coordinate pair, which places the legend itself). + + `side` is the side of the GRID the legend's strip is on -- 'right', + 'left', 'top' or 'bottom' -- or 'over' for ``'center'``, which draws + the legend over the middle of the grid; `align` is where along that + strip it sits ('upper', 'center' or 'lower' on a side strip; 'center' + on the top and bottom ones). A location names the legend's place + relative to the grid, as it names a single plot's relative to its + axes: ``'upper right'`` is the top of the right-hand strip, + ``'lower center'`` the strip under the grid, ``'center left'`` the + left-hand strip. ``'best'`` is the default (right, centered). + """ + if isinstance(loc, (int, np.integer)) and not isinstance(loc, bool): + loc = _LEGEND_LOC_CODES.get(int(loc)) + if not isinstance(loc, str): + return None + words = set(loc.lower().split()) + if not words or not words <= {'best', 'upper', 'lower', 'center', + 'left', 'right'}: + return None + if words == {'best'}: + return 'right', 'center' + if words == {'center'}: + return 'over', 'center' + align = ('upper' if 'upper' in words + else 'lower' if 'lower' in words else 'center') + if 'right' in words: + return 'right', align + if 'left' in words: + return 'left', align + return ('top' if 'upper' in words else 'bottom'), 'center' + + def _shared_legend_call(template, legend_kwargs): - """``(kwargs, placed)`` for the grid's one figure-level legend: the - styling hypertools draws a legend with, in the panels' own text font - (`template` is one of their legends), under the caller's - `legend_kwargs=`. `placed` says the caller positioned it - (``loc``/``bbox_to_anchor``): those then place the one legend in - FIGURE coordinates and no strip is reserved for it.""" - call = dict(loc='center left', borderaxespad=0.0, frameon=False) + """``(kwargs, side, align)`` for the grid's one figure-level legend: + the styling hypertools draws a legend with, in the panels' own text + font (`template` is one of their legends), under the caller's + `legend_kwargs=`. + + `side`/`align` say where the legend's strip is (`_shared_legend_side`; + the right-hand strip, centered, without a ``loc``). `side` is None + when the caller positioned the legend themselves -- a + ``bbox_to_anchor``, or a coordinate pair as ``loc`` -- which is then + passed to matplotlib as given, in FIGURE fractions ((0, 0) is the + figure's bottom-left corner, (1, 1) its top-right), and no strip is + reserved. + """ + call = dict(borderaxespad=0.0, frameon=False) texts = template.get_texts() if texts: call['prop'] = texts[0].get_fontproperties() user = dict(legend_kwargs or {}) - placed = 'loc' in user or 'bbox_to_anchor' in user if 'fontsize' in user and 'prop' in call and 'prop' not in user: prop = call['prop'].copy() prop.set_size(user.pop('fontsize')) call['prop'] = prop + side, align = 'right', 'center' + if 'bbox_to_anchor' in user: + side = None + user.setdefault('loc', 'center left') + elif 'loc' in user: + named = _shared_legend_side(user['loc']) + if named is None: + side = None + else: + side, align = named + user.pop('loc') call.update(user) - return call, placed + return call, side, align + + +#: per strip side, the legend corner (matplotlib ``loc``) that is anchored +#: for each alignment along the strip +_SHARED_LEGEND_ANCHORS = { + 'right': {'upper': 'upper left', 'center': 'center left', + 'lower': 'lower left'}, + 'left': {'upper': 'upper right', 'center': 'center right', + 'lower': 'lower right'}, + 'top': {'center': 'lower center'}, + 'bottom': {'center': 'upper center'}, + 'over': {'center': 'center'}, +} def _add_shared_furniture(fig, panel_axes, legend_spec, colorbar_info, legend_kwargs=None, widen=True): - """Draw a panel grid's ONE legend and/or ONE colorbar in a strip to - the right of the grid, and lay the grid out beside it. + """Draw a panel grid's ONE legend and/or ONE colorbar in strips + beside the grid, and lay the grid out beside them. `legend_spec` is `_merge_panel_legends`' result (the panels' own legends are removed here) and `colorbar_info` `_merge_panel_colorbars`' - (either may be None). The strip is as wide as what it holds, measured - on a real draw: with `widen` (no explicit `size=`) the figure grows by - that much, so the panels keep their size; otherwise the grid is laid - out in the figure's remaining width. A legend too tall for the figure - is wrapped into columns. A colorbar whose ``location`` is not - ``'right'`` is attached to the whole grid on that side instead - (matplotlib's own multi-axes colorbar). - - Returns the strip's state for `_place_shared_furniture`, which + (either may be None). The legend's strip is right of the grid, or on + the side a ``legend_kwargs`` ``loc`` names (`_shared_legend_call`); + the colorbar's is right of the grid, after a right-hand legend. A + strip is as wide (or as tall) as what it holds, measured on a real + draw: with `widen` (no explicit `size=`) the figure grows by that + much on that side, so the panels keep their size; otherwise the grid + is laid out in what remains of the figure. A legend too tall for the + figure is wrapped into columns, and a top or bottom legend is laid + out in as many columns as fit the figure's width. A legend the + caller positioned (``bbox_to_anchor``, or ``loc='center'``) gets no + strip: nothing is reserved for it and the grid is laid out as without + it. A colorbar whose ``location`` is not ``'right'`` is attached to + the whole grid on that side instead (matplotlib's own multi-axes + colorbar). + + Returns the strips' state for `_place_shared_furniture`, which positions the legend and colorbar and is called again whenever the - figure is resized afterwards (the caption, an animated grid's cube - fit). + figure is resized afterwards (the caption, the cube fit). """ from matplotlib.cm import ScalarMappable from matplotlib.colors import BoundaryNorm, ListedColormap, Normalize strip = {'legend': None, 'colorbar': None, 'legend_in': (0.0, 0.0), 'colorbar_in': 0.0, 'panel_axes': list(panel_axes), - 'placed': False, 'rect_right': 1.0} + 'side': None, 'align': 'center', 'rect_right': 1.0, + 'gap_in': 0.0} pad = _SHARED_STRIP_PAD_IN width_in, height_in = fig.get_size_inches() if legend_spec is not None: handles, labels, template = legend_spec - call, placed = _shared_legend_call(template, legend_kwargs) + call, side, align = _shared_legend_call(template, legend_kwargs) for ax in panel_axes: if ax.get_legend() is not None: ax.get_legend().remove() - if not placed: + if side is not None: + call['loc'] = _SHARED_LEGEND_ANCHORS[side][align] call['bbox_to_anchor'] = (0.5, 0.5) call['bbox_transform'] = fig.transFigure - columns = 1 + fixed_columns = 'ncols' in call or 'ncol' in call + horizontal = side in ('top', 'bottom') + columns = len(labels) if horizontal else 1 while True: _call = dict(call) - if columns > 1: + if not fixed_columns and columns > 1: _call['ncols'] = columns legend = fig.legend(handles, labels, **_call) box = legend.get_window_extent(_measurement_renderer(fig)) size_in = (box.width / fig.dpi, box.height / fig.dpi) - if (placed or 'ncols' in call or 'ncol' in call - or size_in[1] <= height_in - 2 * pad + if side is None or side == 'over' or fixed_columns: + break + if horizontal: + # too wide for the figure: fewer columns + if size_in[0] <= width_in - 2 * pad or columns <= 1: + break + legend.remove() + columns = min(columns - 1, max(1, int( + columns * (width_in - 2 * pad) / size_in[0]))) + continue + if (size_in[1] <= height_in - 2 * pad or columns >= len(labels)): break # too tall for the figure: wrap the entries into columns @@ -5222,8 +5303,10 @@ def _add_shared_furniture(fig, panel_axes, legend_spec, colorbar_info, columns = max(columns + 1, int(np.ceil( columns * size_in[1] / (height_in - 2 * pad)))) legend.set_gid(SHARED_LEGEND_GID) - strip.update(legend=legend, placed=placed, - legend_in=(0.0, 0.0) if placed else size_in) + strip.update( + legend=legend, side=side, align=align, + legend_in=(size_in if side in ('right', 'left', 'top', 'bottom') + else (0.0, 0.0))) mappable = ticklabels = None if colorbar_info is not None: @@ -5270,53 +5353,68 @@ def _finish(cbar): box = cax.get_tightbbox(_measurement_renderer(fig)) strip['colorbar_in'] = box.width / fig.dpi - strip_in = sum(part + pad for part in (strip['legend_in'][0], - strip['colorbar_in']) if part) - if strip_in: - strip_in += pad - # The grid is laid out in a figure WITHOUT the strip -- the figure as - # it is when it is about to grow by the strip, or narrowed by it under - # an explicit `size=` -- and the strip is then added on the right - # (`_grow_figure_rightward`), so the layout is exactly the legend-less + # the room each side's strip takes (inches) + legend_w, legend_h = strip['legend_in'] + side = strip['side'] + right_parts = [part for part in (legend_w if side == 'right' else 0.0, + strip['colorbar_in']) if part] + room = {'right': sum(part + pad for part in right_parts) + + (pad if right_parts else 0.0), + 'left': legend_w + 2 * pad if side == 'left' else 0.0, + 'top': legend_h + 2 * pad if side == 'top' else 0.0, + 'bottom': legend_h + 2 * pad if side == 'bottom' else 0.0} + # The grid is laid out in a figure WITHOUT the strips -- the figure as + # it is when it is about to grow by them, or made smaller by them + # under an explicit `size=` -- and the strips are then added on their + # sides (`_grow_figure`), so the layout is exactly the legend-less # grid's. (`tight_layout(rect=...)` is not: it drops the room a 3-D # panel's title needs, which then pokes out of the top of the canvas.) - total_in = width_in + strip_in if widen else width_in - grid_in = max(total_in - strip_in, 0.3 * total_in) - - def _lay_out(width): - """Lay the panels out in a `width`-inch figure and return how far - (inches) what they draw reaches past its right edge.""" - fig.set_size_inches(width, height_in) - with warnings.catch_warnings(): - # the colorbar's axes is placed by hand (below), which - # `tight_layout` reports as an axes it cannot lay out - warnings.filterwarnings( - 'ignore', message='This figure includes Axes that are not ' - 'compatible with tight_layout') - # the panels were last laid out around their own legends, - # which are gone: one pass from there under-reserves a 3-D - # panel's title room (its box is aspect-constrained), a second - # settles it - for _ in range(3): - fig.tight_layout() - return max(0.0, _panels_right_edge_in(fig, panel_axes) - width) - - # what the last column draws right of its own box (a 3-D panel's - # z-axis label hangs in its right margin) must stay clear of the - # strip: the strip starts right of it - overhang_in = _lay_out(grid_in) if strip_in else 0.0 - if not strip_in: - _lay_out(grid_in) - elif widen: - total_in += overhang_in + across = room['left'] + room['right'] + along = room['top'] + room['bottom'] + if widen: + grid_w, grid_h = width_in, height_in else: + grid_w = max(width_in - across, 0.3 * width_in) + grid_h = max(height_in - along, 0.3 * height_in) + # (what a 3-D panel's axis labels draw outside its cube is kept inside + # the panel's own box afterwards -- `_fit_panel_cubes` -- so nothing + # of an outer column reaches into a strip) + fig.set_size_inches(grid_w, grid_h) + with warnings.catch_warnings(): + # the colorbar's axes is placed by hand (below), which + # `tight_layout` reports as an axes it cannot lay out + warnings.filterwarnings( + 'ignore', message='This figure includes Axes that are not ' + 'compatible with tight_layout') + # the panels were last laid out around their own legends, which + # are gone: one pass from there under-reserves a 3-D panel's + # title room (its box is aspect-constrained), a second settles it for _ in range(3): - if overhang_in <= 0.01 or grid_in <= 0.3 * total_in: - break - grid_in = max(grid_in - overhang_in, 0.3 * total_in) - overhang_in = _lay_out(grid_in) - _grow_figure_rightward(fig, total_in - grid_in) - strip['rect_right'] = (total_in - strip_in) / total_in + fig.tight_layout() + if not widen: + # an explicit size too small for the strips: they keep their size + # and the grid the 30% floor above + scale_w = (width_in - grid_w) / across if across else 1.0 + scale_h = (height_in - grid_h) / along if along else 1.0 + room = {'left': room['left'] * scale_w, + 'right': room['right'] * scale_w, + 'top': room['top'] * scale_h, + 'bottom': room['bottom'] * scale_h} + _grow_figure(fig, **room) + total_w, total_h = fig.get_size_inches() + strip['rect_right'] = (total_w - room['right']) / total_w + # how far the legend stands from the panels' boxes (inches): what + # `_place_shared_furniture` keeps when the figure is resized later + boxes = [ax.get_position(original=True) for ax in panel_axes] + if side == 'left': + strip['gap_in'] = min(b.x0 for b in boxes) * total_w - ( + room['left'] - pad) + elif side == 'bottom': + strip['gap_in'] = min(b.y0 for b in boxes) * total_h - ( + room['bottom'] - pad) + elif side == 'top': + strip['gap_in'] = (total_h - room['top'] + pad) - max( + b.y1 for b in boxes) * total_h if mappable is not None and not in_strip: _finish(fig.colorbar( mappable, ax=list(panel_axes), @@ -5327,45 +5425,50 @@ def _lay_out(width): return strip -def _panels_right_edge_in(fig, panel_axes): - """How far right (inches from the figure's left edge) the panels - `panel_axes` draw, measured on a real draw: each visible panel's box - and its axis labels (a 3-D panel's hang outside the box).""" - renderer = _measurement_renderer(fig) - right = 0.0 - for ax in panel_axes: - if not ax.get_visible(): - continue - boxes = [ax.get_window_extent(renderer)] - axis_map = getattr(ax, '_axis_map', None) or { - 'x': ax.xaxis, 'y': ax.yaxis} - for axis in axis_map.values(): - label = axis.label - if label.get_text() and label.get_visible(): - boxes.append(label.get_window_extent(renderer)) - right = max([right] + [float(box.x1) for box in boxes - if np.isfinite(box.x1)]) - return right / fig.dpi - - def _place_shared_furniture(fig, strip): """Position a grid's shared legend and colorbar (`strip`, from - `_add_shared_furniture`) in the strip right of the panels: the legend - first, then the colorbar, each vertically centered on the grid. - Idempotent, and re-run after anything resizes the figure -- the strip - starts at the same fraction of the figure's width, and what it holds - keeps its size in inches.""" + `_add_shared_furniture`) in their strips: on the right, the legend + first, then the colorbar, each vertically centered on the grid (or + the legend at its top or bottom, for an ``'upper ...'``/``'lower + ...'`` location); a left, top or bottom legend at its recorded + distance from the panels. Idempotent, and re-run after anything + resizes the figure -- the right-hand strip starts at the same + fraction of the figure's width, and what a strip holds keeps its size + in inches.""" if strip is None: return width_in, height_in = fig.get_size_inches() boxes = [ax.get_position() for ax in strip['panel_axes']] y0, y1 = min(b.y0 for b in boxes), max(b.y1 for b in boxes) middle = 0.5 * (y0 + y1) + # (the panels' slots, which a 3-D panel's square box is centered in: + # what the recorded distances are measured from) + slots = [ax.get_position(original=True) for ax in strip['panel_axes']] + x0, x1 = min(b.x0 for b in slots), max(b.x1 for b in slots) + slot_y0, slot_y1 = (min(b.y0 for b in slots), + max(b.y1 for b in slots)) x = strip['rect_right'] + _SHARED_STRIP_PAD_IN / width_in legend = strip['legend'] - if legend is not None and not strip['placed']: - legend.set_bbox_to_anchor((x, middle), transform=fig.transFigure) + side = strip['side'] + along = {'upper': y1, 'center': middle, 'lower': y0}[strip['align']] + if legend is not None and side == 'right': + legend.set_bbox_to_anchor((x, along), transform=fig.transFigure) x += (strip['legend_in'][0] + _SHARED_STRIP_PAD_IN) / width_in + elif legend is not None and side == 'left': + legend.set_bbox_to_anchor( + (x0 - strip['gap_in'] / width_in, along), + transform=fig.transFigure) + elif legend is not None and side == 'top': + legend.set_bbox_to_anchor( + (0.5 * (x0 + x1), slot_y1 + strip['gap_in'] / height_in), + transform=fig.transFigure) + elif legend is not None and side == 'bottom': + legend.set_bbox_to_anchor( + (0.5 * (x0 + x1), slot_y0 - strip['gap_in'] / height_in), + transform=fig.transFigure) + elif legend is not None and side == 'over': + legend.set_bbox_to_anchor((0.5 * (x0 + x1), middle), + transform=fig.transFigure) cbar = strip['colorbar'] if cbar is not None and strip['colorbar_in']: height = _SHARED_COLORBAR_HEIGHT * (y1 - y0) @@ -5888,7 +5991,13 @@ def _draw_grid(consolidate): save_path=save_path, show=show, return_model=return_model, shared_pipeline=shared_pipeline, resize=call_kwargs.get('size') is None, _name=_name, - strip=strip, grid_colors=grid_colors) + strip=strip, grid_colors=grid_colors, + rotations=call_kwargs.get('rotations', 1)) + + # a static 3-D panel's axis labels stay inside the panel's own box + _fit_static_cube_labels(fig, panel_axes, + resize=call_kwargs.get('size') is None) + _place_shared_furniture(fig, strip) if caption is not None or dynamic_caption is not None: # a static grid's caption: fixed text, or the dynamic forms @@ -6058,21 +6167,54 @@ def _common(name): panels=panel_contexts) -#: how much of its axes' square a rotating panel cube may fill, at most +#: how much of its axes' square a panel's cube (and its axis labels) may +#: fill, at most _PANEL_CUBE_FILL = 0.96 +#: the least a LABELED animated panel cube may be, as a share of the size +#: the same cube has without axis labels: below this the cube is too small +#: beside its own labels, and the default figure grows instead +_PANEL_LABELED_CUBE_SHARE = 0.7 + +#: ...the least a labeled STATIC panel cube may be before its default figure +#: grows (a static grid's default figure is one fixed size whatever the +#: grid, so it is enlarged only where the cubes would become very small)... +_STATIC_LABELED_CUBE_SHARE = 0.65 + +#: ...and the share under which an explicit `size=` is refused for an +#: animated grid (a size the caller chose is honored down to cubes half +#: their unlabeled size) +_REFUSED_LABELED_CUBE_SHARE = 0.5 + + +def _camera_azimuths(axis, rotations, step): + """The camera angles a panel is seen from: its current azimuth and, + for a rotating animation, the arc ``rotations`` turns sweep from there + (a full circle from one turn up), sampled every `step` degrees with + both ends included. A static panel, or ``rotations=0``, has the one + view.""" + try: + turns = float(rotations or 0.0) + except (TypeError, ValueError): + turns = 1.0 + span = min(abs(turns) * 360.0, 360.0) + if span <= 0.0: + return [float(axis.azim)] + offsets = np.append(np.arange(0.0, span, step), span) + return [float(axis.azim + np.sign(turns) * off) for off in offsets] + -def _cube_reach(axis): +def _cube_reach(axis, azimuths): """How far a 3-D axes' cube reaches from the center of the square the - axes is drawn in, at the widest camera angle of a full turn (at the - axes' current elevation and box zoom): 0.5 is the square's edge.""" + axes is drawn in, at the widest of the camera angles `azimuths` (at + the axes' current elevation and box zoom): 0.5 is the square's edge.""" import itertools from mpl_toolkits.mplot3d import proj3d elev, azim0 = axis.elev, axis.azim corners = np.array(list(itertools.product( axis.get_xlim3d(), axis.get_ylim3d(), axis.get_zlim3d()))) reach = 0.0 - for azim in np.arange(0.0, 360.0, 3.0): + for azim in azimuths: axis.view_init(elev=elev, azim=azim) px, py, _ = proj3d.proj_transform( corners[:, 0], corners[:, 1], corners[:, 2], axis.get_proj()) @@ -6083,16 +6225,20 @@ def _cube_reach(axis): return reach -def _axis_label_reach(fig, cells, step=30.0): +def _axis_label_reach(fig, cells, rotations): """Per cell, how far its 3-D AXIS LABELS reach from the center of the - axes' square over a full turn (0.5 is the square's edge; 0.0 for a - cell without labels). Label placement is matplotlib's, decided at draw - time, so this draws the figure once per sampled camera angle.""" + axes' square over the views the panel is seen from (0.5 is the + square's edge; 0.0 for a cell without labels). Label placement is + matplotlib's, decided at draw time, so this draws the figure once per + sampled camera angle (every 30 degrees of the rotation).""" reaches = [0.0] * len(cells) views = [(cell['axes'].elev, cell['axes'].azim) for cell in cells] - for azim in np.arange(0.0, 360.0, step): - for cell, (elev, _) in zip(cells, views): - cell['axes'].view_init(elev=elev, azim=azim) + sweeps = [_camera_azimuths(cell['axes'], rotations, 30.0) + for cell in cells] + for step in range(max([0] + [len(sweep) for sweep in sweeps])): + for cell, (elev, _), sweep in zip(cells, views, sweeps): + cell['axes'].view_init(elev=elev, + azim=sweep[min(step, len(sweep) - 1)]) renderer = _measurement_renderer(fig) for k, cell in enumerate(cells): axis = cell['axes'] @@ -6110,39 +6256,85 @@ def _axis_label_reach(fig, cells, step=30.0): return reaches -#: the least a LABELED rotating panel cube may reach from the center of its -#: axes' square (0.5 is the square's edge): below this the cube is too -#: small beside its own axis labels, and the figure grows instead -_PANEL_LABELED_CUBE_REACH = 0.3 - - -def _fit_rotating_cubes(fig, cells, resize=True, _name='panels'): - """Zoom every animated 3-D panel out until its cube -- and its axis - labels, when it has any -- stay inside the panel's own cell at EVERY - camera angle of the rotation (GH #295). +class _StaticCubeZoom: + """A STATIC 3-D panel's zoom handle, in the shape of an animated + panel's `PanelAnimationStub` (``zoom_scale`` and ``draw``), so + `_fit_panel_cubes` fits either: ``draw`` applies ``zoom_scale[0]`` to + the axes' own box aspect.""" + + def __init__(self, axis): + self._axis = axis + self._aspect = tuple(axis.get_box_aspect()) + self.zoom_scale = [1.0] + + def draw(self, frame=0): + """Apply the current zoom (`frame` is ignored: a static panel + has one).""" + self._axis.set_box_aspect(self._aspect, zoom=self.zoom_scale[0]) + + +def _has_axis_labels(axis): + """Whether the 3-D axes `axis` draws any axis label.""" + return any(axis3d.label.get_text() and axis3d.label.get_visible() + for axis3d in axis._axis_map.values()) + + +def _fit_static_cube_labels(fig, panel_axes, resize=True): + """Keep every STATIC 3-D panel's axis labels inside the panel's own + box (`_fit_panel_cubes`): matplotlib hangs a 3-D axes' labels outside + its cube, where no layout accounts for them, so in a grid they landed + on the next panel's cube, on the title of the panel below and on the + shared legend. A labeled panel's cube is drawn smaller until its + labels fit, and where that would leave the cube too small the figure + is enlarged instead (`resize`: no explicit `size=`, which is honored + as given). Panels without axis labels are not touched.""" + cells = [{'axes': ax, 'stub': _StaticCubeZoom(ax)} + for ax in panel_axes + if ax.get_visible() and hasattr(ax, 'get_proj') + and _has_axis_labels(ax)] + if cells: + _fit_panel_cubes(fig, cells, resize=resize, rotations=0, + static=True) + + +def _fit_panel_cubes(fig, cells, resize=True, rotations=1, static=False, + _name='panels'): + """Zoom every 3-D panel out until its cube -- and its axis labels, + when it has any -- stay inside the panel's own box at EVERY camera + angle the panel is seen from (GH #295). A single animated 3-D plot gives its axes the whole canvas, because the cube an animation draws -- zoomed, and wider on screen when seen corner-on -- overflows a normal subplot box at some angles (the frame and the data are drawn unclipped). In a grid that overflow would run into the panel's own title and legend and into the next panel. So the - cube's projected extent is measured over a full turn, at the panel's - own elevation and zoom, and the panel's box zoom is lowered + cube's projected extent is measured over the views the animation + takes (`_camera_azimuths`: the whole turn, the arc of a partial one, + or the single view of ``rotations=0``), at the panel's own elevation + and zoom, and the panel's box zoom is lowered (`PanelAnimationStub.zoom_scale`) until the widest view fits the square matplotlib draws a 3-D axes in -- which the title sits above and the legend beside. A panel whose cube already fits is left alone, and 2-D panels have no camera and are never touched. - Axis labels (`xlabel=`/`ylabel=`/`zlabel=`) hang a fixed distance - outside the cube and swing around with it, so a labeled panel's cube is - drawn smaller still, until the labels fit too. That distance does not - shrink with the figure: in a small cell the labels would leave the cube - almost no room, so the whole figure is enlarged first (`resize`, i.e. - no explicit `size=`), and with an explicit `size=` too small for them - this raises, naming the size that would do. + Axis labels (`xlabel=`/`ylabel=`/`zlabel=`) hang outside the cube, at + a distance that scales with the cube, and swing around with it, so a + labeled panel's cube is drawn smaller still, until the labels fit + too. The figure is enlarged only where that leaves a cube smaller + than `_PANEL_LABELED_CUBE_SHARE` of its unlabeled size -- and then by + no more than brings it back to that (`resize`, i.e. no explicit + `size=`). An explicit `size=` is honored down to + `_REFUSED_LABELED_CUBE_SHARE`; below that this raises, naming a size + that works (it is found by fitting the grid at that size). + + `static` fits a STATIC grid's labeled panels (see + `_fit_static_cube_labels`): only the labels are fitted, at the one + view, and an explicit `size=` too small for them is honored (smaller + cubes) instead of refused. """ cubes = [cell for cell in cells if hasattr(cell['axes'], 'get_proj')] limit = 0.5 * _PANEL_CUBE_FILL + labeled = [cell for cell in cubes if _has_axis_labels(cell['axes'])] def _fit_cube(cell, target): # the projection is perspective, so the reach is not exactly linear @@ -6150,61 +6342,94 @@ def _fit_cube(cell, target): for _ in range(4): # frame 0 sets the panel's elevation and applies its box zoom cell['stub'].draw(0) - cell['reach'] = _cube_reach(cell['axes']) + cell['reach'] = _cube_reach( + cell['axes'], _camera_azimuths(cell['axes'], rotations, 3.0)) if abs(cell['reach'] - target) <= 0.001 * target or ( target >= limit and cell['reach'] <= target): break cell['stub'].zoom_scale[0] *= target / cell['reach'] - for cell in cubes: - _fit_cube(cell, limit) - labeled = [cell for cell in cubes - if any(axis3d.label.get_text() - for axis3d in cell['axes']._axis_map.values())] - if labeled: - # how far the labels stand outside the cube, in square widths - gaps = [max(0.0, label_reach - cell['reach']) - for cell, label_reach in zip( - labeled, _axis_label_reach(fig, labeled))] + def _fit(): + """Fit every cube, then every labeled cube's labels, at the + figure's current size; returns the smallest share of its + unlabeled size a labeled cube is left with.""" + for cell in cubes: + cell['stub'].zoom_scale[0] = 1.0 + # (a static cube is only ever moved for its labels) + _fit_cube(cell, 10.0 * limit if static else limit) + # what the cube reaches without labels, over these views + cell['free'] = cell['reach'] + pending = list(labeled) + for _ in range(6): + if not pending: + break + over = [] + for cell, label_reach in zip( + pending, _axis_label_reach(fig, pending, rotations)): + if label_reach - limit <= 0.004: + continue + # the labels' distance from the cube scales with the cube + _fit_cube(cell, max(0.02, cell['reach'] * limit + / label_reach)) + over.append(cell) + pending = over + return min([1.0] + [cell['reach'] / cell['free'] + for cell in labeled]) + + smallest = _fit() + floor = (_STATIC_LABELED_CUBE_SHARE if static + else _PANEL_LABELED_CUBE_SHARE if resize + else _REFUSED_LABELED_CUBE_SHARE) + if labeled and smallest < floor - 0.02 and (resize or not static): width, height = fig.get_size_inches() - grow_w = grow_h = 1.0 - for cell, gap in zip(labeled, gaps): - # the side this panel's square needs for its labels to leave - # the cube its share, against the cell's own width and height - # (the square is the smaller of the two) - box = cell['axes'].get_position(original=True) - cell_w, cell_h = box.width * width, box.height * height - side = (min(cell_w, cell_h) * gap - / (limit - _PANEL_LABELED_CUBE_REACH)) - grow_w = max(grow_w, side / cell_w) - grow_h = max(grow_h, side / cell_h) - if grow_w > 1.0 or grow_h > 1.0: + new_width, new_height = width, height + # (a refusal's suggestion may be generous; it must be reached) + step = 1.2 if resize else 1.5 + for _ in range(40): + # at this size a cube's labels reach `overhang` cube-reaches + # past it, a share that falls as the panel's square grows: the + # square (the smaller of the cell's width and height) must be + # about `grow` times its side, so the figure grows in the + # direction(s) that limit it and no further -- in steps of at + # most a fifth, re-fitted each time, so it stops close to the + # smallest figure that does + grow_w = grow_h = 1.0 + for cell in labeled: + wanted = floor * cell['free'] + if cell['reach'] >= wanted - 0.002: + continue + overhang = limit / max(cell['reach'], 1e-6) - 1.0 + grow = min(step, max(1.02, overhang + / max(limit / wanted - 1.0, 1e-6))) + box = cell['axes'].get_position(original=True) + cell_w = box.width * new_width + cell_h = box.height * new_height + side = grow * min(cell_w, cell_h) + grow_w = max(grow_w, side / cell_w) + grow_h = max(grow_h, side / cell_h) if not resize: - raise ValueError( - f"the axis labels (xlabel=/ylabel=/zlabel=) of this " - f"animated 3-D {_name}= grid swing around each panel's " - f"rotating cube and need more room than a " - f"{width:g} x {height:g} inch figure gives each panel. " - f"Pass a larger size= (about " - f"({width * grow_w:.1f}, {height * grow_h:.1f}) or " - "more), leave size= out to have the figure sized for " - "them, or drop the axis labels.") - # the labels' distance from the cube is fixed in points, so a - # larger figure is what gives the cube its share back - fig.set_size_inches(width * grow_w, height * grow_h) - for _ in range(5): - if not labeled: - break - over = [] - for cell, label_reach in zip(labeled, - _axis_label_reach(fig, labeled)): - excess = label_reach - limit - if excess <= 0.005: - continue - # pull the cube in by what the labels overshoot - _fit_cube(cell, max(0.1, cell['reach'] - excess)) - over.append(cell) - labeled = over + # a size to SUGGEST keeps the caller's proportions: the + # grid is laid out afresh at an explicit size, and only a + # figure of the same shape is laid out the same way + grow_w = grow_h = max(grow_w, grow_h) + new_width, new_height = new_width * grow_w, new_height * grow_h + fig.set_size_inches(new_width, new_height) + smallest = _fit() + if smallest >= floor - 0.004: + break + if not resize: + fig.set_size_inches(width, height) + raise ValueError( + f"the axis labels (xlabel=/ylabel=/zlabel=) of this " + f"animated 3-D {_name}= grid hang outside each panel's " + f"cube, and a {width:g} x {height:g} inch figure leaves " + f"too little of each panel for the cube itself. Pass a " + f"larger size= " + f"(({np.ceil(new_width * 10) / 10:g}, " + f"{np.ceil(new_height * 10) / 10:g}) or more), leave " + "size= out to have the figure sized for them, or drop the " + "axis labels (xlabel='', ylabel='', zlabel='' also drops " + "the ones taken from DataFrame column names).") for cell in cubes: # leave every panel showing frame 0 at its final zoom cell['stub'].draw(0) @@ -6214,7 +6439,7 @@ def _animate_panel_grid(fig, cells, panel_axes, panel_models, grid, grid_hooks, caption, dynamic_caption, font, save_path, show, return_model, shared_pipeline, resize=True, _name='panels', strip=None, - grid_colors=None): + grid_colors=None, rotations=1): """Turn a drawn grid of animated panels into ONE animation (GH #295). Every panel call left its frame function in `cells` (a @@ -6257,7 +6482,8 @@ def _abandon(): n_frames = frame_counts[0] interval = cells[0]['stub']._interval try: - _fit_rotating_cubes(fig, cells, resize=resize, _name=_name) + _fit_panel_cubes(fig, cells, resize=resize, rotations=rotations, + _name=_name) _place_shared_furniture(fig, strip) except Exception: _abandon() @@ -6454,9 +6680,17 @@ def _draw_panels(consolidate): title_px = max([0] + [max(0, int(panel.layout.margin.t or 0) - 10) for panel, title in zip(panel_figs, titles) if title]) + # a caller's own legend position (`legend_kwargs` x/y, paper fractions + # of the whole grid): the legend is drawn there, so no strip is + # reserved for it + _position = None + if consolidate and shared_legend: + _position = _explicit_legend_position( + panel_figs[0].layout.legend.to_plotly_json() + if panel_figs[0].layout.legend is not None else {}) strip_px = 0 if consolidate: - if shared_legend: + if shared_legend and _position is None: strip_px += PANEL_LEGEND_PX if colorbar_info is not None \ and colorbar_info.get('location', 'right') == 'right': @@ -6474,9 +6708,6 @@ def _draw_panels(consolidate): panel_axes.append(keys['scene'] if ndims >= 3 else (keys['xaxis'], keys['yaxis'])) if consolidate and (shared_legend or colorbar_info is not None): - _first_legend = (panel_figs[0].layout.legend.to_plotly_json() - if panel_figs[0].layout.legend is not None else {}) - _position = _explicit_legend_position(_first_legend) place_shared_furniture( fig, shared_legend, (None if colorbar_info is None else _colorbar_trace( @@ -7354,6 +7585,28 @@ def plot( anything given here wins over hypertools' own defaults (a frameless legend centered outside the right edge). Default None. + In a `panels=` grid these style the grid's ONE shared legend, and + its position is read relative to the whole GRID. On matplotlib a + named ``loc`` picks the side of the grid the legend's strip is + on: ``'right'``/``'center right'`` (the default), ``'upper + right'`` and ``'lower right'`` put it right of the grid, level + with its middle, top or bottom; ``'center left'``/``'upper + left'``/``'lower left'`` left of it; ``'upper center'`` above the + panels and their titles and ``'lower center'`` below them (above + a `caption=`), laid out in a row. Room is reserved on that side + only -- the default figure grows by the legend's measured size + there, and an explicit `size=` is honored with the grid laid out + in what remains -- so the legend never overlaps a panel. + ``loc='center'`` draws it over the middle of the grid, and + ``bbox_to_anchor`` (or a coordinate pair as ``loc``) places it + yourself, in FIGURE fractions -- (0, 0) is the figure's + bottom-left corner and (1, 1) its top-right, so values outside + 0..1 are off the canvas; in both cases no room is reserved and + the panels are laid out as without a legend. On plotly, ``x``/ + ``y`` are paper fractions of the whole grid (0..1 spans the + panels; above 1 is the margin right of or above them) and + likewise reserve no strip. + legend_colors : list of colors, or list of (label, color) pairs An explicit override of the legend's swatches. A plain list of colors -- one per legend entry, in order -- RECOLORS the entries @@ -8686,16 +8939,36 @@ def plot( under `panels=`). On a STATIC plot it is drawn once: a pattern or callable is resolved for the finished figure, as a dynamic `title=` is (``frame``/``n_frames`` are None and ``progress`` is - 1.0, so a pattern shows the LAST row's index). + 1.0, so a pattern shows the LAST row's index); its context + carries the figure, its axes, the drawn ``artists`` and the + ``datasets``, and for a static grid ``panels`` holds one such + context per panel. A callable is also called when the figure is + built, with the real context of the frames named below. + + Under a `panels=` grid an ``{index}`` pattern shows the index + that a PANEL's own ``title='{index}'`` shows: the first dataset + that carries an index is read, at the reveal head of the panel + that draws it (the first panel, when every panel draws every + dataset under a list-valued `reduce=`). Panels whose indexes or + lengths differ are therefore never averaged or mixed; use a + callable and ``ctx.panels`` to show something else. The caption sits a small gap below the lowest thing drawn. Where the figure has no blank room there -- an animated 3-D plot fills its canvas -- the figure is made taller by the caption's height, and nothing already drawn moves or shrinks, so the caption never overlaps a panel, a legend or a colorbar and never leaves the - canvas. Room is made for as many lines as the first frame's - caption has (``'\\n'`` starts a new line); keep later frames to - that many. It is drawn in the plot's font (`font=`), at the + canvas. A caption wider than the figure is WRAPPED to the + figure's width (at spaces; a single word wider than the figure + is broken; your own ``'\\n'`` line breaks are kept; a line with + ``$...$`` mathtext is left whole), on every frame, so it never + leaves the canvas at the sides. The room under the plot is made + for the tallest of the captions of the FIRST, MIDDLE and LAST + frames once wrapped (a static or fixed caption: its own lines), + so a caption that grows over the animation has its room from the + start; a frame in between that needs more lines than all three + runs below that room. An empty caption (``''``) draws nothing + and adds no room. It is drawn in the plot's font (`font=`), at the default text size; it is a matplotlib ``Text`` with ``gid='hypertools-caption'``, should you want to restyle it:: @@ -9033,8 +9306,11 @@ def plot( whole grid is ONE animation: every panel runs on the same clock (`duration=` x `frame_rate=` frames), and one ``HyperAnimation`` is returned for the figure -- ``hyp.plot([a, b, c, d], panels=(1, 4), - animate=True, duration=10, caption='{index}', - save_path='grid.mp4')`` writes one video of four panels. Each + animate=True, duration=10, + caption=lambda ctx: f'frame {ctx.frame + 1}', + save_path='grid.mp4')`` writes one video of four panels (a + ``caption='{index}'`` pattern works too when the datasets are + DataFrames with a row index to read). Each panel is animated exactly as the single-axes call for its data is: every `animate=` style and `order=` value, `tail_duration=`, `rotations=`, the trail flags, `predict=`, per-frame titles and so @@ -9047,14 +9323,28 @@ def plot( raises ``ValueError``. Each 3-D panel's cube is zoomed out as far as it takes to stay inside its own cell through the whole rotation, so `zoom=` can shrink a panel's cube but cannot enlarge - it past its cell; with axis labels (`xlabel=`/`ylabel=`/`zlabel=`) - the figure is enlarged so the rotating labels fit as well (an - explicit `size=` too small for them raises, naming a size that - fits). Without `size=` the figure is sized BY THE GRID -- 3.2 in - per panel each way, at least 6.4 in wide -- so a saved clip of a - row of panels is not mostly blank canvas (a static grid keeps the - 6.4 x 4.8 in default). `caption=` adds a line of text under the grid, updated - every frame. `on_frame=` is called ONCE per frame for the whole + it past its cell. With axis labels (`xlabel=`/`ylabel=`/`zlabel=`, + or a DataFrame's column names) the cube is drawn smaller still, + so the labels stay inside the panel's own cell at every view the + animation takes (the whole turn, or the single view of + ``rotations=0``); the figure is enlarged only where that would + leave a cube under 70% of an unlabeled one's size, and by no + more than restores that. An explicit `size=` is honored down to + cubes half their unlabeled size and raises below that, naming a + size that works; ``xlabel='', ylabel='', + zlabel=''`` drops the labels instead. Without `size=` the figure + is sized BY THE GRID -- 3.2 in per panel each way, at least + 6.4 in wide -- so a saved clip of a row of panels is not mostly + blank canvas (a static grid keeps the 6.4 x 4.8 in default); it + is then widened by the strip of a shared legend or colorbar, + made taller by a `caption=`, and enlarged for axis labels as + just described. A STATIC 3-D grid keeps its axis labels inside + each panel the same way (its default figure grows where the + cubes would otherwise become very small; an explicit `size=` is + honored). `caption=` adds a line of text under the grid, updated + every frame. A per-frame `title=` (callable or ``{index}`` + pattern, one for all panels or a list with one per panel) is + given its room above each panel like a fixed title. `on_frame=` is called ONCE per frame for the whole figure: its ``FrameContext`` has ``axes`` as a tuple of the panel axes, ``artists`` and ``datasets`` as every panel's in panel order, and ``panels`` as one ordinary per-panel ``FrameContext`` @@ -15073,7 +15363,7 @@ def _real_frame_context(frame): # cloud, an unclipped trail) whose extents say nothing # about what the panel will show, and what it will show # stays inside the cell's own box at every frame (see - # `_fit_rotating_cubes`). The box, the title, the legend + # `_fit_panel_cubes`). The box, the title, the legend # and the axis labels are what the layout arranges. for _artist in (list(ax.lines) + list(ax.collections) + list(ax.patches)): @@ -15087,6 +15377,15 @@ def _real_frame_context(frame): # draw frame 0, whose title the layout then arranges # like a fixed one line_ani._func(0, *line_ani._args) + if (_grid_furniture and ax is not None + and ax.get_legend() is not None): + # this panel's legend only carries its entries to the + # grid's ONE shared legend (`_merge_panel_legends`), which + # removes it and lays the grid out afresh: laying this + # panel out around it squeezed the cell for a legend that + # is never shown, and in a grid of many panels warned + # "Tight layout not applied" once per panel + ax.get_legend().set_in_layout(False) if ((not animate or _panel_animation is not None) and not _caller_figure and isinstance(fig, plt.Figure)): diff --git a/hypertools/plot/plotly_backend.py b/hypertools/plot/plotly_backend.py index ba2c436d9..375442274 100644 --- a/hypertools/plot/plotly_backend.py +++ b/hypertools/plot/plotly_backend.py @@ -3388,7 +3388,8 @@ def place_shared_furniture(target, legend, colorbar_trace, ndims, target.layout.legend = style if colorbar_trace is not None: if side is None: - offset = PANEL_GUTTER_PAD_PX + (PANEL_LEGEND_PX if legend else 0) + offset = PANEL_GUTTER_PAD_PX + ( + PANEL_LEGEND_PX if legend and legend_position is None else 0) cb.update(x=1.0 + offset / plot_w, xanchor='left', y=0.5, yanchor='middle') elif side == 'l': diff --git a/tests/test_panel_layout_review.py b/tests/test_panel_layout_review.py new file mode 100644 index 000000000..c5ea5033b --- /dev/null +++ b/tests/test_panel_layout_review.py @@ -0,0 +1,476 @@ +"""Layout of `panels=` grids, review round 1 (GH #295). + +Axis labels of 3-D panels (static and animated) stay inside their own +panel; an animated labeled grid is enlarged no more than its labels need, +accepts the size hypertools picks itself, and names a size that works when +it refuses one; and the grid's one shared legend goes where +`legend_kwargs` asks, with room reserved only where it is drawn. + +Everything is measured on real draws of real figures (Agg), frame by +frame for animations; nothing is mocked or patched. +""" +import itertools +import re + +import matplotlib +matplotlib.use('Agg') + +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +import pytest +from mpl_toolkits.mplot3d import proj3d + +import hypertools as hyp +from hypertools.plot.plot import (CAPTION_GID, SHARED_COLORBAR_GID, + SHARED_LEGEND_GID) + + +def _walk(seed, rows=30, cols=3): + rng = np.random.default_rng(seed) + return np.cumsum(rng.normal(size=(rows, cols)), axis=0) + + +DATA = [_walk(seed) for seed in range(4)] +XYZ = [pd.DataFrame(d, columns=list('xyz')) for d in DATA] +LONG = [pd.DataFrame(d, columns=['first axis', 'second axis', + 'third axis']) for d in DATA] +ANIM = dict(animate=True, duration=1, frame_rate=6, show=False) +GRIDS = [((1, 4), 4), ((2, 2), 4), ((3, 1), 3)] + + +@pytest.fixture(autouse=True) +def _close_figures(): + yield + plt.close('all') + + +def _draw(fig): + fig.canvas.draw() + return fig.canvas.get_renderer() + + +def _cube_box(ax): + """The drawn box (pixels) of a 3-D axes' cube at its current view.""" + corners = np.array(list(itertools.product( + ax.get_xlim3d(), ax.get_ylim3d(), ax.get_zlim3d()))) + px, py, _ = proj3d.proj_transform( + corners[:, 0], corners[:, 1], corners[:, 2], ax.get_proj()) + points = ax.transData.transform(np.column_stack([px, py])) + return matplotlib.transforms.Bbox.from_extents( + points[:, 0].min(), points[:, 1].min(), + points[:, 0].max(), points[:, 1].max()) + + +def _shrunk(box, pixels=2.0): + """`box` less a couple of pixels of antialiasing on every side.""" + return matplotlib.transforms.Bbox.from_extents( + box.x0 + pixels, box.y0 + pixels, box.x1 - pixels, box.y1 - pixels) + + +def _assert_labels_clear(fig, n, frame=None): + """Every panel's axis labels are on the canvas and clear of every + OTHER panel's cube, axis labels and title, and of the shared legend, + colorbar and caption.""" + renderer = _draw(fig) + width, height = fig.canvas.get_width_height() + panels = fig.axes[:n] + furniture = [legend.get_window_extent(renderer) + for legend in fig.legends] + furniture += [ax.get_tightbbox(renderer) for ax in fig.axes + if ax.get_gid() == SHARED_COLORBAR_GID] + furniture += [text.get_window_extent(renderer) for text in fig.texts + if text.get_gid() == CAPTION_GID] + labels = {} + for i, ax in enumerate(panels): + labels[i] = [axis.label.get_window_extent(renderer) + for axis in (ax.xaxis, ax.yaxis, ax.zaxis) + if axis.label.get_text()] + assert labels[i], i + for i, ax in enumerate(panels): + for label in labels[i]: + where = (frame, i) + assert label.x0 >= -0.5 and label.x1 <= width + 0.5, where + assert label.y0 >= -0.5 and label.y1 <= height + 0.5, where + label = _shrunk(label) + for box in furniture: + assert not label.overlaps(box), where + for j, other in enumerate(panels): + if j == i: + continue + assert not label.overlaps(_cube_box(other)), (where, j) + if other.get_title(): + assert not label.overlaps( + other.title.get_window_extent(renderer)), (where, j) + for theirs in labels[j]: + assert not label.overlaps(_shrunk(theirs)), (where, j) + + +# -------------------------------------------------------------------------- +# A1 / T5: static 3-D grids +# -------------------------------------------------------------------------- + +@pytest.mark.parametrize('extras', [ + {}, dict(legend=True), dict(title=['a', 'b', 'c', 'd']), + dict(legend=True, caption='a caption', title=['a', 'b', 'c', 'd']), + dict(hue=[np.arange(30)] * 4, colorbar=True), +], ids=['bare', 'legend', 'titles', 'legend-caption-titles', 'colorbar']) +@pytest.mark.parametrize('frames', [XYZ, LONG], ids=['short', 'long']) +@pytest.mark.parametrize('shape,n', GRIDS, ids=['1x4', '2x2', '3x1']) +def test_static_3d_grid_axis_labels_stay_in_their_own_panel(shape, n, + frames, extras): + extras = {key: (value[:n] if isinstance(value, list) else value) + for key, value in extras.items()} + fig = hyp.plot(frames[:n], panels=shape, show=False, **extras) + _assert_labels_clear(fig, n) + + +def test_static_3d_grid_z_label_is_clear_of_the_legend(): + """T5: the last column's z-axis label was drawn over the legend.""" + fig = hyp.plot(XYZ, panels=(1, 4), legend=True, show=False) + renderer = _draw(fig) + legend = fig.legends[0].get_window_extent(renderer) + for ax in fig.axes[:4]: + assert not ax.zaxis.label.get_window_extent(renderer).overlaps( + legend) + + +def test_static_grid_with_an_explicit_size_keeps_that_size(): + fig = hyp.plot(LONG, panels=(1, 4), size=[8, 3], show=False) + assert tuple(fig.get_size_inches()) == (8.0, 3.0) + _assert_labels_clear(fig, 4) + + +def test_static_grid_without_axis_labels_is_not_resized_or_rezoomed(): + plain = hyp.plot(DATA, panels=(2, 2), show=False) + unlabeled = hyp.plot(XYZ, panels=(2, 2), xlabel='', ylabel='', + zlabel='', show=False) + assert tuple(plain.get_size_inches()) == (6.4, 4.8) + assert tuple(unlabeled.get_size_inches()) == (6.4, 4.8) + for a, b in zip(plain.axes, unlabeled.axes): + assert np.allclose(a.get_box_aspect(), b.get_box_aspect()) + + +def test_static_labeled_cubes_keep_a_share_of_their_cells(): + fig = hyp.plot(LONG, panels=(1, 4), show=False) + _draw(fig) + for ax in fig.axes[:4]: + cube, cell = _cube_box(ax), ax.get_window_extent() + assert cube.width >= 0.3 * cell.width + + +# -------------------------------------------------------------------------- +# A1 / A3: animated 3-D grids +# -------------------------------------------------------------------------- + +@pytest.mark.parametrize('extras', [ + {}, dict(legend=True, caption='a caption'), + dict(title=lambda ctx: f'frame {ctx.frame}'), +], ids=['bare', 'legend-caption', 'titles']) +@pytest.mark.parametrize('frames', [XYZ, LONG], ids=['short', 'long']) +@pytest.mark.parametrize('shape,n', GRIDS, ids=['1x4', '2x2', '3x1']) +def test_animated_3d_grid_axis_labels_stay_in_their_own_panel( + shape, n, frames, extras): + anim = hyp.plot(frames[:n], panels=shape, **dict(ANIM, **extras)) + for frame in range(anim.n_frames): + anim.draw_frame(frame) + _assert_labels_clear(anim.figure, n, frame) + + +@pytest.mark.parametrize('shape,n', GRIDS, ids=['1x4', '2x2', '3x1']) +def test_axis_labels_enlarge_an_animated_grid_no_more_than_they_need( + shape, n): + """A3: a 3 x 1 grid with axis labels became 6.4 x 13 in, mostly + blank, with cubes a small part of their cells.""" + plain = hyp.plot(DATA[:n], panels=shape, **ANIM) + labeled = hyp.plot(XYZ[:n], panels=shape, **ANIM) + plain_size = plain.figure.get_size_inches() + size = labeled.figure.get_size_inches() + assert size[0] <= 1.1 * plain_size[0] + assert size[1] <= 1.1 * plain_size[1] + # the cube keeps a real share of its cell at every view + fig = labeled.figure + for frame in range(labeled.n_frames): + labeled.draw_frame(frame) + _draw(fig) + for ax in fig.axes[:n]: + cube, cell = _cube_box(ax), ax.get_window_extent() + assert cube.width >= 0.38 * cell.width, frame + assert cube.width <= cell.width and cube.height <= cell.height + + +# -------------------------------------------------------------------------- +# T2: explicit size= on an animated labeled grid +# -------------------------------------------------------------------------- + +@pytest.mark.parametrize('frames', [XYZ, LONG], ids=['short', 'long']) +@pytest.mark.parametrize('extras', [{}, dict(legend=True, caption='c')], + ids=['bare', 'legend-caption']) +@pytest.mark.parametrize('shape,n', GRIDS, ids=['1x4', '2x2', '3x1']) +def test_the_size_hypertools_picks_is_accepted_as_size(shape, n, extras, + frames): + picked = hyp.plot(frames[:n], panels=shape, **dict(ANIM, **extras)) + size = [float(v) for v in picked.figure.get_size_inches()] + again = hyp.plot(frames[:n], panels=shape, size=size, + **dict(ANIM, **extras)) + assert again.n_frames == picked.n_frames + + +@pytest.mark.parametrize('frames', [XYZ, LONG], ids=['short', 'long']) +@pytest.mark.parametrize('size', [[3, 1], [2, 2], [4, 1.5]]) +@pytest.mark.parametrize('shape,n', GRIDS, ids=['1x4', '2x2', '3x1']) +def test_the_size_a_refusal_suggests_works(shape, n, size, frames): + with pytest.raises(ValueError, match='larger size=') as err: + hyp.plot(frames[:n], panels=shape, size=size, **ANIM) + message = str(err.value) + assert "xlabel='', ylabel='', zlabel=''" in message + match = re.search(r'\(\(([\d.]+), ([\d.]+)\) or more\)', message) + assert match, message + suggested = [float(match.group(1)), float(match.group(2))] + assert suggested[0] >= size[0] and suggested[1] >= size[1] + anim = hyp.plot(frames[:n], panels=shape, size=suggested, **ANIM) + for frame in (0, anim.n_frames // 2, anim.n_frames - 1): + anim.draw_frame(frame) + _assert_labels_clear(anim.figure, n, frame) + # ...and so does the advice to drop the labels + hyp.plot(frames[:n], panels=shape, size=size, xlabel='', ylabel='', + zlabel='', **ANIM) + + +def test_a_grid_that_does_not_rotate_needs_only_the_room_of_its_view(): + """`rotations=0`: the labels do not swing, so the cube is fitted for + the one view and a size that a full turn refuses can be enough.""" + turning = hyp.plot(XYZ, panels=(1, 4), **ANIM) + still = hyp.plot(XYZ, panels=(1, 4), rotations=0, **ANIM) + still.draw_frame(0) + turning.draw_frame(0) + _draw(still.figure) + _draw(turning.figure) + # the one view's cube is drawn larger than the turning one's + assert (_cube_box(still.figure.axes[0]).width + > _cube_box(turning.figure.axes[0]).width) + for frame in range(still.n_frames): + still.draw_frame(frame) + _assert_labels_clear(still.figure, 4, frame) + # ...and it is fitted for that one view: the views sampled for a + # panel that does not rotate are its own camera angle alone + from hypertools.plot.plot import _camera_azimuths + axis = still.figure.axes[0] + assert _camera_azimuths(axis, 0, 3.0) == [float(axis.azim)] + assert len(_camera_azimuths(axis, 1, 3.0)) == 121 + assert len(_camera_azimuths(axis, 0.25, 3.0)) == 31 + # a size the turning grid accepts is accepted without the turn, and + # the smallest size refused without the turn is refused with it + for size in ([8.0, 2.2], [7.0, 2.0], [6.0, 1.8], [5.0, 1.5]): + try: + hyp.plot(LONG, panels=(1, 4), size=size, **ANIM) + turning_ok = True + except ValueError: + turning_ok = False + try: + hyp.plot(LONG, panels=(1, 4), size=size, rotations=0, **ANIM) + still_ok = True + except ValueError: + still_ok = False + assert still_ok or not turning_ok, size + + +# -------------------------------------------------------------------------- +# A2: where the shared legend goes +# -------------------------------------------------------------------------- + +NAMES = ['alpha', 'beta', 'gamma', 'delta'] + + +def _legend(fig): + found = [legend for legend in fig.legends + if legend.get_gid() == SHARED_LEGEND_GID] + assert len(found) == 1 + return found[0] + + +def _grid_boxes(fig, n=4): + renderer = _draw(fig) + boxes = [ax.get_tightbbox(renderer) for ax in fig.axes[:n]] + boxes += [ax.title.get_window_extent(renderer) for ax in fig.axes[:n] + if ax.get_title()] + return renderer, boxes + + +SIDES = { + 'right': 'right', 'center right': 'right', 'upper right': 'right', + 'lower right': 'right', 'center left': 'left', + 'upper left': 'left', 'lower left': 'left', 'upper center': 'top', + 'lower center': 'bottom', 9: 'top', 6: 'left', +} + + +@pytest.mark.parametrize('ndims', [2, 3]) +@pytest.mark.parametrize('animated', [False, True], + ids=['static', 'animated']) +@pytest.mark.parametrize('loc', list(SIDES), ids=[str(k) for k in SIDES]) +def test_a_named_legend_location_is_a_strip_on_that_side(loc, animated, + ndims): + extra = dict(ANIM, caption='a caption') if animated else dict( + show=False) + result = hyp.plot(DATA, ndims=ndims, panels=(2, 2), legend=NAMES, + title=['a', 'b', 'c', 'd'], + legend_kwargs={'loc': loc}, **extra) + fig = getattr(result, 'figure', result) + frames = range(result.n_frames) if animated else [None] + for frame in frames: + if frame is not None: + result.draw_frame(frame) + renderer, boxes = _grid_boxes(fig) + width, height = fig.canvas.get_width_height() + legend = _legend(fig).get_window_extent(renderer) + # on the canvas, clear of every panel and title (and the caption) + assert legend.x0 >= 0 and legend.x1 <= width, frame + assert legend.y0 >= 0 and legend.y1 <= height, frame + for box in boxes: + assert not legend.overlaps(box), frame + for text in fig.texts: + assert not legend.overlaps(text.get_window_extent(renderer)) + side = SIDES[loc] + if side == 'right': + assert legend.x0 >= max(b.x1 for b in boxes) - 1 + elif side == 'left': + assert legend.x1 <= min(b.x0 for b in boxes) + 1 + elif side == 'top': + assert legend.y0 >= max(b.y1 for b in boxes) - 1 + else: + assert legend.y1 <= min(b.y0 for b in boxes) + 1 + + +def test_upper_and_lower_right_align_the_legend_with_the_grid(): + tops = {} + for loc in ('upper right', 'center right', 'lower right'): + fig = hyp.plot(DATA, ndims=2, panels=(2, 2), legend=NAMES, + legend_kwargs={'loc': loc}, show=False) + renderer = _draw(fig) + tops[loc] = _legend(fig).get_window_extent(renderer).y1 + plt.close(fig) + assert tops['upper right'] > tops['center right'] > tops['lower right'] + + +def test_default_legend_strip_is_unchanged_by_loc_right(): + default = hyp.plot(DATA, panels=(2, 2), legend=NAMES, show=False) + named = hyp.plot(DATA, panels=(2, 2), legend=NAMES, show=False, + legend_kwargs={'loc': 'center right'}) + assert tuple(default.get_size_inches()) == tuple(named.get_size_inches()) + a = _legend(default).get_window_extent(_draw(default)) + b = _legend(named).get_window_extent(_draw(named)) + assert np.allclose(a.extents, b.extents, atol=0.5) + + +@pytest.mark.parametrize('loc,grows', [ + ('center left', 0), ('upper center', 1), ('lower center', 1), + ('upper right', 0)]) +def test_a_legend_strip_widens_the_default_figure_on_its_side_only(loc, + grows): + plain = hyp.plot(DATA, panels=(2, 2), show=False) + fig = hyp.plot(DATA, panels=(2, 2), legend=NAMES, show=False, + legend_kwargs={'loc': loc}) + before, after = plain.get_size_inches(), fig.get_size_inches() + assert after[grows] > before[grows] + 0.2 + assert after[1 - grows] == pytest.approx(before[1 - grows]) + + +@pytest.mark.parametrize('loc', ['center left', 'lower center', + 'upper right']) +def test_an_explicit_size_holds_the_legend_strip_inside_it(loc): + fig = hyp.plot(DATA, panels=(1, 4), legend=NAMES, size=[9, 3], + show=False, legend_kwargs={'loc': loc}) + assert tuple(fig.get_size_inches()) == (9.0, 3.0) + renderer, boxes = _grid_boxes(fig) + legend = _legend(fig).get_window_extent(renderer) + assert legend.x0 >= 0 and legend.x1 <= 900 and legend.y0 >= 0 + for box in boxes: + assert not legend.overlaps(box) + + +@pytest.mark.parametrize('kwargs', [ + {'bbox_to_anchor': (0.5, 0.5), 'loc': 'center'}, + {'bbox_to_anchor': (0.02, 0.98), 'loc': 'upper left'}, + {'loc': 'center'}, {'loc': (0.3, 0.4)}, {'loc': 10}, +], ids=['anchor-center', 'anchor-corner', 'center', 'pair', 'code']) +def test_a_legend_the_caller_positions_gets_no_strip(kwargs): + """No room is reserved for a legend the caller placed: the figure and + the panels are exactly the legend-less grid's.""" + plain = hyp.plot(DATA, panels=(2, 2), show=False) + fig = hyp.plot(DATA, panels=(2, 2), legend=NAMES, show=False, + legend_kwargs=kwargs) + assert tuple(fig.get_size_inches()) == tuple(plain.get_size_inches()) + for a, b in zip(plain.axes[:4], fig.axes[:4]): + # (a reserved strip would move the panels by a tenth of the figure) + assert np.allclose(a.get_position().bounds, b.get_position().bounds, + atol=0.01) + assert len(_legend(fig).get_texts()) == 4 + + +def test_bbox_to_anchor_is_in_figure_fractions(): + fig = hyp.plot(DATA, panels=(2, 2), legend=NAMES, show=False, + legend_kwargs={'bbox_to_anchor': (0.25, 0.75), + 'loc': 'lower left'}) + renderer = _draw(fig) + width, height = fig.canvas.get_width_height() + box = _legend(fig).get_window_extent(renderer) + assert box.x0 / width == pytest.approx(0.25, abs=0.01) + assert box.y0 / height == pytest.approx(0.75, abs=0.01) + + +def test_a_bottom_legend_is_laid_out_in_columns_that_fit(): + many = [f'dataset number {i}' for i in range(12)] + data = [_walk(seed) for seed in range(12)] + fig = hyp.plot(data, panels=(3, 4), legend=many, show=False, + legend_kwargs={'loc': 'lower center'}) + renderer = _draw(fig) + width, _ = fig.canvas.get_width_height() + box = _legend(fig).get_window_extent(renderer) + assert box.x0 >= 0 and box.x1 <= width + assert _legend(fig)._ncols > 1 + + +def test_plotly_legend_the_caller_positions_gets_no_strip(): + plain = hyp.plot(DATA, panels=(2, 2), backend='plotly', show=False) + strip = hyp.plot(DATA, panels=(2, 2), backend='plotly', show=False, + legend=NAMES) + placed = hyp.plot(DATA, panels=(2, 2), backend='plotly', show=False, + legend=NAMES, legend_kwargs={'x': 0.5, 'y': 1.1}) + assert strip.layout.width > plain.layout.width + assert placed.layout.width == plain.layout.width + assert placed.layout.margin.r == plain.layout.margin.r + assert (placed.layout.legend.x, placed.layout.legend.y) == (0.5, 1.1) + assert {trace.name for trace in placed.data if trace.showlegend} == set( + NAMES) + + +@pytest.mark.parametrize('kwargs', [{}, {'loc': 'lower center'}], + ids=['right', 'bottom']) +def test_a_many_panel_grid_with_a_legend_lays_out_without_warnings(kwargs): + """Each panel was first laid out around its own (transient) legend, + which a small cell cannot hold: one "Tight layout not applied" + warning per panel.""" + import warnings + many = [f'dataset number {i}' for i in range(12)] + data = [_walk(seed) for seed in range(12)] + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + fig = hyp.plot(data, panels=(3, 4), legend=many, show=False, + legend_kwargs=kwargs) + assert not [str(w.message) for w in caught] + assert len(_legend(fig).get_texts()) == 12 + + +@pytest.mark.parametrize('shape,n', GRIDS, ids=['1x4', '2x2', '3x1']) +def test_static_long_axis_labels_do_not_run_into_each_other(shape, n): + """Fitting the labels by shrinking the cube alone left three long + labels on top of each other around a tiny cube: the default figure + grows instead.""" + fig = hyp.plot(LONG[:n], panels=shape, legend=True, show=False) + renderer = _draw(fig) + for ax in fig.axes[:n]: + boxes = [_shrunk(axis.label.get_window_extent(renderer)) + for axis in (ax.xaxis, ax.yaxis, ax.zaxis)] + for a, b in itertools.combinations(boxes, 2): + assert not a.overlaps(b) From cbdd36be5a21050d235ea89bddc6ec09c16767cd Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 06:31:07 -0500 Subject: [PATCH 19/58] docs: caption wrapping and contexts, axis-label fitting, shared legend placement (GH #295) Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- CHANGELOG.md | 57 +++++++++++++++++-- docs/animation.rst | 41 +++++++++++-- ...sion_2026-11-22_feat295-animated-panels.md | 38 +++++++++++++ 3 files changed, 124 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 86e74739e..24dd7ba1c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,12 +18,22 @@ draws into a figure the caller built, found by executing notebooks with `HyperAnimation` is returned for the figure. The combination used to raise `ValueError`. Styles and orderings play per panel, not as a sequence across panels. Each 3-D panel's cube is zoomed out as far as it - takes to stay inside its own cell through the whole rotation, and with - axis labels the figure is enlarged so the rotating labels fit. + takes to stay inside its own cell through the whole rotation. With axis + labels (`xlabel=`/`ylabel=`/`zlabel=`, or DataFrame column names) the + cube is drawn smaller still so the labels stay inside the panel's own + cell at every view the animation takes (one view for `rotations=0`); the + figure is enlarged only where that would leave a cube under 70% of an + unlabeled one's size, and an explicit `size=` that would leave cubes + under half their unlabeled size raises, naming a size that works (`xlabel='', ylabel='', zlabel=''` drops the + labels). Per-frame titles (a callable, an `'{index...}'` pattern, or a + list with one per panel) get their room above each panel, and + `animate={...}` dictionaries work as for a single plot. Without `size=`, the figure is sized by the grid (3.2 in per panel each way, at least 6.4 in wide) instead of matplotlib's fixed 6.4 x 4.8 in, so a - saved clip of a row of panels is not mostly blank canvas; a static grid's - default size is unchanged. + saved clip of a row of panels is not mostly blank canvas; it is then + widened by a shared legend or colorbar strip and made taller by a + caption. A static grid's default size is unchanged, except as noted for + axis labels under "Fixed". `on_frame=` is called once per frame for the whole figure, with a `FrameContext` whose `axes` is a tuple of the panel axes and whose new `panels` field holds one per-panel context each. `return_model=True` @@ -41,8 +51,16 @@ draws into a figure the caller built, found by executing notebooks with `caption=lambda ctx: f'timepoint {ctx.frame + 1} of {ctx.n_frames}'`. It sits just below the lowest thing drawn, and the figure is made taller where there is no blank room for it, so it never overlaps a panel, a - legend or a colorbar and never leaves the canvas. On a static plot it is - drawn once. Matplotlib only: `backend='plotly'` raises + legend or a colorbar and never leaves the canvas. A caption wider than + the figure is wrapped to its width on every frame; room is made for the + tallest of the first, middle and last frames' wrapped captions; an empty + caption adds nothing. On a static plot it is drawn once. A callable gets + the frame's real `FrameContext` (a static grid's has `datasets`, + `artists`, `axes` and `panels` filled in). Under a grid, an `{index}` + pattern shows the index of the first indexed dataset at the reveal head + of the panel that draws it, so it agrees with that panel's own + `title='{index}'` in every `animate=` style and `order=`. + Matplotlib only: `backend='plotly'` raises `NotImplementedError`, and a caller-supplied `ax=` raises `ValueError`. ### Changed @@ -75,6 +93,13 @@ draws into a figure the caller built, found by executing notebooks with legend (gid `'hypertools-shared-legend'`) and a colorbar axes (gid `'hypertools-shared-colorbar'`); on plotly, `layout.legend` and one colorbar trace. + - *Placing the shared legend.* `legend_kwargs={'loc': ...}` picks the + side of the grid the legend's strip is on (`'upper right'`, + `'center left'`, `'upper center'`, `'lower center'`, ...), and room is + reserved on that side only. `bbox_to_anchor` (matplotlib, in figure + fractions) or `x`/`y` (plotly, paper fractions of the whole grid) + place it yourself: no strip is reserved, and the panels are laid out + as without a legend. - *Where panels keep their own.* Clusters fit separately per panel (`cluster=`/`n_clusters=` with `panel_fit='independent'` or with a list-valued `reduce=`), `forecast_cluster=`/`forecast_n_clusters=`, @@ -95,6 +120,26 @@ draws into a figure the caller built, found by executing notebooks with ### Fixed +- **Axis labels of a static 3-D `panels=` grid stay inside their own + panel.** matplotlib hangs a 3-D axes' labels outside its cube, where no + layout accounts for them, so in a grid they were drawn over the next + panel's cube, over the title of the panel below, over the legend, or off + the canvas. A labeled panel's cube is now drawn smaller until its labels + fit its own cell; where that would leave the cubes very small the + default figure grows in the direction that limits them (a 1 x 4 grid of + labeled 3-D panels is wider than 6.4 in), and an explicit `size=` is + honored as given. Grids without axis labels are unchanged. +- **A failed `panels=` call leaves no figure behind.** Whatever makes a + grid call raise (a refused combination, an unknown `predict=` model, a + `title=`/`caption=` callable that raises, a failed save), every figure + the call registered with pyplot is closed first, with `show=True` as + with `show=False`. Static grids leaked one figure per failed call. +- **No `ndims` warning the caller did not cause.** `hyp.plot` on data with + fewer than three columns warned "ndims/n_components was set to 3 but the + data only has 2 feature(s)" in any `panels=` grid and with + `return_model=True`, `manip=` or `cluster=`, although `ndims` was never + passed and the plain call is silent. `hyp.reduce`/`hyp.analyze` still + warn when asked for more dimensions than the data has. - **`labels=` in a panel grid stay with their own panel.** The annotations' bookkeeping was one module-level list holding only the most recently drawn plot's labels, so in a grid only the last panel's labels were diff --git a/docs/animation.rst b/docs/animation.rst index a42d2e40b..b7125201f 100644 --- a/docs/animation.rst +++ b/docs/animation.rst @@ -728,21 +728,40 @@ A few things are specific to a grid: * Without ``size=`` the figure is sized by the grid -- 3.2 in per panel each way, and at least 6.4 in wide -- so a saved clip of a row of panels is not - mostly blank canvas. (A static grid keeps matplotlib's 6.4 x 4.8 in + mostly blank canvas. It is then widened by the strip of a shared legend or + colorbar, made taller by a ``caption=``, and enlarged for axis labels where + they need it (below). (A static grid keeps matplotlib's 6.4 x 4.8 in default.) ``size=`` sets the whole figure's size as usual. +* ``animate=`` may be given in its dictionary form + (``animate={'style': 'spin', 'rotations': 2}``) exactly as for a single + plot; per-dataset values inside it go to their panels, and + ``{'style': False}`` is a static grid. * Every panel must draw the same number of frames, or the call raises ``ValueError`` (``animate='morph'`` needs the same number of datasets in each panel). * Each 3-D panel's cube is zoomed out as far as it takes to stay inside its own cell through the whole rotation, so ``zoom=`` can shrink a panel's - cube but not enlarge it past its cell. With ``xlabel=``/``ylabel=``/ - ``zlabel=`` the figure is enlarged so the rotating axis labels fit too; - an explicit ``size=`` too small for them raises, naming a size that fits. + cube but not enlarge it past its cell. With axis labels (``xlabel=``/ + ``ylabel=``/``zlabel=``, or a DataFrame's column names) the cube is drawn + smaller still, so the labels stay inside the panel's own cell at every + view the animation takes (the whole turn, or the one view of + ``rotations=0``). The figure is enlarged only where that would leave a + cube under 70% of an unlabeled one's size, and by no more than restores + that. An explicit ``size=`` is honored down to cubes half their unlabeled + size and raises below that, naming a size that works; pass ``xlabel='', ylabel='', zlabel=''`` to drop the labels instead. +* A per-frame ``title=`` (a callable or an ``'{index...}'`` pattern, one for + every panel or a list with one per panel) gets its room above each panel + like a fixed title. * Colors, the legend and the colorbar belong to the whole grid, as in a static grid: each dataset keeps the color the single-axes call of all the datasets gives it, ``hue=`` is mapped through one scale, and one legend and/or one colorbar is drawn in a strip right of the panels. They are static across frames, and every rotating cube stays clear of the strip. + ``legend_kwargs={'loc': ...}`` moves the legend's strip to another side of + the grid (``'upper center'`` above it, ``'lower center'`` below it, + ``'center left'`` left of it, ``'upper right'`` at the top of the right-hand + strip); ``bbox_to_anchor`` places it yourself in figure fractions, with no + room reserved. (Clusters fit per panel -- ``panel_fit='independent'`` or a list-valued ``reduce=`` with ``cluster=``/``n_clusters=`` -- keep a legend per panel, because their colors mean something different in each one.) @@ -775,9 +794,19 @@ index under the reveal head, or a callable given the frame's The caption sits a small gap below the lowest thing drawn; where the figure has no blank room there (an animated 3-D plot fills its canvas) the figure is made taller by the caption's height, so the caption never overlaps a -panel, a legend or a colorbar and never leaves the canvas. Room is made for -as many lines as the first frame's caption has. On a static plot the caption +panel, a legend or a colorbar and never leaves the canvas. A caption wider +than the figure is wrapped to the figure's width, on every frame. Room is +made for the tallest of the first, middle and last frames' wrapped captions, +so a caption that grows as the animation runs has its room from the start +(a frame in between that needs more lines than all three runs below it). An +empty caption draws nothing and adds no room. On a static plot the caption is drawn once, a pattern or callable being resolved for the finished figure. + +A callable receives the frame's real ``FrameContext`` (for a grid, the +figure-level one, with one context per panel in ``ctx.panels``). Under a grid +an ``'{index...}'`` pattern shows what a panel's own ``title='{index}'`` +shows: the first dataset that carries an index is read, at the reveal head of +the panel that draws it (the first panel under a list-valued ``reduce=``). ``caption=`` raises ``NotImplementedError`` under ``backend='plotly'`` (a per-frame ``title=`` works on both backends) and ``ValueError`` with a caller-supplied ``ax=``. diff --git a/notes/session_2026-11-22_feat295-animated-panels.md b/notes/session_2026-11-22_feat295-animated-panels.md index 003ad0ee9..43882cb3e 100644 --- a/notes/session_2026-11-22_feat295-animated-panels.md +++ b/notes/session_2026-11-22_feat295-animated-panels.md @@ -89,3 +89,41 @@ removing the panels' own legends both under-reserve a 3-D panel's title room Tests: `tests/test_panels_shared_legend_colors.py` (new); the tests that asserted per-panel legends/colorbars/colors were rewritten, each with a "CHANGED for 1.2.0" comment. + +## Review round 1 fixes (2026-11-22, after the shared-legend commits) + +Source list: the scratchpad's `feat295/fix_round1.md` (C1-C5, T1-T6, S1) plus +A1-A3. Tests: `tests/test_animated_panels_review.py` (contexts, leaks, +captions, titles, warnings) and `tests/test_panel_layout_review.py` (3-D axis +labels, explicit sizes, shared-legend placement). + +- `_resolve_animate_argument` is the one resolver of `animate=` (dict form, + sugar styles, scalars); `plot()` and `_plot_panels_impl` both call it. +- `_plot_panels` is now a wrapper that closes every pyplot figure a failed + grid call registered; the implementation is `_plot_panels_impl`. +- Captions: `_wrap_caption` wraps to the figure width (per frame, through + `_set_caption_text`); `_add_caption(samples=)` sizes the room for the + first/middle/last frames (`_caption_sample_frames`). `caption=''` is no + caption. Contexts are real: `_real_frame_context` in `plot()`, + `_static_grid_context` for a static grid. +- Grid `{index}` caption: `_make_title_pattern_resolver` reads the context of + the panel that draws the first indexed dataset (panel 0 for reducer grids). +- A panel cell with a per-frame title draws frame 0 before `tight_layout`, so + the title has room. +- `_fit_panel_cubes` (was `_fit_rotating_cubes`): matplotlib's 3-D label + offset SCALES with the cube (measured: label reach ~1.45 x cube reach in a + 3.2 in cell), so labels are fitted by shrinking the cube proportionally; + the figure grows only when a cube would fall under 70% of an unlabeled one + (`_PANEL_LABELED_CUBE_REACH`), in steps of at most 20%, in the limiting + direction. Static grids use the same fitter through + `_fit_static_cube_labels` (floor `_STATIC_LABELED_CUBE_REACH`, explicit + `size=` honored). The camera views come from `_camera_azimuths` + (`rotations=0` is one view). +- Shared legend placement: `_shared_legend_side` maps a `legend_kwargs` `loc` + to a strip side; `_grow_figure` adds room on any side; `bbox_to_anchor` / + `loc='center'` / plotly `x`/`y` reserve nothing. +- `analyze(internal=True)` no longer warns about the display `ndims` on its + Pipeline path. +- `tests/test_animated_panels.py::test_axis_labels_enlarge_the_figure...` + still asserts labeled > plain width for long labels; it passes because the + 70% floor makes long labels grow the figure slightly. It was not edited. From 468a4cf415e756c9adc73e0dff7f05facf54cd82 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 06:31:19 -0500 Subject: [PATCH 20/58] notes: review round 1 constants Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- notes/session_2026-11-22_feat295-animated-panels.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/notes/session_2026-11-22_feat295-animated-panels.md b/notes/session_2026-11-22_feat295-animated-panels.md index 43882cb3e..7c78815e4 100644 --- a/notes/session_2026-11-22_feat295-animated-panels.md +++ b/notes/session_2026-11-22_feat295-animated-panels.md @@ -114,10 +114,12 @@ labels, explicit sizes, shared-legend placement). offset SCALES with the cube (measured: label reach ~1.45 x cube reach in a 3.2 in cell), so labels are fitted by shrinking the cube proportionally; the figure grows only when a cube would fall under 70% of an unlabeled one - (`_PANEL_LABELED_CUBE_REACH`), in steps of at most 20%, in the limiting - direction. Static grids use the same fitter through - `_fit_static_cube_labels` (floor `_STATIC_LABELED_CUBE_REACH`, explicit - `size=` honored). The camera views come from `_camera_azimuths` + (`_PANEL_LABELED_CUBE_SHARE`), in steps of at most 20%, in the limiting + direction. An explicit `size=` is refused only under 50% + (`_REFUSED_LABELED_CUBE_SHARE`); the suggested size keeps the caller's + proportions and is found by fitting at that size. Static grids use the + same fitter through `_fit_static_cube_labels` (65%, + `_STATIC_LABELED_CUBE_SHARE`; explicit `size=` honored, never refused). The camera views come from `_camera_azimuths` (`rotations=0` is one view). - Shared legend placement: `_shared_legend_side` maps a `legend_kwargs` `loc` to a strip side; `_grow_figure` adds room on any side; `bbox_to_anchor` / From 7a920b2eba1a3f9c01f51747e3cb263f0f494086 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 07:15:46 -0500 Subject: [PATCH 21/58] fix: a panel grid resolves its colors, legend and colorbar once, as the single-axes call does (GH #295) Review round 2 (Codex 1-8, 10; tester R2-R7, R10). One mechanism replaces the per-panel decisions: _resolve_grid_colors makes the single-axes call of every dataset (analyzed rows, no analysis) and each panel is handed its share through plot()'s internal _panel_shared: - hue classification (integer hue categorical vs continuous) is the grid's - an all-NaN or all-unlabeled panel draws gray under the grid's scale - the grid's one colorbar is that call's (dataset colors included), also beside per-panel legends - a legend= list is validated against the grid and names the grid's categories/clusters; legend entries are in the single-axes order - palette mappings are narrowed before independent fits - whole-call warnings (non-finite hue count, legend on a continuous hue) are issued once - the bundle's 'colors' is that call's scale - plotly: line width and marker size are part of a legend entry's look; names= alone shows the grid's legend Single-axes fixes met on the way: a legend= list under a categorical hue names the categories on the line path too, and a colorbar for datasets drawn in one explicit color shows that color. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/plot/plot.py | 582 ++++++++++++++---- hypertools/plot/plotly_backend.py | 34 +- ...sion_2026-11-22_feat295-animated-panels.md | 41 ++ tests/test_panels_global_resolution.py | 572 +++++++++++++++++ tests/test_panels_shared_legend_colors.py | 13 + 5 files changed, 1107 insertions(+), 135 deletions(-) create mode 100644 tests/test_panels_global_resolution.py diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index 3eee952f7..8de34d06a 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -4683,7 +4683,7 @@ def _add_caption(fig, text, font=None, family=None, samples=()): return artist -def _panel_probe(data, kw, ndims, caught_warnings): +def _panel_probe(data, kw, ndims, caught_warnings, panel_shared=None): """Fit one panel grid's pipeline exactly as the equivalent single-axes call fits it -- by MAKING that call (``return_model=True``, figure thrown away) -- and hand back ``(xform, pipeline, clustering, colors)`` @@ -4703,8 +4703,13 @@ def _panel_probe(data, kw, ndims, caught_warnings): format_data/analyze here -- is what makes "a panel is analyzed exactly as the single-axes call analyzes it" true by construction. The warnings the call raises are appended to `caught_warnings` (see - `_reemit_panel_warnings`).""" + `_reemit_panel_warnings`). `panel_shared` is the panel's share of the + grid's color resolution (``plot``'s ``_panel_shared``), for a probe of + ONE panel (``panel_fit='independent'``): the probe reads its `hue=` as + the panel's drawing call will.""" probe_kwargs = dict(kw) + if panel_shared: + probe_kwargs['_panel_shared'] = dict(panel_shared) probe_kwargs.update(return_model=True, show=False, save_path=None, colorbar=None, legend=None, labels=None, names=None, surface=None, density=None, title=None) @@ -4869,29 +4874,125 @@ def _panel_dataset_colors(grid_kw, sources): return colors -def _panel_color_probe(lengths, grid_kw): - """The color scale the single-axes call of every dataset resolves for - the grid's `hue=` (its bundle's ``'colors'``), for a grid with no such - call to read it from (``panel_fit='independent'`` fits each panel - alone): that call's color resolution, run on placeholder rows of the - datasets' own lengths with no analysis. None when it cannot be - resolved (the grid then keeps per-panel legends and colorbars).""" - rows = [np.column_stack([np.linspace(0.0, 1.0, max(int(n), 1)), - np.linspace(1.0, 0.0, max(int(n), 1)) ** 2, - np.sin(np.arange(max(int(n), 1)))]) - for n in lengths] - try: - with warnings.catch_warnings(): - warnings.simplefilter('ignore') - probe = plot(rows, hue=grid_kw.get('hue'), - palette=grid_kw.get('palette') or 'hls', - fmt=grid_kw.get('fmt'), reduce=None, show=False, - return_model=True, backend='matplotlib') - except Exception: # noqa: BLE001 - reported by the panel calls instead - return None +#: the `plot()` arguments that decide what a figure's colors mean and what +#: explains them: the colors themselves, the legend's entries and the +#: colorbar. A `panels=` grid resolves them ONCE (`_resolve_grid_colors`). +_GRID_COLOR_KWARGS = ('fmt', 'hue', 'palette', 'color', 'colors', 'legend', + 'names', 'colorbar', 'hue_mode', 'color_reduce') + + +def _placeholder_rows(lengths, width=3): + """Stand-in rows for datasets of the given `lengths`, `width` columns + wide: what `_resolve_grid_colors` is run on when the datasets' analyzed + rows do not exist yet (``panel_fit='independent'`` resolves its `hue=` + before any panel is fit) or cannot share one axes (panels of unequal + width). Colors, legend entries and the colorbar do not depend on the + coordinates.""" + rows = [] + for n in lengths: + n = max(int(n), 1) + columns = [np.linspace(0.0, 1.0, n), np.linspace(1.0, 0.0, n) ** 2, + np.sin(np.arange(n))] + rows.append(np.column_stack(columns[:max(1, min(int(width), 3))])) + return rows + + +def _resolve_grid_colors(rows, grid_kw, ndims, caught_warnings, + clustering=None, keys=_GRID_COLOR_KWARGS): + """Resolve, ONCE and for the whole grid, everything a one-panel-per- + dataset `panels=` grid's colors mean -- exactly as the equivalent + single-axes call of all the datasets resolves it, by MAKING that call + (on `rows`, the datasets' analyzed rows, with no analysis; the figure + is thrown away). Every panel is then handed its share (``plot``'s + ``_panel_shared``); no panel re-decides any of this from its own + subset of the data. + + `grid_kw` is the grid's own kwargs, of which `keys` are forwarded + (`_GRID_COLOR_KWARGS`); `clustering` the grid's one clustering, replayed + (`_panel_cluster_labels` over every dataset), or None. The call's + errors are the grid's errors (a `legend=` list of the wrong length is + refused with the count of the grid's datasets or groups, a `palette=` + mapping naming a category no dataset has, a `colorbar=` nothing can be + put on), and its warnings are appended to `caught_warnings`, to be + issued once for the grid (the number of non-finite hue values over all + the panels, a legend asked of a continuous hue). + + Returns a dict: + + - ``'scale'``: the call's color scale (its bundle's ``'colors'``): + whether the hue is ``'continuous'`` or ``'discrete'``, its value + range, its ``{category: color}`` mapping; + - ``'categories'``: that mapping keyed by the hue's own categories + (the scale's is keyed by legend label, which a `legend=` list + changes); + - ``'colorbar'``: the colorbar the call draws (`_build_colorbar_info`), + or None -- the grid's one colorbar; + - ``'legend_names'``: ``{category: legend label}`` where the legend + names hue categories or clusters under a `legend=` list, else None; + - ``'legend_labels'``: the legend label of every trace the call draws + (``'_nolegend_'`` for a trace without an entry), or None without a + legend; + - ``'legend_order'``: the legend's labels in the order the call lists + them, or None without a legend. + """ + kw = {key: grid_kw[key] for key in keys if key in grid_kw} + if clustering is not None: + kw.update(cluster=clustering, n_clusters=None) + report, colorbars = {}, [] + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + probe = plot(rows, reduce=None, normalize=None, align=None, + ndims=ndims, show=False, return_model=True, + backend='matplotlib', + _panel_shared={'colorbars': colorbars, + 'report': report}, **kw) + caught_warnings.extend(caught) if isinstance(probe.get('fig'), plt.Figure): plt.close(probe['fig']) - return probe.get('colors') + legend = report.get('legend') + groups = report.get('group_names') + names = order = None + if isinstance(legend, list): + order = report.get('legend_order') or [ + str(label) for label in legend if label != '_nolegend_'] + if groups is not None and grid_kw.get('legend') is not True: + names = {str(group): label + for group, label in zip(groups, legend) + if group != '_nolegend_'} + scale = probe.get('colors') + categories = (scale.get('categories') or {} + if isinstance(scale, dict) else {}) + if names and all(str(label) in categories for label in names.values()): + # the scale names its colors by legend label; the panels' hue + # holds the categories themselves + categories = {group: categories[str(label)] + for group, label in names.items()} + return {'scale': scale, + 'categories': dict(categories), + 'colorbar': colorbars[0] if colorbars else None, + 'legend_names': names, + 'legend_labels': (list(legend) if isinstance(legend, list) + else None), + 'legend_order': None if order is None else list(order)} + + +def _panel_hue_scale_probe(lengths, grid_kw): + """What the single-axes call of every dataset resolves for the grid's + `hue=` (a `_resolve_grid_colors` result, of which the scale and its + categories are read), for + ``panel_fit='independent'``, BEFORE any panel is fit: each panel's fit + is a call of its own, which must already read its `hue=` and + `palette=` under the grid's scale (a ``{category: color}`` palette + names the grid's categories, not one panel's). Resolved on placeholder + rows of the datasets' own lengths, from `hue=`, `palette=` and `fmt=` + alone; None when that fails -- the full resolution, run once the + panels are fit, then reports the error.""" + try: + return _resolve_grid_colors( + _placeholder_rows(lengths), grid_kw, 3, [], + keys=('fmt', 'hue', 'palette', 'hue_mode', 'color_reduce')) + except Exception: # noqa: BLE001 - reported by the full resolution + return None def _hue_label_strings(hue): @@ -4917,22 +5018,30 @@ def _walk(value): return out -def _panel_apply_hue_scale(kw, scale, shared): +def _panel_apply_hue_scale(kw, resolution, shared): """Make one panel (kwargs `kw`, already narrowed to its dataset) draw - its `hue=` under the GRID's color scale `scale` (the single-axes - call's ``'colors'``): a continuous hue is mapped over the grid-wide - value range (``shared['limits']``, see `plot`'s ``_panel_shared``), - and a categorical hue through the grid's own ``{category: color}`` + its `hue=` under the GRID's color scale (`resolution`, a + `_resolve_grid_colors` result: the single-axes call's ``'colors'`` + and its ``{category: color}`` mapping): the hue is continuous or categorical as the + grid's is (``shared['hue_kind']``, see `plot`'s ``_panel_shared``), a + continuous hue is mapped over the grid-wide value range + (``shared['limits']``), and a categorical hue through the grid's own ``{category: color}`` mapping, narrowed to the categories this panel has (a `palette=` mapping may only name categories the plot draws). Returns False when the panel has a category the scale does not know -- the grid then cannot claim one shared mapping.""" + scale = None if resolution is None else resolution.get('scale') if not isinstance(scale, dict) or kw.get('hue') is None: return True + if scale.get('kind') in ('continuous', 'discrete'): + # the grid's classification of a numeric hue (integers are + # categorical or continuous by how many distinct values the WHOLE + # grid has), which the panel draws under + shared['hue_kind'] = scale['kind'] if scale.get('kind') == 'continuous': shared['limits'] = (float(scale['vmin']), float(scale['vmax'])) return True - categories = scale.get('categories') or {} + categories = resolution.get('categories') or {} if scale.get('kind') != 'discrete' or not categories \ or _looks_like_dataset_palettes(kw.get('palette')): return True @@ -4942,9 +5051,11 @@ def _panel_apply_hue_scale(kw, scale, shared): return False if any(label not in categories for label in present): return False - if present: - kw['palette'] = {label: tuple(categories[label]) - for label in categories if label in present} + # (a panel with no labeled observation names no category at all: it + # draws its unlabeled points, which take no palette color) + kw['palette'] = ({label: tuple(categories[label]) + for label in categories if label in present} + if present else 'hls') return True @@ -4982,13 +5093,15 @@ def _plain(value): return repr(signature) -def _merge_panel_legends(panel_axes): +def _merge_panel_legends(panel_axes, order=None): """The ONE legend a grid draws for its panels' legends: ``(handles, labels, template)``, or None when no panel drew a legend. `template` is the first panel legend, whose text styling the shared one copies. The entries are the union of the panels', without duplicates: the data - entries in panel (dataset) order, then the `predict=`/`truth=` overlay + entries in `order` -- the labels in the order the single-axes call of + every dataset lists them (`_resolve_grid_colors`), when it covers them + -- else in panel (dataset) order, then the `predict=`/`truth=` overlay entries. Two entries are one when they have the same label and look the same. An overlay entry that differs between panels only in color (one model's forecasts, each continuing a dataset of another color) is @@ -5034,8 +5147,12 @@ def _merge_panel_legends(panel_axes): raise _PanelFurnitureConflict(label) if template is None: return None - ordered = ([e for e in entries if not e['overlay']] - + [e for e in entries if e['overlay']]) + data = [e for e in entries if not e['overlay']] + if order is not None and len(set(order)) == len(order) \ + and {e['label'] for e in data} <= set(order) \ + and len({e['label'] for e in data}) == len(data): + data.sort(key=lambda e: order.index(e['label'])) + ordered = data + [e for e in entries if e['overlay']] handles = [] for entry in ordered: handle = entry['handle'] @@ -5088,14 +5205,29 @@ def _merge_panel_colorbars(infos, order=None): return merged -def _merge_panel_color_scales(scales, dataset_mode=False, names=None): - """A grid bundle's ``'colors'``: the one color scale its panels share, - merged from each panel's own (`scales`, the panel bundles' +def _grid_color_scale(scales, resolved, dataset_mode=False): + """A grid bundle's ``'colors'``: `resolved`, the color scale of the + single-axes call of every dataset (`_resolve_grid_colors`), which the + panels drew their shares of -- so a grid whose every panel holds one + category still reports all of them, by name. Where there is none (a + reducer-list grid) or the panels drew another kind of scale than it + (`scales`, the panels' own), the panels' scales are merged + (`_merge_panel_color_scales`).""" + kinds = {s.get('kind') for s in scales if isinstance(s, dict)} + if isinstance(resolved, dict) and kinds <= {resolved.get('kind')}: + return resolved + return _merge_panel_color_scales(scales, dataset_mode=dataset_mode) + + +def _merge_panel_color_scales(scales, dataset_mode=False): + """A grid bundle's ``'colors'`` where the grid has no resolved scale + of its own (see `_grid_color_scale`): the one color scale its panels + share, merged from each panel's own (`scales`, the panel bundles' ``'colors'``). Continuous scales are the grid's common one; discrete scales merge into the union of their groups -- every dataset's color, - in panel order, for a one-panel-per-dataset grid (`dataset_mode`) with - nothing grouping the data (labeled with `names`, the grid's `legend=` - list, when given), otherwise ``label -> color`` by name. Where + in panel order, numbered 1..n, for a one-panel-per-dataset grid + (`dataset_mode`) with nothing grouping the data, otherwise + ``label -> color`` by name. Where the panels' scales do not combine (colors that mean different things per panel), the first panel's is returned as before and each panel's own is in ``panel_models[i]['colors']``.""" @@ -5113,10 +5245,7 @@ def _merge_panel_color_scales(scales, dataset_mode=False, names=None): if ungrouped: colors = [np.asarray(s['colors'][0], dtype=float)[:3] for s in scales] - if names is not None and len(names) == len(scales): - labels, named = list(names), True - else: - labels, named = [i + 1 for i in range(len(scales))], False + labels, named = [i + 1 for i in range(len(scales))], False else: try: merged = _merge_panel_colorbars( @@ -5650,6 +5779,15 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): #: the color scale the single-axes call of the whole grid resolves #: (its bundle's ``'colors'``), which the panels share grid_scale = None + #: per panel, what `plot()` reads as ``_panel_shared``: the panel's + #: share of the grid's color resolution (`_resolve_grid_colors`) + panel_shared = [{} for _ in range(n_panels)] + #: whether a panel's categories turned out not to be the grid scale's + #: (the grid then cannot claim one shared mapping) + scale_mismatch = False + #: the grid's ONE clustering (a shared fit's), replayed by the color + #: resolution over every dataset + grid_clustering = None #: per panel: the input datasets it draws (for their index/column #: labels), its analyzed rows (one array per dataset), its fitted #: pipeline, and its narrowed kwargs @@ -5687,8 +5825,25 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): # mode _panel_narrow_kwargs(kw, i, n_panels, lengths) panel_kwargs.append(kw) + if shared.get('hue') is not None and not ( + shared.get('cluster') + or shared.get('n_clusters') is not None): + # (clusters override `hue=`, and each panel fits its own) + # each panel's fit is a call of its own, so the grid's `hue=` + # scale is resolved -- and each panel's share of it handed + # over -- BEFORE any of them runs: a ``{category: color}`` + # palette names the GRID's categories, and a panel refused the + # ones it does not hold + _early = _panel_hue_scale_probe(lengths, shared) + for i in range(n_panels): + if not _panel_apply_hue_scale(panel_kwargs[i], _early, + panel_shared[i]): + scale_mismatch = True + elif _early is not None: + panel_shared[i]['quiet'] = True probes = [_panel_probe(panel_sources[i], panel_kwargs[i], ndims, - probe_warnings) + probe_warnings, + panel_shared=panel_shared[i]) for i in range(n_panels)] panel_xforms = [probe[0] for probe in probes] panel_pipelines = [probe[1] for probe in probes] @@ -5715,6 +5870,10 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): # cluster must not shift the others' colors, round 9) panel_clusters = [] offsets = np.cumsum([0] + lengths) + if shared_clustering is not None: + grid_clustering = _panel_cluster_labels( + shared_clustering[0], shared_clustering[1], + shared.get('cluster'), categories=shared_clustering[2]) for i in range(n_panels): kw = dict(shared) _panel_narrow_kwargs(kw, i, n_panels, lengths) @@ -5736,23 +5895,34 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): # COLOR MEANS ONE THING ACROSS THE FIGURE (1.2). A reducer-list grid's # panels each draw every dataset through the same color resolution, so # they agree already. A one-panel-per-dataset grid's panels each see - # one dataset, so the grid resolves what the single-axes call of ALL - # the datasets would draw and hands every panel its share: its - # dataset's color (palette position i of n), its number under - # ``legend=True``, and the grid's `hue=` scale (one value range for a - # continuous hue, one category -> color mapping for a categorical one). - meanings_differ = _panel_meanings_differ(shared, per_panel_reduce, - panel_fit) - #: per panel, what `plot()` reads as ``_panel_shared`` - panel_shared = [{} for _ in range(n_panels)] - #: the names a one-panel-per-dataset grid's bundle lists its datasets' - #: colors under (the `legend=` list), when nothing groups the data - color_names = None - if not per_panel_reduce: - if shared.get('hue') is not None and panel_fit == 'independent': - grid_scale = _panel_color_probe(lengths, shared) - if grid_scale is None: - meanings_differ = True + # one dataset, so the grid resolves ONCE what the single-axes call of + # ALL the datasets draws (`_resolve_grid_colors`: that very call, on + # the analyzed rows) and hands every panel its share: its dataset's + # color (palette position i of n), its number or name in the legend, + # the grid's `hue=` scale (continuous or categorical, one value range, + # one category -> color mapping) and the grid's names for its + # categories. The legend's order, the colorbar and the bundle's + # ``'colors'`` are that call's; so are its errors and its warnings. + meanings_differ = (_panel_meanings_differ(shared, per_panel_reduce, + panel_fit) or scale_mismatch) + #: the grid's color resolution; None for a reducer-list grid, and where + #: every panel fits clusters of its own (no grid-wide meaning exists) + resolution = None + clustered = bool(shared.get('cluster')) \ + or shared.get('n_clusters') is not None + if not per_panel_reduce and not (clustered + and panel_fit == 'independent'): + _rows = [_panel_frame(src[0], xf[0]) + for src, xf in zip(panel_sources, panel_xforms)] + if len({int(xf[0].shape[1]) if xf[0].ndim == 2 else 1 + for xf in panel_xforms}) > 1: + # panels of unequal width (independent fits) share no axes + _rows = _placeholder_rows([len(xf[0]) for xf in panel_xforms], + width=panel_ndims) + resolution = _resolve_grid_colors( + _rows, shared, panel_ndims, probe_warnings, + clustering=grid_clustering) + grid_scale = resolution['scale'] # one drawn trace per dataset (ndims=1 draws one line per COLUMN, # colored by column in every panel alike) one_trace = panel_ndims != 1 or all( @@ -5760,29 +5930,43 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): for xf in panel_xforms for xi in xf) own_colors = (_panel_dataset_colors(shared, datasets) if one_trace else [None] * n_panels) - ungrouped = (shared.get('hue') is None and not shared.get('cluster') - and shared.get('n_clusters') is None) - _legend = shared.get('legend') - if (ungrouped and isinstance(_legend, (list, tuple)) - and len(_legend) == n_panels): - color_names = list(_legend) + ungrouped = shared.get('hue') is None and not clustered for i in range(n_panels): kw = panel_kwargs[i] + # the warnings about the whole call are the resolution's + panel_shared[i]['quiet'] = True if own_colors[i] is not None: kw['color'] = [own_colors[i]] - if (kw.get('legend') is True and ungrouped and panel_ndims != 1 - and kw.get('names') is None): - # the single-axes call numbers its datasets 1..n; every - # panel numbered its own dataset 1 - kw['legend'] = [i + 1] - if not _panel_apply_hue_scale(kw, grid_scale, panel_shared[i]): + _labels = resolution['legend_labels'] + if (kw.get('legend') is True and ungrouped and one_trace + and kw.get('names') is None and _labels is not None + and len(_labels) == n_panels): + # the single-axes call numbers its datasets 1..n (or, in + # ndims=1 series mode, calls them 'dataset 1'..'dataset + # n'); every panel called its own dataset the first + kw['legend'] = [_labels[i]] + if resolution['legend_names'] is not None: + # a `legend=` list naming the grid's categories/clusters: + # each panel labels the ones it draws + kw['legend'] = True + panel_shared[i]['legend_names'] = resolution['legend_names'] + if not _panel_apply_hue_scale(kw, resolution, panel_shared[i]): # a panel's categories are not the grid scale's: no # shared mapping to claim meanings_differ = True - #: the grid scale's category order, for the shared colorbar + #: the grid scale's category order, for a merged colorbar scale_order = (list(grid_scale['categories']) if isinstance(grid_scale, dict) and grid_scale.get('categories') else None) + #: the grid's one colorbar and the order of its one legend's entries, + #: as the single-axes call draws them (a reducer-list grid merges its + #: panels' instead: each already drew every dataset) + # (...also where the LEGENDS end up per panel, a label looking + # different in two panels: the colorbar is the grid's all the same) + grid_colorbar = (None if resolution is None or meanings_differ + else resolution['colorbar']) + legend_order = (None if resolution is None + else resolution['legend_order']) panel_data = [] for i in range(n_panels): kw = panel_kwargs[i] @@ -5854,8 +6038,10 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): plotly_kwargs, shared_pipeline=shared_pipeline, panel_pipelines=panel_pipelines, panel_shared=panel_shared, consolidate=not meanings_differ, - scale_order=scale_order, color_names=color_names, - dataset_mode=not per_panel_reduce) + scale_order=scale_order, + dataset_mode=not per_panel_reduce, + grid_colorbar=grid_colorbar, legend_order=legend_order, + grid_scale=(None if resolution is None else grid_scale)) _reemit_panel_warnings(probe_warnings, draw_warnings) return grid @@ -5897,6 +6083,9 @@ def _draw_grid(consolidate): kw['_panel_shared'] = dict( panel_shared[i], **({'colorbars': colorbars} if consolidate else {})) + if grid_colorbar is not None: + # the grid's one colorbar is already resolved + kw['colorbar'] = None if panel_ndims < (3 if ndims is None else min(ndims, 3)): # cells lowered to the data's width # (`_panel_cell_ndims`): the panel call's `ax=` @@ -5930,12 +6119,14 @@ def _draw_grid(consolidate): panel_axes = list(axes[:n_panels]) if consolidate: try: - legend_spec = _merge_panel_legends(panel_axes) - colorbar_info = _merge_panel_colorbars(colorbars, scale_order) + legend_spec = _merge_panel_legends(panel_axes, legend_order) + colorbar_info = (grid_colorbar if grid_colorbar is not None + else _merge_panel_colorbars(colorbars, + scale_order)) except _PanelFurnitureConflict: plt.close(fig) consolidate = False - legend_spec = colorbar_info = None + legend_spec, colorbar_info = None, grid_colorbar (fig, axes, panel_models, cells, draw_warnings, colorbars) = _draw_grid(False) panel_axes = list(axes[:n_panels]) @@ -5943,8 +6134,8 @@ def _draw_grid(consolidate): for spare in axes[n_panels:]: spare.set_visible(False) strip = None - if consolidate and (legend_spec is not None - or colorbar_info is not None): + if (consolidate and legend_spec is not None) \ + or colorbar_info is not None: # room for them is reserved ONCE, in a strip right of the grid: # the default figure grows by the strip's measured width (an # explicit `size=` is honored verbatim, the grid laid out beside @@ -5979,9 +6170,10 @@ def _draw_grid(consolidate): _scales = ([m.get('colors') for m in panel_models] if return_model else [cell['colors'] for cell in cells]) grid_colors = (_scales[0] if _scales and meanings_differ - else _merge_panel_color_scales( - _scales, dataset_mode=not per_panel_reduce, - names=color_names)) + else _grid_color_scale( + _scales, + None if resolution is None else grid_scale, + dataset_mode=not per_panel_reduce)) if animated: return _animate_panel_grid( @@ -6585,7 +6777,8 @@ def _plot_panels_plotly(panel_data, panel_kwargs, titles, nrows, ncols, ndims, call_kwargs, shared_pipeline=None, panel_pipelines=None, panel_shared=None, consolidate=False, scale_order=None, - color_names=None, dataset_mode=False): + dataset_mode=False, grid_colorbar=None, + legend_order=None, grid_scale=None): """`panels=` under the plotly backend: the same grid, built with `plotly.subplots.make_subplots` (3-D panels get ``type='scene'`` cells). Each panel is drawn by an ordinary `plot()` call and its traces @@ -6594,9 +6787,11 @@ def _plot_panels_plotly(panel_data, panel_kwargs, titles, nrows, ncols, With `consolidate` the grid shows ONE legend and ONE colorbar for the figure, as the matplotlib grid does (see `_plot_panels`): `panel_shared` is each panel's ``_panel_shared``, `scale_order` the - grid color scale's category order, and `color_names`/`dataset_mode` - what `_merge_panel_color_scales` builds the bundle's ``'colors'`` - from. + grid color scale's category order, and `grid_colorbar`, + `legend_order` and `grid_scale` the grid's one colorbar, the order of + its legend's entries and its color scale as `_resolve_grid_colors` + resolved them (None for a reducer-list grid, whose panels' own are + merged; `dataset_mode` is False for one). `return_model=True` gets the SAME bundle shape the matplotlib panel path returns -- ``fig``, ``axes``, ``panels``, ``panel_models``, @@ -6642,6 +6837,9 @@ def _draw_panels(consolidate): kw['_panel_shared'] = dict( panel_shared[i] if panel_shared is not None else {}, **({'colorbars': colorbars} if consolidate else {})) + if grid_colorbar is not None: + # the grid's one colorbar is already resolved + kw['colorbar'] = None result = plot(data, **kw) figs.append(result['fig'] if return_model else result) if return_model: @@ -6660,16 +6858,24 @@ def _draw_panels(consolidate): panel_figs, panel_models, colorbars = _draw_panels(consolidate) shared_legend = False colorbar_info = None + # a legend is asked for by `legend=`, or by `names=` alone (which + # names the datasets in one) unless ``legend=False`` -- as on one axes + legend_wanted = (bool(call_kwargs.get('legend')) + or (call_kwargs.get('legend') is None + and call_kwargs.get('names') is not None)) if consolidate: try: - shared_legend = (merge_panel_legends(panel_figs) - and bool(call_kwargs.get('legend'))) - colorbar_info = _merge_panel_colorbars(colorbars, scale_order) + shared_legend = (merge_panel_legends(panel_figs, legend_order) + and legend_wanted) + colorbar_info = (grid_colorbar if grid_colorbar is not None + else _merge_panel_colorbars(colorbars, + scale_order)) except (PanelFurnitureConflict, _PanelFurnitureConflict): consolidate = False - shared_legend, colorbar_info = False, None + shared_legend, colorbar_info = False, grid_colorbar panel_figs, panel_models, colorbars = _draw_panels(False) - legend_present = call_kwargs.get('legend') is not None + legend_present = (call_kwargs.get('legend') is not None + or legend_wanted) colorbar_present = any( getattr(getattr(trace, 'marker', None), 'showscale', None) for panel in panel_figs for trace in panel.data) @@ -6689,13 +6895,12 @@ def _draw_panels(consolidate): panel_figs[0].layout.legend.to_plotly_json() if panel_figs[0].layout.legend is not None else {}) strip_px = 0 - if consolidate: - if shared_legend and _position is None: - strip_px += PANEL_LEGEND_PX - if colorbar_info is not None \ - and colorbar_info.get('location', 'right') == 'right': - strip_px += PANEL_COLORBAR_PX - strip_px += PANEL_GUTTER_PAD_PX if strip_px else 0 + if shared_legend and _position is None: + strip_px += PANEL_LEGEND_PX + if colorbar_info is not None \ + and colorbar_info.get('location', 'right') == 'right': + strip_px += PANEL_COLORBAR_PX + strip_px += PANEL_GUTTER_PAD_PX if strip_px else 0 fig = make_panel_grid(nrows, ncols, ndims, size=call_kwargs.get('size'), gutter_px=(0 if consolidate else panel_gutter_px( @@ -6707,7 +6912,7 @@ def _draw_panels(consolidate): i, ndims) panel_axes.append(keys['scene'] if ndims >= 3 else (keys['xaxis'], keys['yaxis'])) - if consolidate and (shared_legend or colorbar_info is not None): + if shared_legend or colorbar_info is not None: place_shared_furniture( fig, shared_legend, (None if colorbar_info is None else _colorbar_trace( @@ -6718,7 +6923,7 @@ def _draw_panels(consolidate): font=(panel_figs[0].layout.font.to_plotly_json() if panel_figs[0].layout.font is not None else None), title_px=title_px, widen=call_kwargs.get('size') is None) - fig.update_layout(showlegend=bool(call_kwargs.get('legend'))) + fig.update_layout(showlegend=legend_wanted) # the SAME figure class the single-axes plotly path returns, displayed # through the same one-shot end-of-cell queue: a bare `go.Figure` shown # with `fig.show()` here was displayed a second time by the notebook's @@ -6754,9 +6959,9 @@ def _draw_panels(consolidate): else m['xform_data'] for m in panel_models], 'colors': ( (panel_models[0].get('colors') if panel_models else None) - if not consolidate else _merge_panel_color_scales( - [m.get('colors') for m in panel_models], - dataset_mode=dataset_mode, names=color_names)), + if not consolidate else _grid_color_scale( + [m.get('colors') for m in panel_models], grid_scale, + dataset_mode=dataset_mode)), 'pipeline': shared_pipeline, } return fig @@ -7546,8 +7751,15 @@ def plot( item); the list must have exactly one entry per drawn dataset/ group (``ValueError`` naming legend otherwise). A bare string is treated as a single-entry list (valid only for a single dataset). + Under a categorical `hue=` (or `cluster=`/`n_clusters=`) a list + names the CATEGORIES: one entry per category, in the order + ``legend=True`` lists them -- with a line format too, where a + category that recurs is drawn as several line segments but is + still one legend entry. A `panels=` grid draws ONE legend for the whole figure, right of - the grid (see `panels=`). + the grid, and reads `legend=` as the single-axes call of all the + datasets does: a list has one entry per dataset, or per category + of the whole grid (see `panels=`). Under a MultiIndex HIERARCHY the drawn traces are leaves plus derived per-level means, and only the TOP-level groups carry a @@ -9242,10 +9454,30 @@ def plot( mapping. (A list-valued `reduce=` grid draws every dataset in every panel and always colored them alike.) + All of this is resolved ONCE, for the whole grid, exactly as the + single-axes call of all the datasets resolves it, and each panel + draws its share; no panel decides any of it from its own data. + Whether an integer `hue=` is categorical or continuous is decided + from the values of every panel together (see `hue=`); a + ``{category: color}`` `palette=` names the categories of the + whole grid, in either `panel_fit=` mode; a `legend=` list has one + entry per dataset, or -- under a categorical `hue=` or a shared + clustering -- one per category of the whole grid, each panel + labeling the categories it draws, and a list of any other length + raises the single-axes call's ``ValueError`` (which counts the + grid's datasets or groups); ``colorbar=True`` with nothing + grouping the data draws the one discrete colorbar of the + datasets' colors that call draws; a panel whose `hue=` has no + finite value, or no labeled observation, is drawn in the neutral + gray under the grid's scale; and a warning about the whole call + (the number of non-finite `hue=` values, a legend asked of a + continuous `hue=`) is issued once, not once per panel. + The legend and the colorbar are then drawn ONCE for the figure: one legend holding the union of the panels' entries without - duplicates -- the data entries in dataset order, then the - `predict=`/`truth=` entries, where two entries are one when they + duplicates -- the data entries in the order the single-axes call + lists them (datasets in dataset order, categories and clusters + in their own order), then the `predict=`/`truth=` entries, where two entries are one when they have the same label and look the same (a forecast or truth key that differs between panels only in color is one key in the neutral gray the single-axes legend uses for a model that @@ -9913,15 +10145,29 @@ def plot( # function, frame hooks and axes to (`_plot_animated_panels` collects # them into the grid's single animation). Internal, never a user kwarg. _panel_animation = kwargs.pop('_panel_animation', None) - # ...and what a `panels=` grid shares across its panels (see - # `_plot_panels`): ``'limits'``, the grid-wide ``(vmin, vmax)`` of a - # continuous `hue=`, which this panel's value-to-color mapping must use - # so a color is the same value in every panel; and ``'colorbars'``, a - # list this call appends its resolved colorbar to INSTEAD of drawing it - # (the grid draws one for the figure, and one legend, so the panel's - # own legend is not fitted either). Internal, never a user kwarg. + # ...and what a `panels=` grid resolved ONCE for all of its panels and + # hands this one its share of (see `_resolve_grid_colors`; a panel + # never re-decides any of it from its own subset of the data): + # ``'hue_kind'``, whether the grid's numeric `hue=` is ``'continuous'`` + # or ``'discrete'`` (categorical); ``'limits'``, the grid-wide + # ``(vmin, vmax)`` of a continuous `hue=`, which this panel's + # value-to-color mapping must use so a color is the same value in every + # panel; ``'legend_names'``, the grid's ``{category: legend label}`` + # (a `legend=` list naming the grid's hue categories or clusters); + # ``'quiet'``, set when the grid itself issues the warnings that are + # about the whole call (the count of non-finite hue values, a legend + # asked of a continuous hue), so no panel repeats them; ``'colorbars'``, + # a list this call appends its resolved colorbar to INSTEAD of drawing + # it (the grid draws one for the figure, and one legend, so the panel's + # own legend is not fitted either); and ``'report'``, a dict this call + # fills with the legend it resolved (the grid's own probe call reads + # it). Internal, never a user kwarg. _panel_shared = kwargs.pop('_panel_shared', None) _hue_limits = (_panel_shared or {}).get('limits') + _grid_hue_kind = (_panel_shared or {}).get('hue_kind') + _grid_legend_names = (_panel_shared or {}).get('legend_names') + _grid_quiet = bool((_panel_shared or {}).get('quiet')) + _grid_report = (_panel_shared or {}).get('report') _grid_furniture = (_panel_shared is not None and 'colorbars' in _panel_shared) @@ -9955,7 +10201,9 @@ def plot( '_panels_spec', '_panels_name', '_panel_lift', '_panel_animation', '_panel_shared', '_hue_limits', - '_grid_furniture')} + '_grid_furniture', '_grid_hue_kind', + '_grid_legend_names', '_grid_quiet', + '_grid_report')} _panel_call.update(kwargs) return _plot_panels(x, _panels_spec, _panel_call, _name=_panels_name) @@ -12737,6 +12985,15 @@ def _compute_forecasts(datasets): and hue_array.shape[0] == n_obs and len(np.unique(hue_array)) <= 12 and len(np.unique(hue_array)) < n_obs) + if (_grid_hue_kind is not None and hue_array is not None + and hue_array.ndim == 1 and hue_array.shape[0] == n_obs + and (np.issubdtype(hue_array.dtype, np.integer) + or np.issubdtype(hue_array.dtype, np.bool_))): + # a `panels=` cell: the rule above was applied ONCE, to the + # grid's whole hue (20 distinct integers over two panels are + # continuous, though each panel holds only 10 of them); the + # panel draws under that classification + _hue_int_categorical = _grid_hue_kind == 'discrete' hue_is_continuous = (hue_array is not None and hue_array.ndim == 1 and np.issubdtype(hue_array.dtype, np.number) and hue_array.shape[0] == n_obs @@ -12782,7 +13039,7 @@ def _compute_forecasts(datasets): # swatches instead of discarding the legend. _hue_legend_entries = _matrix_hue_legend_entries( hue_array, palette, legend, _hue_column_names) - else: + elif not _grid_quiet: warnings.warn( "legend is not supported for continuous or " "RGB-valued hue; ignoring legend.", @@ -12828,7 +13085,10 @@ def _compute_forecasts(datasets): # spelled it. Guarded on "some entry is a string" so a purely # numeric hue (binned as continuous values, where non-finite # entries are already handled by `mat2colors`) is untouched. - if any(isinstance(el, str) for el in hue): + if (any(isinstance(el, str) for el in hue) + or _grid_hue_kind == 'discrete'): + # (a `panels=` cell of a categorical grid may hold nothing + # but missing labels: still the unlabeled group) hue = [None if is_missing_label(el) else el for el in hue] # if all of the elements are numbers, map them to colors @@ -12854,7 +13114,8 @@ def _compute_forecasts(datasets): hue_group_labels = list(hue_category_names) hue = group_by_category(hue) elif (any(el is None for el in hue) - and any(isinstance(el, str) for el in hue) + and (any(isinstance(el, str) for el in hue) + or _grid_hue_kind == 'discrete') and all(el is None or isinstance(el, str) for el in hue)): # partially-labeled hue (the docstring's "label a subset @@ -13359,10 +13620,19 @@ def _compute_forecasts(datasets): _nested_hover_labels = [g + 1 for g in nested_groups] # handle legend + #: the names `legend=True` gives the drawn hue/cluster groups, one per + #: drawn trace ('_nolegend_' for a trace with no entry), before a + #: `legend=` list renames them -- what a `panels=` grid keys its + #: ``{category: legend label}`` by (`_resolve_grid_colors`) + _legend_group_names = None if legend is not None: if legend is False: legend = None - elif legend is True and hue is not None: + elif hue is not None and ( + legend is True + or (isinstance(legend, (list, tuple)) + and hue_group_labels is not None)): + _renamed = None if legend is True else list(legend) if hue_group_labels is not None: # categorical string hue: show the ORIGINAL category names, # not the integer group ids `hue` was reassigned to above @@ -13371,7 +13641,48 @@ def _compute_forecasts(datasets): legend = list(hue_group_labels) else: legend = [item for item in - sorted(set(hue), key=list(hue).index)] + sorted(set(hue), key=list(hue).index)] + _legend_group_names = list(legend) + _rename = None + if _renamed is not None: + # a `legend=` LIST under a categorical hue names the + # CATEGORIES, one entry per category in the order + # `legend=True` lists them -- on the line path too, whose + # drawn traces are the categories' RUNS (a category that + # recurs along a trajectory is several traces, so three + # names for three categories were refused as "3 entries + # for 4 dataset(s)/group(s)", and a list that happened to + # match the run count named the runs in data order, not + # the categories the marker path names) + _listed = ([n for n in _legend_order if n != '_nolegend_'] + if _legend_order is not None + else [str(n) for n in legend + if n != '_nolegend_']) + if _legend_order is None and len(_renamed) == len(legend): + # (one entry per drawn group, the unlabeled group's + # included: named in drawn order, as always) + _listed = [str(n) for n in legend] + _legend_group_names = list(_listed) + legend = list(_listed) + if len(_renamed) != len(_listed): + raise ValueError( + f"legend= was given as a list of length " + f"{len(_renamed)}, but there are {len(_listed)} " + "dataset(s)/group(s) to plot; pass one entry per " + "drawn dataset, or legend=True to auto-number " + "them.") + _rename = dict(zip(_listed, _renamed)) + elif _grid_legend_names: + # a `panels=` cell: the grid's `legend=` list named the + # categories of the WHOLE grid; this panel labels the ones + # it draws + _rename = _grid_legend_names + if _rename: + legend = [n if n == '_nolegend_' else _rename.get(str(n), n) + for n in legend] + if _legend_order is not None: + _legend_order = [str(_rename.get(n, n)) + for n in _legend_order] elif (_nested_group_colored and hue is None and len(nested_groups) == len(xform) and (legend is True or ( @@ -13418,6 +13729,15 @@ def _compute_forecasts(datasets): mpl_kwargs["label"] = legend + if _grid_report is not None: + # a `panels=` grid's probe call: what this (single-axes) call's + # legend resolved to + _grid_report.update( + group_names=_legend_group_names, + legend=(list(legend) if isinstance(legend, (list, tuple)) + else legend), + legend_order=_legend_order) + # colorbar (GH #100): resolve the color-mapping info (continuous hue # value range + palette, or discrete group colors + labels) now, while # `hue`/`multicolor_hue`/`xform`/`legend` reflect the FINAL grouping @@ -13602,6 +13922,8 @@ def _finite_before(trace_index): line_colors = _multicolor_line_colors( multicolor_hue, pre_interp_lengths, xform, palette, is_rgb=multicolor_hue_is_rgb, + # (a `panels=` grid says it once, counting every panel's) + warn_non_finite=not _grid_quiet, # only a `panels=` grid pins the range (its shared scale) **({} if _hue_limits is None else {'limits': _hue_limits})) @@ -15871,7 +16193,7 @@ def _build_colorbar_info(colorbar, hue, multicolor_hue, cluster, n_clusters, # the range either: `np.min` over a NaN is NaN, and a colorbar (or # bundle['colors']) spanning nan..nan is a colorbar over nothing. finite = vals[np.isfinite(vals)] - if finite.size == 0: + if finite.size == 0 and limits is None: raise ValueError( "hue= has no finite values (every entry is NaN/inf), so " "there is no value range to put on a colorbar.") @@ -15940,6 +16262,16 @@ def _build_colorbar_info(colorbar, hue, multicolor_hue, cluster, n_clusters, # always-on color-scale resolution `bundle['colors']` added there). from matplotlib.colors import to_rgba_array colors = to_rgba_array(explicit_colors)[:, :3] + elif (explicit_colors is not None and hue is None and cluster is None + and n_clusters is None + and (isinstance(explicit_colors, str) + or _is_single_color(explicit_colors))): + # ONE explicit color for every ungrouped dataset + # (``color='red'``): the swatches are that color, the color the + # datasets are drawn in -- not the palette's, which nothing drew + from matplotlib.colors import to_rgba_array + colors = np.tile(to_rgba_array([explicit_colors])[:, :3], + (n_groups, 1)) elif isinstance(palette, collections.abc.Mapping): # a {category: color} dict names the SWATCHES, so index it by the # group names resolved above rather than by position (GH #285). diff --git a/hypertools/plot/plotly_backend.py b/hypertools/plot/plotly_backend.py index 375442274..3347e6288 100644 --- a/hypertools/plot/plotly_backend.py +++ b/hypertools/plot/plotly_backend.py @@ -3246,26 +3246,29 @@ class PanelFurnitureConflict(Exception): def _legend_trace_look(trace, color=True): """What a legend-listed trace's key LOOKS like, as a comparable - value: mode, dash, width, marker symbol and (with `color`) its line - and marker colors.""" + value: mode, line dash and width, marker symbol and size and (with + `color`) its line and marker colors.""" line = trace.line.to_plotly_json() if trace.line is not None else {} marker = (trace.marker.to_plotly_json() if getattr(trace, 'marker', None) is not None else {}) mode = trace.mode or 'lines' + def _plain(value): + """A color or size as a comparable plain value.""" + return value if (value is None or isinstance(value, str)) \ + else repr(np.round(np.asarray(value, dtype=float), 4).tolist()) + look = [type(trace).__name__, mode, line.get('dash'), - marker.get('symbol') if 'markers' in mode else None] + _plain(line.get('width')) if 'lines' in mode else None, + marker.get('symbol') if 'markers' in mode else None, + _plain(marker.get('size')) if 'markers' in mode else None] if color: - def _plain(value): - """A color as a comparable plain value.""" - return value if (value is None or isinstance(value, str)) \ - else repr(np.asarray(value).tolist()) look += [_plain(line.get('color')) if 'lines' in mode else None, _plain(marker.get('color')) if 'markers' in mode else None, trace.opacity] return repr(look) -def merge_panel_legends(panels): +def merge_panel_legends(panels, order=None): """Make the drawn panel figures `panels` list every legend entry ONCE between them -- the plotly twin of `hypertools.plot.plot._merge_panel_legends`, under the same rule: two @@ -3276,8 +3279,10 @@ def merge_panel_legends(panels): other name that looks different in two panels raises `PanelFurnitureConflict`. Same-named traces share a ``legendgroup``, so clicking the one entry toggles them in every panel, and the - forecast/truth keys are ranked after the data entries. Returns whether - any entry is listed.""" + forecast/truth keys are ranked after the data entries. The data + entries are listed in `order` -- their names in the order the + single-axes call of every dataset lists them -- when it covers them, + else in panel order. Returns whether any entry is listed.""" from .forecast import FORECAST_LEGEND_COLOR kept = {} for panel in panels: @@ -3315,6 +3320,15 @@ def merge_panel_legends(panels): raise PanelFurnitureConflict(name) same.append({'look': look, 'shape': shape, 'overlay': overlay, 'trace': trace}) + data = [entry for same in kept.values() for entry in same + if not entry['overlay']] + names = [str(entry['trace'].name) for entry in data] + if order is not None and len(set(order)) == len(order) \ + and len(set(names)) == len(names) and set(names) <= set(order): + for entry, name in zip(data, names): + # (plotly lists equal ranks in trace order; 1000 is its + # default rank, and the overlay keys sit at 2000) + entry['trace'].legendrank = 1000 + order.index(name) return bool(kept) diff --git a/notes/session_2026-11-22_feat295-animated-panels.md b/notes/session_2026-11-22_feat295-animated-panels.md index 7c78815e4..eaad84383 100644 --- a/notes/session_2026-11-22_feat295-animated-panels.md +++ b/notes/session_2026-11-22_feat295-animated-panels.md @@ -129,3 +129,44 @@ labels, explicit sizes, shared-legend placement). - `tests/test_animated_panels.py::test_axis_labels_enlarge_the_figure...` still asserts labeled > plain width for long labels; it passes because the 70% floor makes long labels grow the figure slightly. It was not edited. + +## Review round 2 fixes (2026-11-22) + +Source list: the scratchpad's `feat295/fix_round2.md` (Codex 1-10, tester +R1-R11). Tests: `tests/test_panels_global_resolution.py` (new: every color / +legend item, both backends, each compared with the single-axes call), the +renamed-for-real `test_plotly_grid_categorical_hue_and_legend_false`, and +the layout/title tests added to `tests/test_panel_layout_review.py` and +`tests/test_animated_panels_review.py`. + +Structure of the color/legend fix (one mechanism instead of per-item cases): + +- `_resolve_grid_colors(rows, grid_kw, ndims, caught, clustering=)` MAKES the + single-axes call of every dataset (on the analyzed rows, `reduce=None`, + matplotlib, figure thrown away) with the color kwargs + (`_GRID_COLOR_KWARGS`: fmt, hue, palette, color(s), legend, names, + colorbar, hue_mode, color_reduce) and the shared clustering replayed. It + returns the call's color scale, its `{category: color}` keyed by the hue's + own categories, its colorbar info, `{category: legend label}` and the + legend's order. Its errors are the grid's errors (legend-list length with + the grid's counts, palette validation, colorbar validation); its warnings + are issued once (`_reemit_panel_warnings`). +- `plot()`'s internal `_panel_shared` carries a panel's share: + `'hue_kind'` (forces the integer-hue categorical/continuous decision), + `'limits'`, `'legend_names'`, `'quiet'` (no per-panel repeat of the + whole-call warnings), `'colorbars'` (collector) and `'report'` (what the + probe call's legend resolved to). A consolidated grid's panels get + `colorbar=None`: the grid's one colorbar is the resolution's. +- `panel_fit='independent'`: `_panel_hue_scale_probe` (the same resolver on + placeholder rows, hue/palette/fmt only) runs BEFORE the per-panel fits so + their kwargs are already narrowed; the full resolution runs after them. +- Not resolved globally (no grid-wide meaning exists): reducer-list grids + (each panel already draws every dataset; their legends/colorbars are + merged as before) and per-panel clusters (`panel_fit='independent'` with + `cluster=`). +- Single-axes change that came with it: a `legend=` list under a categorical + hue names the CATEGORIES in `legend=True` order on the line path too + (was: one entry per run, in data order). +- Plotly: `_legend_trace_look` compares line width and marker size; + `merge_panel_legends(order=)` ranks the kept entries; a grid's legend is + wanted by `legend=` or by `names=` alone. diff --git a/tests/test_panels_global_resolution.py b/tests/test_panels_global_resolution.py new file mode 100644 index 000000000..53cf8e733 --- /dev/null +++ b/tests/test_panels_global_resolution.py @@ -0,0 +1,572 @@ +"""`panels=` grids resolve their colors ONCE, for the whole grid (1.2.0, +review round 2). + +A panel grid's colors, hue classification (continuous vs categorical), hue +range, category-to-color mapping, palette validation, legend names and +their validation are resolved globally, exactly as the equivalent +single-axes call of all the datasets resolves them, and each panel is handed +its share; no panel re-decides any of these from its own subset of the +data. Every test here compares a real grid (matplotlib artists or plotly +traces, read back after a real draw) with that single-axes call, on calls +such as ``hyp.plot(x, hue=hue, legend=True, panels=True)``. +""" +import re +import warnings + +import matplotlib.pyplot as plt +import numpy as np +import pytest +from matplotlib.colors import to_rgb + +import hypertools as hyp +from hypertools.plot.colors import NAN_COLOR +from hypertools.plot.plot import SHARED_COLORBAR_GID, SHARED_LEGEND_GID + +BACKENDS = ['matplotlib', 'plotly'] + + +@pytest.fixture(autouse=True) +def _close_figures(): + yield + plt.close('all') + + +def _xy(): + """Two 2-D walks of 20 rows (the review's reproduction data).""" + x = np.random.default_rng(0).normal(size=(20, 2)).cumsum(0) + return [x, x + 3] + + +def _three(): + """Three 4-column clouds of 30 rows, offset from each other.""" + rng = np.random.default_rng(1) + return [rng.normal(size=(30, 4)) + i for i in range(3)] + + +K = dict(reduce=None, ndims=2, show=False) + + +def _plot(*args, **kwargs): + """`hyp.plot`, with every warning it raises recorded: ``(result, + [messages])``.""" + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + result = hyp.plot(*args, **kwargs) + return result, [str(w.message) for w in caught] + + +def _quiet(*args, **kwargs): + """`hyp.plot` with its warnings ignored.""" + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + return hyp.plot(*args, **kwargs) + + +def _mpl_legends(fig): + """The label lists of every legend on a matplotlib figure: the + figure-level (shared) ones first, then each axes' own.""" + out = [[t.get_text() for t in lg.get_texts()] for lg in fig.legends] + out += [[t.get_text() for t in ax.get_legend().get_texts()] + for ax in fig.axes if ax.get_legend() is not None] + return out + + +def _mpl_legend_colors(legend): + """``{label: rgb}`` of a matplotlib legend's entries.""" + out = {} + for handle, text in zip(legend.legend_handles, legend.get_texts()): + color = (handle.get_color() if hasattr(handle, 'get_color') + else handle.get_facecolor()) + color = np.asarray(color, dtype=object) + rgb = (to_rgb(color.tolist()) if color.ndim <= 1 + else to_rgb(np.asarray(color[0], dtype=float))) + out[text.get_text()] = tuple(np.round(rgb, 3)) + return out + + +def _plotly_legend_names(fig): + """The names a plotly figure's legend lists, in the order it lists + them (by ``legendrank``, then trace order).""" + listed = [(t.legendrank if t.legendrank is not None else 1000, i, + str(t.name)) + for i, t in enumerate(fig.data) if t.showlegend] + return [name for _, _, name in sorted(listed)] + + +def _plotly_rgb(color): + """A plotly ``rgb(...)``/``rgba(...)`` string as a 0-1 rgb tuple.""" + numbers = [float(v) for v in re.findall(r'[\d.]+', color)[:3]] + return tuple(np.round(np.asarray(numbers) / 255.0, 3)) + + +def _point_colors(fig, backend): + """The per-observation marker colors of every dataset a figure draws + with a continuous hue, one (n, 3) array per drawn dataset in drawing + order.""" + if backend == 'plotly': + out = [] + for trace in fig.data: + colors = getattr(trace.marker, 'color', None) + if colors is None or isinstance(colors, str): + continue + if getattr(trace.marker, 'showscale', None): + continue # the colorbar's phantom trace + out.append(np.asarray([_plotly_rgb(c) for c in colors])) + return out + return [np.round(np.asarray(coll.get_facecolors())[:, :3], 3) + for ax in fig.axes for coll in ax.collections + if len(coll.get_offsets()) > 1] + + +# --- Codex 1: the hue's classification is the grid's ---------------------- + +@pytest.mark.parametrize('backend', BACKENDS) +def test_integer_hue_is_classified_once_for_the_grid(backend): + hue = [np.tile(np.arange(10), 2), np.tile(np.arange(10, 20), 2)] + kw = dict(fmt='o', hue=hue, colorbar=True, return_model=True, + backend=backend, **K) + single = _quiet(_xy(), **kw) + grid = _quiet(_xy(), panels=True, **kw) + # 20 distinct integers are continuous, though each panel holds 10 + assert single['colors']['kind'] == 'continuous' + assert grid['colors']['kind'] == 'continuous' + assert [m['colors']['kind'] for m in grid['panel_models']] \ + == ['continuous', 'continuous'] + assert (grid['colors']['vmin'], grid['colors']['vmax']) == (0.0, 19.0) + expected = _point_colors(single['fig'], backend) + drawn = _point_colors(grid['fig'], backend) + assert len(expected) == len(drawn) == 2 + for want, got in zip(expected, drawn): + np.testing.assert_allclose(got, want, atol=2e-3) + # the palette does not restart in the second panel + assert not np.allclose(drawn[0][0], drawn[1][0], atol=1e-3) + + +@pytest.mark.parametrize('backend', BACKENDS) +def test_small_integer_hue_stays_categorical_in_every_panel(backend): + # 4 categories over the grid; the second panel has as many distinct + # values as observations, which alone would read as continuous + x = [np.random.default_rng(2).normal(size=(12, 2)), + np.random.default_rng(3).normal(size=(2, 2))] + hue = [np.repeat([0, 1], 6), np.array([2, 3])] + kw = dict(fmt='o', hue=hue, legend=True, return_model=True, + backend=backend, **K) + single = _quiet(x, **kw) + grid = _quiet(x, panels=True, **kw) + assert single['colors']['kind'] == 'discrete' + assert grid['colors']['kind'] == 'discrete' + assert [m['colors']['kind'] for m in grid['panel_models']] \ + == ['discrete', 'discrete'] + assert grid['colors']['labels'] == single['colors']['labels'] + + +# --- Codex 2: the bundle's colors are the grid's -------------------------- + +@pytest.mark.parametrize('backend', BACKENDS) +def test_bundle_colors_keep_categories_when_each_panel_has_one(backend): + kw = dict(fmt='o', hue=[['a'] * 20, ['b'] * 20], legend=True, + return_model=True, backend=backend, **K) + single = _quiet(_xy(), **kw) + grid = _quiet(_xy(), panels=True, **kw) + assert grid['colors']['labels'] == ['a', 'b'] + assert list(grid['colors']['categories']) == ['a', 'b'] + for name in 'ab': + np.testing.assert_allclose(grid['colors']['categories'][name], + single['colors']['categories'][name]) + + +# --- Codex 3: plotly legend entries that look different stay apart -------- + +def test_plotly_legend_entries_of_different_line_width_are_not_merged(): + fig = _quiet(_xy(), panels=True, color='red', linewidth=[1, 8], + legend=['same', 'same'], backend='plotly', **K) + listed = [t for t in fig.data if t.showlegend] + assert [t.name for t in listed] == ['same', 'same'] + assert listed[0].line.width != listed[1].line.width + assert fig.layout.showlegend + # ...as on matplotlib, which keeps a legend per panel + mpl = _quiet(_xy(), panels=True, color='red', linewidth=[1, 8], + legend=['same', 'same'], backend='matplotlib', **K) + assert _mpl_legends(mpl) == [['same'], ['same']] + + +def test_plotly_legend_entries_of_different_marker_size_are_not_merged(): + fig = _quiet(_xy(), panels=True, fmt='o', color='red', + markersize=[3, 14], legend=['same', 'same'], + backend='plotly', **K) + listed = [t for t in fig.data if t.showlegend] + assert [t.name for t in listed] == ['same', 'same'] + assert listed[0].marker.size != listed[1].marker.size + + +def test_plotly_identical_entries_are_still_merged(): + fig = _quiet(_xy(), panels=True, fmt='o', + hue=[['a'] * 20, ['a'] * 10 + ['b'] * 10], legend=True, + backend='plotly', **K) + assert _plotly_legend_names(fig) == ['a', 'b'] + + +# --- Codex 4 / R6: a panel with no finite hue value ----------------------- + +@pytest.mark.parametrize('backend', BACKENDS) +def test_all_nan_panel_draws_gray_under_the_grid_colorbar(backend): + hue = [np.full(20, np.nan), np.linspace(0., 1., 20)] + kw = dict(fmt='o', hue=hue, colorbar=True, return_model=True, + backend=backend, **K) + single, single_warned = _plot(_xy(), **kw) + grid, warned = _plot(_xy(), panels=True, **kw) + assert (grid['colors']['vmin'], grid['colors']['vmax']) == (0.0, 1.0) + drawn = _point_colors(grid['fig'], backend) + np.testing.assert_allclose(drawn[0], np.tile(NAN_COLOR, (20, 1)), + atol=2e-3) + np.testing.assert_allclose(drawn[1], + _point_colors(single['fig'], backend)[1], + atol=2e-3) + if backend == 'matplotlib': + assert len([a for a in grid['fig'].axes + if a.get_gid() == SHARED_COLORBAR_GID]) == 1 + else: + assert len([t for t in grid['fig'].data + if getattr(getattr(t, 'marker', None), 'showscale', + None)]) == 1 + # one warning, the single-axes call's (all 20 of them counted) + nan_warnings = [m for m in warned if 'non-finite' in m] + assert nan_warnings == [m for m in single_warned if 'non-finite' in m] + assert len(nan_warnings) == 1 and nan_warnings[0].startswith('20 ') + + +# --- Codex 5: a colorbar for the datasets' own colors --------------------- + +@pytest.mark.parametrize('backend', BACKENDS) +@pytest.mark.parametrize('legend', [['a', 'b'], None]) +def test_dataset_color_colorbar_is_drawn_once_for_the_grid(backend, legend): + kw = dict(colorbar=True, return_model=True, backend=backend, **K) + if legend is not None: + kw['legend'] = legend + single = _quiet(_xy(), **kw) + grid = _quiet(_xy(), panels=True, **kw) + labels = legend if legend is not None else [1, 2] + assert grid['colors']['labels'] == single['colors']['labels'] == labels + np.testing.assert_allclose(np.asarray(grid['colors']['colors']), + np.asarray(single['colors']['colors'])) + fig = grid['fig'] + if backend == 'matplotlib': + (bar,) = [a for a in fig.axes if a.get_gid() == SHARED_COLORBAR_GID] + fig.canvas.draw() + ticks = [t.get_text() for t in bar.get_yticklabels()] + assert ticks == [str(label) for label in labels] + # the bar's swatches are the colors the panels' lines are drawn in + lines = [to_rgb(ax.lines[0].get_color()) + for ax in grid['axes']] + np.testing.assert_allclose(lines, + np.asarray(grid['colors']['colors']), + atol=1e-6) + else: + (bar,) = [t for t in fig.data + if getattr(getattr(t, 'marker', None), 'showscale', None)] + assert list(bar.marker.colorbar.ticktext) \ + == [str(label) for label in labels] + + +# --- Codex 6: the palette is narrowed before independent fits ------------- + +@pytest.mark.parametrize('backend', BACKENDS) +def test_independent_fit_takes_the_grid_palette_mapping(backend): + grid = _quiet(_xy(), panels=True, panel_fit='independent', fmt='o', + hue=[['a'] * 20, ['b'] * 20], + palette={'a': 'red', 'b': 'blue'}, legend=True, + return_model=True, backend=backend, **K) + categories = grid['colors']['categories'] + assert tuple(categories['a']) == to_rgb('red') + assert tuple(categories['b']) == to_rgb('blue') + if backend == 'matplotlib': + (legend,) = [lg for lg in grid['fig'].legends + if lg.get_gid() == SHARED_LEGEND_GID] + assert _mpl_legend_colors(legend) == {'a': (1.0, 0.0, 0.0), + 'b': (0.0, 0.0, 1.0)} + else: + assert _plotly_legend_names(grid['fig']) == ['a', 'b'] + colors = {t.name: _plotly_rgb(t.marker.color) + for t in grid['fig'].data if t.showlegend} + assert colors == {'a': (1.0, 0.0, 0.0), 'b': (0.0, 0.0, 1.0)} + + +@pytest.mark.parametrize('backend', BACKENDS) +def test_independent_fit_still_refuses_a_category_no_panel_has(backend): + with pytest.raises(ValueError, match="does not have"): + _quiet(_xy(), panels=True, panel_fit='independent', fmt='o', + hue=[['a'] * 20, ['b'] * 20], + palette={'a': 'red', 'b': 'blue', 'zzz': 'green'}, + backend=backend, **K) + + +# --- Codex 7 / R2 / R3 / R4: legend lists are the grid's ------------------ + +@pytest.mark.parametrize('backend', BACKENDS) +@pytest.mark.parametrize('legend, length', [(['only'], 1), ('x', 1), + (['x', 'y'], 2)]) +def test_dataset_legend_list_is_validated_against_the_grid( + backend, legend, length): + x = _three() + with pytest.raises(ValueError) as single: + _quiet(x, '-', legend=legend, show=False, backend=backend) + with pytest.raises(ValueError) as grid: + _quiet(x, '-', legend=legend, panels=(1, 3), show=False, + backend=backend) + assert str(grid.value) == str(single.value) + assert (f"list of length {length}, but there are 3 dataset(s)" + in str(grid.value)) + assert plt.get_fignums() == [] + + +@pytest.mark.parametrize('backend', BACKENDS) +@pytest.mark.parametrize('fmt', ['o', '-']) +def test_legend_list_names_the_grid_categories(backend, fmt): + x = _three() + hue = [['a'] * 15 + ['b'] * 15, ['b'] * 10 + ['c'] * 20, ['d'] * 30] + names = ['A', 'B', 'C', 'D'] + kw = dict(hue=hue, ndims=2, show=False, return_model=True, + backend=backend) + single = _quiet(x, fmt, legend=names, **kw) + plain = _quiet(x, fmt, legend=True, **kw) + grid = _quiet(x, fmt, legend=names, panels=(1, 3), **kw) + assert grid['colors']['labels'] == single['colors']['labels'] == names + # each name keeps its category's color + for name, category in zip(names, 'abcd'): + np.testing.assert_allclose( + grid['colors']['categories'][name], + plain['colors']['categories'][category]) + if backend == 'matplotlib': + (legend,) = [lg for lg in grid['fig'].legends + if lg.get_gid() == SHARED_LEGEND_GID] + assert [t.get_text() for t in legend.get_texts()] == names + (single_legend,) = [ax.get_legend() for ax in single['fig'].axes + if ax.get_legend() is not None] + assert _mpl_legend_colors(legend) \ + == _mpl_legend_colors(single_legend) + assert all(ax.get_legend() is None for ax in grid['axes']) + else: + assert _plotly_legend_names(grid['fig']) == names + assert _plotly_legend_names(single['fig']) == names + + +@pytest.mark.parametrize('backend', BACKENDS) +def test_categorical_legend_list_of_the_wrong_length_names_the_grid(backend): + hue = [['a'] * 10 + ['b'] * 10, ['b'] * 10 + ['c'] * 10] + with pytest.raises(ValueError, match=r"length 2, but there are 3 "): + _quiet(_xy(), panels=True, fmt='o', hue=hue, + legend=['Alpha', 'Beta'], backend=backend, **K) + + +@pytest.mark.parametrize('backend', BACKENDS) +def test_single_axes_line_legend_list_names_categories_not_runs(backend): + # 'b' is drawn as two runs (one per dataset): three names for three + # categories were refused as "3 entries for 4 dataset(s)/group(s)" + hue = [['a'] * 10 + ['b'] * 10, ['b'] * 10 + ['c'] * 10] + names = ['Alpha', 'Beta', 'Gamma'] + kw = dict(hue=hue, return_model=True, backend=backend, **K) + lines = _quiet(_xy(), '-', legend=names, **kw) + markers = _quiet(_xy(), 'o', legend=names, **kw) + assert lines['colors']['labels'] == markers['colors']['labels'] == names + for name in names: + np.testing.assert_allclose(lines['colors']['categories'][name], + markers['colors']['categories'][name]) + if backend == 'matplotlib': + assert _mpl_legends(lines['fig']) == [names] + else: + assert _plotly_legend_names(lines['fig']) == names + with pytest.raises(ValueError, match=r"length 2, but there are 3 "): + _quiet(_xy(), '-', hue=hue, legend=['x', 'y'], backend=backend, **K) + + +def test_single_axes_line_legend_list_follows_the_legend_order(): + # integer categories are listed sorted (1, 3) though 3 is drawn first: + # the names follow the legend, as on the marker path + x = np.random.default_rng(0).normal(size=(20, 2)).cumsum(0) + hue = np.repeat([3, 1], 10) + for fmt in ('o', '-'): + result = _quiet(x, fmt, hue=hue, legend=['one', 'three'], + return_model=True, **K) + plain = _quiet(x, fmt, hue=hue, legend=True, return_model=True, **K) + assert _mpl_legends(result['fig']) == [['one', 'three']] + np.testing.assert_allclose(result['colors']['categories']['one'], + plain['colors']['categories']['1']) + np.testing.assert_allclose(result['colors']['categories']['three'], + plain['colors']['categories']['3']) + + +# --- Codex 8: names= alone asks for the legend on plotly too -------------- + +def test_plotly_grid_shows_the_legend_names_asks_for(): + single = _quiet(_xy(), names=['a', 'b'], backend='plotly', **K) + grid = _quiet(_xy(), names=['a', 'b'], panels=True, backend='plotly', + **K) + assert single.layout.showlegend + assert grid.layout.showlegend + assert _plotly_legend_names(grid) == _plotly_legend_names(single) \ + == ['a', 'b'] + # every trace is on the figure's ONE legend + assert {t.legend for t in grid.data if t.showlegend} <= {None, 'legend'} + off = _quiet(_xy(), names=['a', 'b'], legend=False, panels=True, + backend='plotly', **K) + assert not off.layout.showlegend + assert not any(t.showlegend for t in off.data) + mpl = _quiet(_xy(), names=['a', 'b'], panels=True, + backend='matplotlib', **K) + assert _mpl_legends(mpl) == [['a', 'b']] + + +# --- R5: the shared legend lists clusters in label order ------------------ + +@pytest.mark.parametrize('backend', BACKENDS) +@pytest.mark.parametrize('fmt', ['o', '-']) +def test_shared_cluster_legend_is_in_label_order(backend, fmt): + kw = dict(n_clusters=3, legend=True, random_state=0, ndims=2, + show=False, backend=backend) + single = _quiet(_three(), fmt, **kw) + grid = _quiet(_three(), fmt, panels=(1, 3), **kw) + if backend == 'matplotlib': + assert _mpl_legends(single) == [['0', '1', '2']] + assert _mpl_legends(grid) == [['0', '1', '2']] + else: + assert _plotly_legend_names(single) == ['0', '1', '2'] + assert _plotly_legend_names(grid) == ['0', '1', '2'] + + +def test_animated_shared_cluster_legend_is_in_label_order(): + anim = _quiet(_three(), 'o', n_clusters=3, legend=True, random_state=0, + ndims=2, show=False, panels=(1, 3), animate=True, + duration=1, frame_rate=4) + assert _mpl_legends(anim.figure) == [['0', '1', '2']] + + +@pytest.mark.parametrize('backend', BACKENDS) +def test_cluster_legend_list_names_the_grid_clusters(backend): + names = ['low', 'mid', 'high'] + kw = dict(n_clusters=3, legend=names, random_state=0, ndims=2, + show=False, backend=backend) + single = _quiet(_three(), 'o', **kw) + grid = _quiet(_three(), 'o', panels=(1, 3), **kw) + if backend == 'matplotlib': + assert _mpl_legends(grid) == _mpl_legends(single) == [names] + else: + assert _plotly_legend_names(grid) \ + == _plotly_legend_names(single) == names + + +# --- R7 / R10: warnings about the whole call are issued once -------------- + +@pytest.mark.parametrize('backend', BACKENDS) +@pytest.mark.parametrize('panel_fit', ['shared', 'independent']) +def test_nan_hue_warning_is_issued_once_with_the_total(backend, panel_fit): + x = _three() + hue = [np.r_[np.nan, np.linspace(0, 1, 29)] for _ in x] + kw = dict(hue=hue, ndims=2, show=False, backend=backend) + _, single = _plot(x, 'o', **kw) + _, grid = _plot(x, 'o', panels=(1, 3), panel_fit=panel_fit, **kw) + single = [m for m in single if 'non-finite' in m] + grid = [m for m in grid if 'non-finite' in m] + assert len(single) == 1 and single[0].startswith('3 observation(s)') + assert grid == single + + +@pytest.mark.parametrize('backend', BACKENDS) +@pytest.mark.parametrize('panel_fit', ['shared', 'independent']) +def test_continuous_hue_legend_warning_is_issued_once(backend, panel_fit): + x = _three() + hue = [np.linspace(0, 1, 30) for _ in x] + kw = dict(hue=hue, legend=True, ndims=2, show=False, backend=backend) + _, single = _plot(x, 'o', **kw) + _, grid = _plot(x, 'o', panels=(1, 3), panel_fit=panel_fit, **kw) + single = [m for m in single if 'legend is not supported' in m] + grid = [m for m in grid if 'legend is not supported' in m] + assert len(single) == 1 + assert grid == single + + +# --- a panel whose every label is missing --------------------------------- + +@pytest.mark.parametrize('backend', BACKENDS) +def test_panel_of_unlabeled_points_does_not_take_a_category_color(backend): + hue = [[None] * 20, ['b'] * 10 + ['c'] * 10] + kw = dict(fmt='o', hue=hue, legend=True, return_model=True, + backend=backend, **K) + single = _quiet(_xy(), **kw) + grid = _quiet(_xy(), panels=True, **kw) + assert grid['colors']['labels'] == ['b', 'c'] + for name in 'bc': + np.testing.assert_allclose(grid['colors']['categories'][name], + single['colors']['categories'][name]) + category_colors = [tuple(np.round(c, 3)) + for c in grid['colors']['categories'].values()] + if backend == 'matplotlib': + first = grid['axes'][0] + drawn = [tuple(np.round(to_rgb(line.get_color()), 3)) + for line in first.lines] + assert drawn and all(c not in category_colors for c in drawn) + assert _mpl_legends(grid['fig']) == [['b', 'c']] + else: + unlabeled = [t for t in grid['fig'].data + if t.name not in ('b', 'c') + and isinstance(t.marker.color, str)] + assert unlabeled + assert all(_plotly_rgb(t.marker.color) not in category_colors + for t in unlabeled) + assert _plotly_legend_names(grid['fig']) == ['b', 'c'] + + +# --- a shared colorbar beside per-panel legends; one explicit color ------- + +@pytest.mark.parametrize('backend', BACKENDS) +def test_colorbar_of_one_explicit_color_reports_that_color(backend): + # (single axes too: the swatches were the palette's, which nothing drew) + for extra in ({}, {'panels': True}): + result = _quiet(_xy(), color='red', colorbar=True, + return_model=True, backend=backend, **extra, **K) + np.testing.assert_allclose(np.asarray(result['colors']['colors']), + [[1.0, 0.0, 0.0], [1.0, 0.0, 0.0]]) + + +@pytest.mark.parametrize('backend', BACKENDS) +def test_grid_colorbar_is_drawn_once_beside_per_panel_legends(backend): + # the two 'same' entries look different (line width), so the legends + # stay per panel; the colorbar is still the grid's one + fig = _quiet(_xy(), panels=True, color='red', linewidth=[1, 8], + legend=['same', 'same'], colorbar=True, backend=backend, + **K) + if backend == 'matplotlib': + assert _mpl_legends(fig) == [['same'], ['same']] + assert len([a for a in fig.axes + if a.get_gid() == SHARED_COLORBAR_GID]) == 1 + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + (bar,) = [a for a in fig.axes if a.get_gid() == SHARED_COLORBAR_GID] + bar_box = bar.get_tightbbox(renderer) + assert bar_box.x1 <= fig.bbox.width + 1 and bar_box.x0 >= 0 + for ax in fig.axes: + if ax is bar: + continue + assert not ax.get_legend().get_window_extent( + renderer).overlaps(bar_box) + assert ax.get_legend().get_window_extent(renderer).x1 \ + <= fig.bbox.width + 1 + else: + assert [t.name for t in fig.data if t.showlegend] \ + == ['same', 'same'] + assert len([t for t in fig.data + if getattr(getattr(t, 'marker', None), 'showscale', + None)]) == 1 + + +# --- ndims=1 series grids name their datasets as the single call does ----- + +def test_series_grid_legend_names_each_dataset(): + x = _three() + single = _quiet(x, ndims=1, legend=True, show=False) + grid = _quiet(x, ndims=1, legend=True, panels=(1, 3), show=False) + assert _mpl_legends(single) == [['dataset 1', 'dataset 2', 'dataset 3']] + assert _mpl_legends(grid) == _mpl_legends(single) + (legend,) = grid.legends + (single_legend,) = [ax.get_legend() for ax in single.axes + if ax.get_legend() is not None] + assert _mpl_legend_colors(legend) == _mpl_legend_colors(single_legend) diff --git a/tests/test_panels_shared_legend_colors.py b/tests/test_panels_shared_legend_colors.py index 69128751e..99ecadc54 100644 --- a/tests/test_panels_shared_legend_colors.py +++ b/tests/test_panels_shared_legend_colors.py @@ -570,6 +570,19 @@ def test_plotly_grid_categorical_hue_and_legend_false(): if trace.name in expected and trace.marker.color is not None \ and isinstance(trace.marker.color, str): assert _plotly_rgb(trace.marker.color) == expected[trace.name] + # ...and an explicit legend=False suppresses it: the categorical hue + # still names and colors the traces, but none is listed and the + # figure shows no legend (review round 2: this combination, which the + # test is named for, was never exercised) + off = _quiet_plot(x, hue=hue, fmt='o', legend=False, panels=True, + backend='plotly') + named = [t for t in off.data if t.name in expected] + assert {t.name for t in named} == {'p', 'q', 'r'} + assert all(t.showlegend is False for t in off.data) + assert off.layout.showlegend is False + for trace in named: + if isinstance(trace.marker.color, str): + assert _plotly_rgb(trace.marker.color) == expected[trace.name] bare = _quiet_plot(x, panels=True, backend='plotly') assert not any(t.showlegend for t in bare.data) assert not bare.layout.showlegend From 8e81ec0c402f1e9a64a150986d40b6584a9ad9f6 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 07:15:47 -0500 Subject: [PATCH 22/58] test: two tests assert the warnings their inputs are designed to raise Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- tests/test_caller_figure_hygiene.py | 18 ++++++++++++++---- tests/test_plot_forecast_truth_review.py | 11 ++++++++++- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/tests/test_caller_figure_hygiene.py b/tests/test_caller_figure_hygiene.py index 0b2fe34fc..cc5628f21 100644 --- a/tests/test_caller_figure_hygiene.py +++ b/tests/test_caller_figure_hygiene.py @@ -239,11 +239,21 @@ def test_plot_into_caller_axes_keeps_the_callers_layout_engine(plot_kwargs): fig, axs = plt.subplots(1, 2, figsize=(8, 4), layout='constrained', subplot_kw={'projection': '3d'}) engine = fig.get_layout_engine() - hyp.plot(_walk(), ax=axs[0], show=False, **plot_kwargs) - assert fig.get_layout_engine() is engine - assert fig.get_size_inches().tolist() == [8.0, 4.0] - fig.canvas.draw() # the caller's engine still runs + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + hyp.plot(_walk(), ax=axs[0], show=False, **plot_kwargs) + assert fig.get_layout_engine() is engine + assert fig.get_size_inches().tolist() == [8.0, 4.0] + fig.canvas.draw() # the caller's engine still runs assert fig.get_layout_engine() is engine + # the caller's figure is not resized, so the one legend too wide for + # its half of it is reported when the figure is drawn (and nothing + # else is) + messages = [str(w.message) for w in caught] + if 'legend' in plot_kwargs: + assert len(messages) == 1 and 'too large to fit' in messages[0] + else: + assert messages == [] plt.close(fig) diff --git a/tests/test_plot_forecast_truth_review.py b/tests/test_plot_forecast_truth_review.py index 9199cea33..3968bd4dd 100644 --- a/tests/test_plot_forecast_truth_review.py +++ b/tests/test_plot_forecast_truth_review.py @@ -448,9 +448,18 @@ def test_shuffled_time_index_is_drawn_in_time_order_and_forecast_joins( from the LATEST date, so the forecast did not join the drawn line's end. The line is drawn in time order, exactly as the sorted frame.""" df, shuffled = _shuffled_series() - with pytest.warns(UserWarning, match='time order'): + # two warnings, both about the shuffled index: the line is drawn in + # time order, and the observations are sorted before forecasting + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') out = hyp.plot(shuffled, ndims=1, reduce=None, predict='Kalman', t=5, antialias=False, backend=backend, show=False) + messages = [str(w.message) for w in caught + if issubclass(w.category, UserWarning)] + assert any('time order' in m for m in messages) + assert any('sorted before forecasting' in m for m in messages) + assert all('time order' in m or 'sorted before forecasting' in m + for m in messages), messages ref = hyp.plot(df, ndims=1, reduce=None, predict='Kalman', t=5, antialias=False, backend=backend, show=False) From cced5cb843682c604f590fc43a53ae1d5d5d276d Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 07:15:47 -0500 Subject: [PATCH 23/58] docs: changelog and notes for the grid-wide color resolution (GH #295) Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- CHANGELOG.md | 55 ++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 49 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 24dd7ba1c..831007fa8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -81,14 +81,37 @@ draws into a figure the caller built, found by executing notebooks with (in 1.1.0 each panel mapped its own values and its own categories, so the same color could mean different things in neighboring panels). Clusters from a shared fit already used one mapping. + - *Resolved once, for the whole grid.* Everything the colors mean is + resolved once, exactly as the single-axes call of all the datasets + resolves it, and each panel draws its share; no panel decides any of + it from its own data. Whether an integer `hue=` is categorical or + continuous is decided from every panel's values together (20 distinct + integers split over two panels are continuous, as on one axes). A + `{category: color}` `palette=` names the categories of the whole grid + in either `panel_fit=` mode. A `legend=` list has one entry per + dataset or, under a categorical `hue=` or a shared clustering, one per + category of the whole grid, and each panel labels the categories it + draws; a list of any other length raises the single-axes call's + `ValueError`, which counts the grid's datasets or groups (a short + list used to be accepted and repeated in every panel, and a list + naming every category of the grid was refused by the panels that hold + only some). `colorbar=True` with nothing grouping the data draws one + discrete colorbar of the datasets' colors (it raised). A panel whose + `hue=` has no finite value, or no labeled observation, is drawn in + the neutral gray under the grid's scale (the first raised with + `colorbar=True`; the second took the first palette color). Warnings + about the whole call (the number of non-finite `hue=` values, a legend + asked of a continuous `hue=`) are issued once, not once per panel. - *Legend and colorbar.* The grid draws one legend (the union of the - panels' entries, in dataset order, each once; `predict=`/`truth=` - entries are listed once too) and/or one colorbar, in a strip to the + panels' entries, each once, in the order the single-axes call lists + them: datasets in dataset order, categories and clusters in their own + order; `predict=`/`truth=` entries are listed once too) and/or one colorbar, in a strip to the right of the grid, vertically centered, clear of every panel, title and `caption=`. In 1.1.0 every panel carried its own. The default figure is widened by that one strip instead of 1.1 in per column; an explicit `size=` is honored. `legend=True` numbers the datasets 1..n - (every panel used to say `1`). No legend or colorbar appears that the + (every panel used to say `1`; an `ndims=1` series grid names them + `dataset 1`..`dataset n`). No legend or colorbar appears that the call did not ask for. On the matplotlib figure they are a figure-level legend (gid `'hypertools-shared-legend'`) and a colorbar axes (gid `'hypertools-shared-colorbar'`); on plotly, `layout.legend` and one @@ -103,9 +126,12 @@ draws into a figure the caller built, found by executing notebooks with - *Where panels keep their own.* Clusters fit separately per panel (`cluster=`/`n_clusters=` with `panel_fit='independent'` or with a list-valued `reduce=`), `forecast_cluster=`/`forecast_n_clusters=`, - and a legend label that would look different in two panels: there the - colors mean something different in every panel, so each panel keeps - its own legend and colorbar. + and a legend label that would look different in two panels (in color, + line style, line width, marker or marker size, on both backends): + there the colors mean something different in every panel, so each + panel keeps its own legend and colorbar. (Where only a legend label + looks different, the legends stay per panel and the colorbar is still + the grid's one.) - *`return_model=True`.* The grid bundle's `'colors'` is the one scale the panels share (every dataset's color in panel order, the grid-wide range of a continuous `hue=`, or the union of the categories) instead @@ -120,6 +146,23 @@ draws into a figure the caller built, found by executing notebooks with ### Fixed +- **A `legend=` list names the categories of a categorical `hue=` on line + plots too.** With a line format, a category that recurs (along one + trajectory, or in two datasets) is drawn as several line segments, and a + list with one name per category was refused ("list of length 3, but + there are 4 dataset(s)/group(s)"), or, when the counts happened to + match, named the segments in data order rather than the categories. A + list now has one entry per category, in the order `legend=True` lists + them, for lines as for markers, and a list of the wrong length is + refused with the number of categories. +- **A colorbar for datasets drawn in one explicit color shows that + color.** `hyp.plot([a, b], color='red', colorbar=True)` drew red lines + beside a colorbar of the palette's first two colors, and reported those + in the bundle's `'colors'`; both now show the color drawn. +- **`names=` alone shows the legend on a plotly `panels=` grid.** + `hyp.plot([a, b], panels=True, names=['a', 'b'], backend='plotly')` + named the traces but hid the legend; it is shown, as on one axes and on + matplotlib, and `legend=False` still suppresses it. - **Axis labels of a static 3-D `panels=` grid stay inside their own panel.** matplotlib hangs a 3-D axes' labels outside its cube, where no layout accounts for them, so in a grid they were drawn over the next From 76e70fbe6e2587cf406114da27d19f521b293e16 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 07:22:50 -0500 Subject: [PATCH 24/58] docs: the hue= docstring says a panel grid classifies its hue once (GH #295) Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/plot/plot.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index 8de34d06a..adbb808e5 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -7606,7 +7606,9 @@ def plot( higher-cardinality integer hues are always continuous. To force grouping, pass the ids as strings (``hue=[str(g) for g in ids]``); to force a continuous mapping, cast to float - (``hue=np.asarray(ids, dtype=float)``). + (``hue=np.asarray(ids, dtype=float)``). In a `panels=` grid the + choice is made once, from the values of every panel together, + as for the single-axes call of all the datasets. A SCALAR `hue` (a single string or number, e.g. ``hue='red'``) is broadcast to one group covering every observation -- a single From cb70fce885082e6ff248dd45558361b0fec80ec4 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 07:04:51 -0500 Subject: [PATCH 25/58] fix: a static labeled 3-D grid too small for its size= keeps legible cubes and warns (GH #295) A static panels= grid with 3-D axis labels and an explicit size= too small for them shrank its cubes without limit (10-40 px) and drew each panel's labels over each other, silently. The cubes are now kept at half their unlabeled size at least, and one UserWarning names a size that works (found by fitting the grid at that size) and the alternative of dropping the labels. The call still draws, at the size asked for. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/plot/plot.py | 118 +++++++++++++++++++++++------- tests/test_panel_layout_review.py | 92 +++++++++++++++++++++++ 2 files changed, 182 insertions(+), 28 deletions(-) diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index adbb808e5..c0161e664 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -6373,9 +6373,10 @@ def _common(name): #: grid, so it is enlarged only where the cubes would become very small)... _STATIC_LABELED_CUBE_SHARE = 0.65 -#: ...and the share under which an explicit `size=` is refused for an -#: animated grid (a size the caller chose is honored down to cubes half -#: their unlabeled size) +#: ...and the legible floor at an explicit `size=` (a size the caller chose +#: is honored down to cubes half their unlabeled size): under it an +#: animated grid is refused, and a static grid is drawn with its cubes AT +#: the floor and a warning _REFUSED_LABELED_CUBE_SHARE = 0.5 @@ -6471,6 +6472,24 @@ def _has_axis_labels(axis): for axis3d in axis._axis_map.values()) +def _axis_labels_collide(fig, cells): + """Whether any 3-D panel in `cells` draws two of its own axis labels + over each other (their drawn boxes, less two pixels of antialiasing a + side, overlap) at its current view and zoom.""" + renderer = _measurement_renderer(fig) + for cell in cells: + boxes = [axis3d.label.get_window_extent(renderer) + for axis3d in cell['axes']._axis_map.values() + if axis3d.label.get_text() and axis3d.label.get_visible()] + for i, one in enumerate(boxes): + for other in boxes[i + 1:]: + if (min(one.x1, other.x1) - max(one.x0, other.x0) > 4.0 + and min(one.y1, other.y1) + - max(one.y0, other.y0) > 4.0): + return True + return False + + def _fit_static_cube_labels(fig, panel_axes, resize=True): """Keep every STATIC 3-D panel's axis labels inside the panel's own box (`_fit_panel_cubes`): matplotlib hangs a 3-D axes' labels outside @@ -6479,7 +6498,9 @@ def _fit_static_cube_labels(fig, panel_axes, resize=True): shared legend. A labeled panel's cube is drawn smaller until its labels fit, and where that would leave the cube too small the figure is enlarged instead (`resize`: no explicit `size=`, which is honored - as given). Panels without axis labels are not touched.""" + as given -- with a warning that names a size that works when it cannot + hold the labeled grid legibly, see `_fit_panel_cubes`). Panels without + axis labels are not touched.""" cells = [{'axes': ax, 'stub': _StaticCubeZoom(ax)} for ax in panel_axes if ax.get_visible() and hasattr(ax, 'get_proj') @@ -6521,8 +6542,14 @@ def _fit_panel_cubes(fig, cells, resize=True, rotations=1, static=False, `static` fits a STATIC grid's labeled panels (see `_fit_static_cube_labels`): only the labels are fitted, at the one - view, and an explicit `size=` too small for them is honored (smaller - cubes) instead of refused. + view. An explicit `size=` is never refused for a static grid (the call + always drew). Where it cannot hold the labeled grid legibly -- a cube + would fall under `_REFUSED_LABELED_CUBE_SHARE` of its unlabeled size, + or a panel's own labels would be drawn over each other + (`_axis_labels_collide`) -- the cubes are kept at that share at least, + the labels fall where they fall, and ONE `UserWarning` names a size + that works (found the same way) and the alternative of dropping the + labels. """ cubes = [cell for cell in cells if hasattr(cell['axes'], 'get_proj')] limit = 0.5 * _PANEL_CUBE_FILL @@ -6541,10 +6568,12 @@ def _fit_cube(cell, target): break cell['stub'].zoom_scale[0] *= target / cell['reach'] - def _fit(): + def _fit(least=0.0): """Fit every cube, then every labeled cube's labels, at the figure's current size; returns the smallest share of its - unlabeled size a labeled cube is left with.""" + unlabeled size a labeled cube is left with. No labeled cube is + drawn smaller than the share `least` of its unlabeled size (its + labels then reach past the panel's box).""" for cell in cubes: cell['stub'].zoom_scale[0] = 1.0 # (a static cube is only ever moved for its labels) @@ -6561,18 +6590,32 @@ def _fit(): if label_reach - limit <= 0.004: continue # the labels' distance from the cube scales with the cube - _fit_cube(cell, max(0.02, cell['reach'] * limit - / label_reach)) + target = cell['reach'] * limit / label_reach + if target < least * cell['free']: + # the legible floor: the labels overflow instead + _fit_cube(cell, least * cell['free']) + continue + _fit_cube(cell, max(0.02, target)) over.append(cell) pending = over return min([1.0] + [cell['reach'] / cell['free'] for cell in labeled]) smallest = _fit() - floor = (_STATIC_LABELED_CUBE_SHARE if static - else _PANEL_LABELED_CUBE_SHARE if resize - else _REFUSED_LABELED_CUBE_SHARE) - if labeled and smallest < floor - 0.02 and (resize or not static): + floor = (_REFUSED_LABELED_CUBE_SHARE if not resize + else _STATIC_LABELED_CUBE_SHARE if static + else _PANEL_LABELED_CUBE_SHARE) + # a static grid at an explicit `size=` must also keep each panel's own + # labels off each other (around a small cube they converge) + explicit_static = static and not resize + + def _illegible(): + return (smallest < floor - (0.02 if size_checked else 0.004) + or (explicit_static and _axis_labels_collide(fig, labeled))) + + size_checked = True + if labeled and _illegible(): + size_checked = False width, height = fig.get_size_inches() new_width, new_height = width, height # (a refusal's suggestion may be generous; it must be reached) @@ -6602,26 +6645,45 @@ def _fit(): if not resize: # a size to SUGGEST keeps the caller's proportions: the # grid is laid out afresh at an explicit size, and only a - # figure of the same shape is laid out the same way - grow_w = grow_h = max(grow_w, grow_h) + # figure of the same shape is laid out the same way. (Cubes + # big enough whose labels still collide: a tenth more.) + grow_w = grow_h = max(grow_w, grow_h, + 1.1 if explicit_static else 1.0) new_width, new_height = new_width * grow_w, new_height * grow_h fig.set_size_inches(new_width, new_height) smallest = _fit() - if smallest >= floor - 0.004: + if not _illegible(): break if not resize: fig.set_size_inches(width, height) - raise ValueError( - f"the axis labels (xlabel=/ylabel=/zlabel=) of this " - f"animated 3-D {_name}= grid hang outside each panel's " - f"cube, and a {width:g} x {height:g} inch figure leaves " - f"too little of each panel for the cube itself. Pass a " - f"larger size= " - f"(({np.ceil(new_width * 10) / 10:g}, " - f"{np.ceil(new_height * 10) / 10:g}) or more), leave " - "size= out to have the figure sized for them, or drop the " - "axis labels (xlabel='', ylabel='', zlabel='' also drops " - "the ones taken from DataFrame column names).") + suggested = (f"({np.ceil(new_width * 10) / 10:g}, " + f"{np.ceil(new_height * 10) / 10:g})") + if static: + # a static grid is drawn all the same (it always was): + # cubes no smaller than the floor, labels where they fall + _fit(least=floor) + warnings.warn( + f"the axis labels (xlabel=/ylabel=/zlabel=) of this 3-D " + f"{_name}= grid do not fit legibly in a {width:g} x " + f"{height:g} inch figure: each panel's cube is drawn " + f"no smaller than " + f"{round(100 * floor)}% of its unlabeled size, so " + f"its labels may overlap each other or the next panel. " + f"Pass a larger size= ({suggested} or more), leave " + f"size= out to have the figure sized for them, or drop " + f"the axis labels (xlabel='', ylabel='', zlabel='' also " + f"drops the ones taken from DataFrame column names).", + UserWarning, stacklevel=external_stacklevel()) + else: + raise ValueError( + f"the axis labels (xlabel=/ylabel=/zlabel=) of this " + f"animated 3-D {_name}= grid hang outside each panel's " + f"cube, and a {width:g} x {height:g} inch figure leaves " + f"too little of each panel for the cube itself. Pass a " + f"larger size= ({suggested} or more), leave " + "size= out to have the figure sized for them, or drop " + "the axis labels (xlabel='', ylabel='', zlabel='' also " + "drops the ones taken from DataFrame column names).") for cell in cubes: # leave every panel showing frame 0 at its final zoom cell['stub'].draw(0) diff --git a/tests/test_panel_layout_review.py b/tests/test_panel_layout_review.py index c5ea5033b..f6fb96f90 100644 --- a/tests/test_panel_layout_review.py +++ b/tests/test_panel_layout_review.py @@ -474,3 +474,95 @@ def test_static_long_axis_labels_do_not_run_into_each_other(shape, n): for axis in (ax.xaxis, ax.yaxis, ax.zaxis)] for a, b in itertools.combinations(boxes, 2): assert not a.overlaps(b) + + +# -------------------------------------------------------------------------- +# Round 2, R1: a static labeled 3-D grid at an explicit size= too small +# -------------------------------------------------------------------------- + +WORDY = [pd.DataFrame(d, columns=['first component', 'second comp', + 'third']) for d in DATA] +NO_LABELS = dict(xlabel='', ylabel='', zlabel='') + + +def _plot_recording(*args, **kwargs): + """``(figure, [warning messages])`` of one static `hyp.plot` call.""" + import warnings + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + fig = hyp.plot(*args, show=False, **kwargs) + return fig, [str(w.message) for w in caught] + + +def _own_label_overlaps(fig, n): + """How many pairs of a panel's OWN axis labels are drawn over each + other, over the first `n` panels.""" + renderer = _draw(fig) + count = 0 + for ax in fig.axes[:n]: + boxes = [_shrunk(axis.label.get_window_extent(renderer)) + for axis in (ax.xaxis, ax.yaxis, ax.zaxis) + if axis.label.get_text()] + count += sum(a.overlaps(b) + for a, b in itertools.combinations(boxes, 2)) + return count + + +def _cube_widths(fig, n): + _draw(fig) + return [_cube_box(ax).width for ax in fig.axes[:n]] + + +@pytest.mark.parametrize('frames,shape,size', [ + (WORDY, (1, 4), (8, 3)), (WORDY, (1, 4), (5, 4)), + (WORDY, (2, 2), (5, 4)), (XYZ, (1, 4), (4, 3)), + (LONG, (2, 2), (4, 3)), +], ids=['wordy-1x4-8x3', 'wordy-1x4-5x4', 'wordy-2x2-5x4', 'xyz-1x4-4x3', + 'long-2x2-4x3']) +def test_a_static_labeled_grid_too_small_warns_once_with_a_size_that_works( + frames, shape, size): + """R1: the cubes shrank to 10-40 px with each panel's labels drawn + over each other, silently. The call still draws (it always did), at + the size asked for, with cubes no smaller than half their unlabeled + size, and ONE warning names a size that works.""" + fig, messages = _plot_recording(frames, '-', panels=shape, legend=True, + size=size) + assert tuple(fig.get_size_inches()) == tuple(float(v) for v in size) + assert len(messages) == 1, messages + message = messages[0] + assert "xlabel='', ylabel='', zlabel=''" in message + match = re.search(r'larger size= \(\(([\d.]+), ([\d.]+)\) or more\)', + message) + assert match, message + suggested = (float(match.group(1)), float(match.group(2))) + assert suggested[0] > size[0] and suggested[1] > size[1] + + # the legible floor: half the cube the same call draws without labels + bare, bare_messages = _plot_recording( + frames, '-', panels=shape, legend=True, size=size, **NO_LABELS) + assert not bare_messages # ...which is the other way out the warning names + for labeled, plain in zip(_cube_widths(fig, 4), _cube_widths(bare, 4)): + assert labeled >= 0.47 * plain + + # the size the warning names: no warning, and a legible grid + again, again_messages = _plot_recording( + frames, '-', panels=shape, legend=True, size=suggested) + assert not again_messages + assert tuple(again.get_size_inches()) == suggested + _assert_labels_clear(again, 4) + assert _own_label_overlaps(again, 4) == 0 + bare = hyp.plot(frames, '-', panels=shape, legend=True, size=suggested, + show=False, **NO_LABELS) + for labeled, plain in zip(_cube_widths(again, 4), _cube_widths(bare, 4)): + assert labeled >= 0.47 * plain + + +@pytest.mark.parametrize('frames,shape,size', [ + (LONG, (1, 4), (8, 3)), (XYZ, (2, 2), (5, 4)), (WORDY, (2, 2), (8, 6)), +], ids=['long-1x4-8x3', 'xyz-2x2-5x4', 'wordy-2x2-8x6']) +def test_a_static_labeled_grid_that_fits_its_size_does_not_warn( + frames, shape, size): + fig, messages = _plot_recording(frames, '-', panels=shape, size=size) + assert not messages + _assert_labels_clear(fig, 4) + assert _own_label_overlaps(fig, 4) == 0 From 35740dcb540bf815683cc2299c9dae7dc2c25e4f Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 07:09:09 -0500 Subject: [PATCH 26/58] fix: room for an animated title is sized for its tallest sampled frame (GH #295) A per-frame title= (callable or {index...} pattern) had its room sized from frame 0 alone, so a title that grew lines later left the canvas: in an animated panels= grid, above a single 3-D animation, and above a single 2-D animation, which reserved nothing beyond the default top margin (a fixed or per-segment title taller than about three lines left the canvas there too). The room is now made for the tallest of the first, middle and last frames' titles, as a caption's room is; a single 2-D animation's figure grows upward by what its tallest title needs. Documented beside the caption's sizing rule. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- docs/animation.rst | 14 ++- hypertools/plot/plot.py | 166 +++++++++++++++++++++------ tests/test_animated_panels_review.py | 97 ++++++++++++++++ 3 files changed, 243 insertions(+), 34 deletions(-) diff --git a/docs/animation.rst b/docs/animation.rst index b7125201f..7222a5280 100644 --- a/docs/animation.rst +++ b/docs/animation.rst @@ -119,6 +119,15 @@ form: A multi-line title (explicit newlines, or from ``title_wrap=``) now reserves room for every line above an animated 3-D plot, not just one. +On the matplotlib backend the room above an animated plot is made for the +tallest title the animation shows: a fixed title's own lines, the tallest +entry of a per-segment list, and, for a callable or ``'{index...}'`` title, +the tallest of the first, middle and last frames' titles, so a title that +grows lines as the animation runs has its room from the start (a frame in +between that needs more lines than all three runs above it). The figure is +made taller by what the title needs, in 2-D and in 3-D, and nothing already +drawn moves or shrinks. + Per-dataset styling ------------------- @@ -751,7 +760,10 @@ A few things are specific to a grid: size and raises below that, naming a size that works; pass ``xlabel='', ylabel='', zlabel=''`` to drop the labels instead. * A per-frame ``title=`` (a callable or an ``'{index...}'`` pattern, one for every panel or a list with one per panel) gets its room above each panel - like a fixed title. + like a fixed title. The room is made for the tallest of the first, middle + and last frames' titles, so a title that grows lines as the animation + runs stays on the canvas and clear of the row above (a frame in between + that needs more lines than all three runs above its room). * Colors, the legend and the colorbar belong to the whole grid, as in a static grid: each dataset keeps the color the single-axes call of all the datasets gives it, ``hue=`` is mapped through one scale, and one legend diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index c0161e664..fb7925687 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -6739,6 +6739,10 @@ def _abandon(): _fit_panel_cubes(fig, cells, resize=resize, rotations=rotations, _name=_name) _place_shared_furniture(fig, strip) + for cell in cells: + # a still of the grid shows frame 0 (a 2-D panel was laid out + # showing its tallest per-frame title; see `plot`) + cell['stub'].draw(0) except Exception: _abandon() raise @@ -7953,6 +7957,18 @@ def plot( carries an index is the one read. A title with braces that does NOT contain ``{index`` is drawn verbatim, as always. + **Room for a title that changes.** On the matplotlib backend the + room above an animated plot (above each panel of a `panels=` + grid) is made for the tallest title the animation shows: a fixed + title's own lines, the tallest entry of a per-segment list, and, + for a per-frame title, the tallest of the titles of the FIRST, + MIDDLE and LAST frames -- so a title that grows lines as the + animation runs has its room from the start; a frame in between + that needs more lines than all three runs above that room. A + single animated plot's figure is made taller by what the title + needs (nothing already drawn moves or shrinks); a grid's panels + are laid out under their titles, as a static grid's are. + **Where the reveal head is.** One rule, so the same pattern means the same thing on the same data: for a serial reveal it is the rows revealed so far across ALL datasets (finished ones plus the @@ -8015,9 +8031,9 @@ def plot( frame. An animated 3-D title reserves top margin per line on both backends: for a per-segment list, the tallest entry; for a dynamic title, plotly measures every frame (all frames are built - up front) while matplotlib measures FRAME 0's text, so a callable - whose title grows lines on later frames can clip there -- give - frame 0 the same number of lines. Default None. + up front) while matplotlib measures the first, middle and last + frames' texts (see `title=`), so only a frame in between that + needs more lines than all three can clip there. Default None. font : None, str, or matplotlib.font_manager.FontProperties Controls the font used for every text surface hypertools draws, @@ -15656,6 +15672,43 @@ def _real_frame_context(frame): return FrameContext(figure=fig, axes=ax, **_frame_hooks.state) + def _sampled_dynamic_titles(): + """The dynamic `title=`'s wrapped text on the frames that + size its room -- the first, the middle and the last + (`_caption_sample_frames`, as a per-frame caption's room is + sized) -- frame 0's first. Each is resolved against that + frame's REAL context (`_real_frame_context`: the frame is + drawn to get it), and the resolver is a pure function of + the context by contract (`FrameContext`), so these cannot + disagree with what the per-frame updater sets later -- and + a resolver that is going to fail fails HERE, before the + animation runs, instead of inside a frame. The animation + is left showing frame 0.""" + try: + texts = [ + _wrap_title_text( + _resolve_dynamic_title_text( + _dynamic_title, _real_frame_context(_frame)), + _title_wrap, _wrap_break) + for _frame in _caption_sample_frames( + int(line_ani._save_count))] + if len(texts) > 1: + _real_frame_context(0) + except Exception: + # the user's title raised before the animation was + # ever handed back: detach it (no HyperAnimation + # exists to silence it) so gc does not later warn + # "Animation was deleted without rendering anything" + # about THEIR exception, and close the abandoned + # figure as the save path does. + from .hyper_animation import mark_draw_started + mark_draw_started(line_ani) + if (not show and not _user_supplied_ax + and isinstance(fig, plt.Figure)): + plt.close(fig) + raise + return texts + # title= per-segment sequence (plan 1.1 Task 8): registered on # the SAME `_frame_hooks` registry as `on_frame=` (added last # above, so this callback also only ever sees final artists -- @@ -15687,34 +15740,11 @@ def _real_frame_context(frame): or _dynamic_title is not None or on_frame is not None)): # a dynamic (callable / `{index...}`) title has no text yet: - # resolve FRAME 0's, purely to count its lines. That is the - # real frame-0 context (`_real_frame_context`: the frame is - # drawn to get it), not a synthetic one, and the - # resolver is a pure function of the context by contract - # (`FrameContext`), so this cannot disagree with what the - # per-frame updater will set a moment later -- and if the - # resolver is going to fail, it fails HERE, before the - # animation runs, instead of inside the first frame. + # the tallest of the first, middle and last frames' titles + # sizes the margin (`_sampled_dynamic_titles`) _probe_title = None if _dynamic_title is not None: - try: - _probe_title = _wrap_title_text( - _resolve_dynamic_title_text( - _dynamic_title, _real_frame_context(0)), - _title_wrap, _wrap_break) - except Exception: - # the user's title raised before the animation - # was ever handed back: detach it (no - # HyperAnimation exists to silence it) so gc does - # not later warn "Animation was deleted without - # rendering anything" about THEIR exception, and - # close the abandoned figure as the save path does. - from .hyper_animation import mark_draw_started - mark_draw_started(line_ani) - if (not show and not _user_supplied_ax - and isinstance(fig, plt.Figure)): - plt.close(fig) - raise + _probe_title = _tallest_title(_sampled_dynamic_titles()) _reserve_animated_3d_title_margin( fig, ax, fontsize=(_title_kwargs or {}).get('fontsize'), @@ -15759,10 +15789,15 @@ def _real_frame_context(frame): # has no text until a frame is drawn, so the layout # below reserved no room for it and every frame's # title was then drawn off the top of the canvas (top - # row) or over the x-axis labels of the row above: - # draw frame 0, whose title the layout then arranges - # like a fixed one - line_ani._func(0, *line_ani._args) + # row) or over the x-axis labels of the row above. The + # layout -- this one and the grid's -- arranges the + # TALLEST of the first, middle and last frames' titles + # like a fixed one (frame 0's alone left a title that + # grows lines later off the canvas); the grid draws + # frame 0 once it is laid out (`_animate_panel_grid`) + _apply_title(ax, _tallest_title(_sampled_dynamic_titles()), + font=_artist_font, + title_kwargs=_title_kwargs) if (_grid_furniture and ax is not None and ax.get_legend() is not None): # this panel's legend only carries its entries to the @@ -15777,6 +15812,32 @@ def _real_frame_context(frame): and isinstance(fig, plt.Figure)): fig.tight_layout() + # an animated 2-D plot's title: the default axes leave room + # for about three lines above them, and nothing reserved more, + # so a taller title -- fixed, per-segment, or a per-frame one + # on any of the frames that size it -- left the canvas. (A 3-D + # animation's margin is reserved above; a grid cell's title is + # arranged by the layout; a caller's figure is the caller's.) + if (animate and ax is not None and line_ani is not None + and _panel_animation is None and not _caller_figure + and isinstance(fig, plt.Figure) + and xform[0].shape[1] < 3 + and (title is not None or _segment_titles is not None + or _dynamic_title is not None)): + _shown_title = ax.get_title() + if _dynamic_title is not None: + _title_candidates = _sampled_dynamic_titles() + elif _segment_titles is not None: + _title_candidates = [ + _text for _text in _segment_titles + if isinstance(_text, str)] + else: + _title_candidates = [_shown_title] + _reserve_animated_2d_title_room( + fig, ax, _tallest_title(_title_candidates), + _shown_title, font=_artist_font, + title_kwargs=_title_kwargs) + # colorbar (GH #100): built once, here, from the (frame- # independent) color mapping. For animated plots this is never # touched by the per-frame update callbacks, so it stays static @@ -16851,6 +16912,45 @@ def _title_line_count(*titles): return n +def _tallest_title(texts): + """The entry of `texts` with the most lines (the first of them when + several tie; ``''`` for none): the title whose room an animation + reserves.""" + best = '' + for text in texts: + text = '' if text is None else str(text) + if not best or text.count('\n') > best.count('\n'): + best = text + return best + + +def _reserve_animated_2d_title_room(fig, ax, tallest, shown, font=None, + title_kwargs=None, pad_in=0.08): + """Give an animated 2-D plot's title the room its TALLEST text needs. + + A static plot is laid out around its title (`tight_layout`); an + animated one is not laid out at all, so its title has the default + axes' top margin (about three lines) and a taller one ran off the top + of the canvas. `tallest` is the title's tallest text (a fixed title: + itself; a per-segment list: its tallest entry; a per-frame title: the + tallest of the first, middle and last frames', as a caption's room is + sized). It is set on `ax` and measured on a real draw, and the figure + grows UPWARD by what leaves the canvas plus `pad_in` (`_grow_figure`: + the axes keeps its size and nothing else moves). A title that already + fits changes nothing. `ax` is left showing `shown`, the title it had + (a per-frame title has none until a frame is drawn). + """ + if not tallest: + return + _apply_title(ax, tallest, font=font, title_kwargs=title_kwargs) + top = ax.title.get_window_extent(_measurement_renderer(fig)).y1 + over_in = (top - fig.bbox.height) / fig.dpi + if np.isfinite(over_in) and over_in > 0: + _grow_figure(fig, top=over_in + pad_in) + if shown != tallest: + _apply_title(ax, shown, font=font, title_kwargs=title_kwargs) + + def _reserve_animated_3d_title_margin(fig, ax, pad_in=0.08, fontsize=None, n_lines=1): """Grow the figure so an animated 3-D plot's title has room to render. diff --git a/tests/test_animated_panels_review.py b/tests/test_animated_panels_review.py index 1270972aa..7f3bc0c6f 100644 --- a/tests/test_animated_panels_review.py +++ b/tests/test_animated_panels_review.py @@ -515,3 +515,100 @@ def test_an_explicit_reduce_to_too_many_dimensions_still_warns(): hyp.reduce(TWO_COLUMNS, reduce='PCA', ndims=3) with pytest.warns(UserWarning, match='no reduction was performed'): hyp.analyze(TWO_COLUMNS, reduce='PCA', ndims=3, return_model=True) + + +# -------------------------------------------------------------------------- +# Round 2 (Codex 9): a per-frame title whose HEIGHT changes over the frames +# -------------------------------------------------------------------------- + +TALL = '\n'.join(['a title line'] * 8) +GROWING = { + # the frame on which the title is eight lines tall (one line elsewhere) + 'first': lambda ctx: TALL if ctx.frame == 0 else 'short', + 'middle': lambda ctx: (TALL if ctx.frame == ctx.n_frames // 2 + else 'short'), + 'last': lambda ctx: (TALL if ctx.frame == ctx.n_frames - 1 + else 'short'), + 'after-first': lambda ctx: 'short' if ctx.frame == 0 else TALL, +} + + +def _assert_titles_on_canvas(anim, n): + """On every frame, every one of the first `n` axes' titles is inside + the canvas and clear of every other panel's box; returns the most + lines a title had.""" + fig = anim.figure + most = 0 + for frame in range(anim.n_frames): + anim.draw_frame(frame) + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + width, height = fig.canvas.get_width_height() + panels = fig.axes[:n] + boxes = [ax.get_window_extent(renderer) for ax in panels] + for i, ax in enumerate(panels): + assert ax.get_title(), (frame, i) + most = max(most, ax.get_title().count('\n') + 1) + title = ax.title.get_window_extent(renderer) + assert title.y1 <= height + 0.5 and title.y0 >= 0, (frame, i) + assert title.x0 >= -0.5 and title.x1 <= width + 0.5, (frame, i) + for j in range(len(panels)): + if j != i: + assert not title.overlaps(boxes[j]), (frame, i, j) + return most + + +@pytest.mark.parametrize('when', sorted(GROWING)) +@pytest.mark.parametrize('ndims', [2, 3]) +@pytest.mark.parametrize('shape', [(1, 2), (2, 2), (3, 1)]) +def test_a_grid_title_that_grows_after_frame_0_stays_on_the_canvas( + shape, ndims, when): + """The room was sized for frame 0's title alone: one that became + eight lines on a later frame ran 114 px off the top of a 320 px + canvas. It is sized for the tallest of the first, middle and last + frames' titles, as a caption's room is.""" + n = shape[0] * shape[1] + anim = hyp.plot([d[:, :ndims] for d in DATA[:n]], reduce=None, + ndims=ndims, panels=shape, title=GROWING[when], + backend='matplotlib', **ANIM) + # a still of the figure shows frame 0's title + expected = TALL if when == 'first' else 'short' + assert [ax.get_title() for ax in anim.figure.axes[:n]] == [expected] * n + assert _assert_titles_on_canvas(anim, n) == 8 + + +@pytest.mark.parametrize('when', sorted(GROWING)) +@pytest.mark.parametrize('ndims', [2, 3]) +def test_a_single_axes_title_that_grows_after_frame_0_stays_on_the_canvas( + ndims, when): + """The same callable on one axes: a 2-D animation reserved no title + room at all beyond the default margin, and a 3-D one frame 0's.""" + anim = hyp.plot([d[:, :ndims] for d in DATA[:2]], reduce=None, + ndims=ndims, title=GROWING[when], backend='matplotlib', + **ANIM) + assert _assert_titles_on_canvas(anim, 1) == 8 + + +def test_a_tall_fixed_title_of_a_2d_animation_stays_on_the_canvas(): + """Eight fixed lines above an animated 2-D plot left the canvas too + (the default margin holds about three); the figure grows upward by + what is missing and the axes keeps its size.""" + plain = hyp.plot(DATA[0][:, :2], reduce=None, ndims=2, title='one line', + **ANIM) + tall = hyp.plot(DATA[0][:, :2], reduce=None, ndims=2, title=TALL, **ANIM) + # a title that fits changes nothing + assert tuple(plain.figure.get_size_inches()) == (6.4, 4.8) + assert _assert_titles_on_canvas(tall, 1) == 8 + plain_w, plain_h = plain.figure.get_size_inches() + tall_w, tall_h = tall.figure.get_size_inches() + assert tall_w == plain_w and tall_h > plain_h + a = plain.figure.axes[0].get_position() + b = tall.figure.axes[0].get_position() + assert np.isclose(a.height * plain_h, b.height * tall_h) + assert np.isclose(a.y0 * plain_h, b.y0 * tall_h) + + +def test_a_tall_per_segment_title_of_a_2d_animation_stays_on_the_canvas(): + anim = hyp.plot([d[:, :2] for d in DATA[:2]], reduce=None, ndims=2, + order='serial', title=['short', TALL], **ANIM) + assert _assert_titles_on_canvas(anim, 1) == 8 From 4cbc3b2a1dbfa06f3b12ef984f47fed4864081ff Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 07:11:01 -0500 Subject: [PATCH 27/58] docs: how often on_frame= is called on a save; panels= no longer needs one shared fit (GH #295) on_frame= is not called exactly once per frame on matplotlib: a save draws frame 0 twice (Animation.save runs FuncAnimation._init_draw, which draws the first frame, before its frame loop), so a callback is called n_frames + 1 times. Said so in docs/animation.rst and the plot() docstring, with a test pinning the count for a single plot and a grid. examples/plot_datasets_tour.py said panels= needs one shared fit, which panel_fit='independent' made untrue; examples/plot_gensim_text.py's matching comment is made exact as well. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- docs/animation.rst | 25 +++++++++++++++++++++---- examples/plot_datasets_tour.py | 12 +++++++----- examples/plot_gensim_text.py | 8 +++++--- hypertools/plot/plot.py | 15 +++++++++------ tests/test_animated_panels_review.py | 27 +++++++++++++++++++++++++++ 5 files changed, 69 insertions(+), 18 deletions(-) diff --git a/docs/animation.rst b/docs/animation.rst index 7222a5280..97f1fabf5 100644 --- a/docs/animation.rst +++ b/docs/animation.rst @@ -182,9 +182,13 @@ backends. Per-frame callbacks ------------------- -``on_frame=`` runs your function once per frame with a -:class:`~hypertools.FrameContext`. **Passing it to** ``plot()`` **works on -both backends** and is the portable form: +``on_frame=`` runs your function for every frame that is drawn, with that +frame's :class:`~hypertools.FrameContext`. On plotly that is exactly once +per frame, while the frames are built; on matplotlib it is every time a +frame is rendered, so a frame can come around more than once -- see +:ref:`the callback contract ` below. +**Passing it to** ``plot()`` **works on both backends** and is the portable +form: .. code-block:: python @@ -385,6 +389,16 @@ contract exists: - at build time, before ``plot()`` returns - exactly once +One repeat on matplotlib is certain: a save (``save_path=``, or ``.save()`` +on the returned animation) draws frame 0 twice, so a callback is called +``n_frames + 1`` times for an animation of ``n_frames`` frames, single plot +or ``panels=`` grid alike. That is matplotlib's own doing: +``Animation.save`` first calls ``FuncAnimation._init_draw``, which draws +the first frame to initialize the figure, and then draws every frame, the +first included. (``Animation._start``, which starts an animation shown in +a window, makes the same initial draw.) A callback that is idempotent per +frame cannot tell. + Both backends deliver the same *context metadata* for a given frame index. They do **not** produce interchangeable rendered output from a mutating callback: ``ctx.figure``, ``ctx.axes`` and ``ctx.artists`` are @@ -777,7 +791,10 @@ A few things are specific to a grid: (Clusters fit per panel -- ``panel_fit='independent'`` or a list-valued ``reduce=`` with ``cluster=``/``n_clusters=`` -- keep a legend per panel, because their colors mean something different in each one.) -* ``on_frame=`` is called once per frame for the whole figure. Its +* ``on_frame=`` is called once for the whole figure each time a frame is + drawn, not once per panel (a save draws frame 0 twice, so a callback + sees it twice; see + :ref:`the callback contract `). Its ``FrameContext`` has ``axes`` as a tuple of the panel axes, ``artists`` and ``datasets`` as every panel's in panel order, and ``panels`` as one ordinary per-panel ``FrameContext`` each (that panel's own axes, artists, diff --git a/examples/plot_datasets_tour.py b/examples/plot_datasets_tour.py index aa3388b27..541d5da04 100644 --- a/examples/plot_datasets_tour.py +++ b/examples/plot_datasets_tour.py @@ -56,11 +56,13 @@ # These four sources are unrelated domains with different column counts and # meanings (iris measurements, penguin measurements, Bechdel-test numeric # columns, ...), so there is no single shared pipeline fit that would make -# sense across them -- hyp.plot's panels= draws one dataset per panel through -# ONE shared fit, which requires a common column space. We keep the -# explicit-axes form instead, via hyp.subplots (a thin wrapper over -# plt.subplots that pre-sets the 3-D projection and hands back a flat axes -# array), and fit each source's own pipeline independently as before. +# sense across them. hyp.plot's panels= draws one dataset per panel and by +# default fits ONE shared pipeline across them, which requires a common +# column space; panel_fit='independent' fits each panel's own pipeline +# instead and draws a grid like this one too. Here we show the +# explicit-axes form, via hyp.subplots (a thin wrapper over plt.subplots +# that pre-sets the 3-D projection and hands back a flat axes array): each +# hyp.plot(..., ax=ax) call fits its own source's pipeline independently. n = max(len(loaded), 1) ncols = 2 if n > 1 else 1 nrows = (n + ncols - 1) // ncols diff --git a/examples/plot_gensim_text.py b/examples/plot_gensim_text.py index b6c0b15d7..f4ebdd196 100644 --- a/examples/plot_gensim_text.py +++ b/examples/plot_gensim_text.py @@ -37,9 +37,11 @@ topics = (['pets'] * 3) + (['finance'] * 3) + (['astronomy'] * 3) # These two panels differ in vectorizer=/semantic= -- upstream embedding -# choices that panels=/reduce=[...] cannot express (both only vary the -# final reduce= step of ONE shared pipeline, not the text-embedding stage -# itself), so we keep the explicit-axes form, via hyp.subplots (a thin +# choices that panels=/reduce=[...] cannot express (panels= varies the +# dataset from panel to panel and reduce=[...] the final reduce= step; the +# text-embedding stage is the same in every panel under both, whether the +# panels share one fit or each fits its own with panel_fit='independent'), +# so we keep the explicit-axes form, via hyp.subplots (a thin # wrapper over plt.subplots that pre-sets the 3-D projection and hands back # a flat axes array). # backend='matplotlib' on the grid and on each call: fig.tight_layout() is diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index fb7925687..5d096bed2 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -2952,8 +2952,8 @@ def _validate_dynamic_title(title, animate, row_indices, name='title'): Two dynamic forms are accepted: - * a **callable** ``ctx -> str``, evaluated once per frame with that - frame's `FrameContext`; + * a **callable** ``ctx -> str``, evaluated every time a frame is + drawn, with that frame's `FrameContext`; * a **format pattern** containing ``{index`` -- e.g. ``title='{index:%B %Y}'`` -- formatted per frame with ``index=`` set to the input's own row-index value under the reveal head. @@ -5735,8 +5735,8 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): 'subplots', 'ax', 'panel_fit', 'caption'): shared.pop(key, None) shared['show'] = False - # on_frame= on an animated grid is called once per frame for the whole - # FIGURE (see `_animate_panel_grid`), not once per panel + # on_frame= on an animated grid is called once per DRAWN frame for the + # whole FIGURE (see `_animate_panel_grid`), not once per panel grid_hooks = None if animated: grid_hooks = FrameHooks() @@ -9174,8 +9174,11 @@ def plot( Supported on BOTH backends, with the same per-frame context metadata but different call schedules: matplotlib calls back at render time, so a frame index may recur across a looping animation - or a save; plotly calls back exactly once per frame index, while - the frames are built. **Callbacks must be deterministic and + or a save -- and a save always draws frame 0 twice (matplotlib's + ``Animation.save`` runs ``FuncAnimation._init_draw``, which draws + the first frame, before its own frame loop), so a callback is + called ``n_frames + 1`` times there; plotly calls back exactly + once per frame index, while the frames are built. **Callbacks must be deterministic and idempotent for a given frame context. They must not depend on call count, call order, wall-clock time, or accumulated external state.** diff --git a/tests/test_animated_panels_review.py b/tests/test_animated_panels_review.py index 7f3bc0c6f..4c878c5a6 100644 --- a/tests/test_animated_panels_review.py +++ b/tests/test_animated_panels_review.py @@ -612,3 +612,30 @@ def test_a_tall_per_segment_title_of_a_2d_animation_stays_on_the_canvas(): anim = hyp.plot([d[:, :2] for d in DATA[:2]], reduce=None, ndims=2, order='serial', title=['short', TALL], **ANIM) assert _assert_titles_on_canvas(anim, 1) == 8 + + +# -------------------------------------------------------------------------- +# Round 2 (R8): how often on_frame= is called when an animation is saved +# -------------------------------------------------------------------------- + +@pytest.mark.parametrize('grid', [{}, dict(panels=(1, 2))], + ids=['single', 'grid']) +def test_a_save_calls_on_frame_for_frame_0_twice(tmp_path, grid): + """What docs/animation.rst ("Backend scheduling") and `on_frame=`'s + docstring say: matplotlib's `Animation.save` draws the first frame + once to initialize the figure (`FuncAnimation._init_draw`) and then + draws every frame, so a callback sees frame 0 twice -- ``n_frames + + 1`` calls -- and must be idempotent per frame. Building the animation + calls it for no frame at all.""" + seen = [] + anim = hyp.plot(DATA[:2], on_frame=lambda ctx: seen.append(ctx.frame), + **dict(ANIM, **grid)) + assert seen == [] + anim.save(str(tmp_path / 'saved.gif')) + assert seen == [0] + list(range(anim.n_frames)) + + seen.clear() + saved = hyp.plot(DATA[:2], on_frame=lambda ctx: seen.append(ctx.frame), + save_path=str(tmp_path / 'direct.gif'), + **dict(ANIM, **grid)) + assert seen == [0] + list(range(saved.n_frames)) From 8f2c5dd4eafe14b838480dc7b55ba2132ac7c349 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 07:14:43 -0500 Subject: [PATCH 28/58] fix: wrap a shared legend too wide for its figure; thin a horizontal colorbar's crowded ticks (GH #295) A panels= grid's shared legend wider than the figure could give it (long labels at an explicit size=, or above/below the grid) was clipped at the canvas edge: its labels are now wrapped until it fits. A top/bottom colorbar of a continuous hue whose tick labels ran into each other (values around 1e-4 or 1e5) gets fewer ticks, at round values, measured on a real draw; the caller's own ticks and a discrete bar's are kept. Also documents, in the panels= docstring, the static-grid size= warning, the per-frame title sizing and the on_frame= call count. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/plot/plot.py | 126 ++++++++++++++++++++++++++++-- tests/test_panel_layout_review.py | 124 +++++++++++++++++++++++++++++ 2 files changed, 244 insertions(+), 6 deletions(-) diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index 5d096bed2..4785d2675 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -5482,6 +5482,27 @@ def _finish(cbar): box = cax.get_tightbbox(_measurement_renderer(fig)) strip['colorbar_in'] = box.width / fig.dpi + if strip['legend'] is not None and strip['side'] in ( + 'right', 'left', 'top', 'bottom'): + # a legend wider than the figure can give it was clipped at the + # canvas' edge: a top/bottom legend wider than the figure (already + # down to one column), or a side legend at an explicit `size=` + # (the default figure widens by the legend instead) wider than + # what the grid's 30% floor and the colorbar leave. Its labels + # are wrapped until it fits. + if strip['side'] in ('top', 'bottom'): + limit_in = width_in - 2 * pad + elif widen: + limit_in = np.inf + else: + limit_in = 0.7 * width_in - 2 * pad - ( + strip['colorbar_in'] + pad if strip['colorbar_in'] else 0.0) + if strip['legend_in'][0] > limit_in: + strip['legend'].remove() + strip['legend'], strip['legend_in'] = _wrap_shared_legend( + fig, handles, labels, _call, limit_in) + strip['legend'].set_gid(SHARED_LEGEND_GID) + # the room each side's strip takes (inches) legend_w, legend_h = strip['legend_in'] side = strip['side'] @@ -5551,9 +5572,81 @@ def _finish(cbar): shrink=_SHARED_COLORBAR_HEIGHT, **({} if ticks is None else {'ticks': ticks}))) _place_shared_furniture(fig, strip) + if (strip['colorbar'] is not None and ticks is None + and colorbar_info['kind'] == 'continuous'): + # (a top/bottom bar: its tick labels must not run into each other) + _thin_horizontal_colorbar_ticks(fig, strip['colorbar']) return strip +#: the fewest characters a wrapped shared-legend line is given +_SHARED_LEGEND_MIN_WRAP = 12 + + +def _wrap_shared_legend(fig, handles, labels, call, limit_in): + """Draw a grid's shared legend with its labels WRAPPED so that it is + no wider than `limit_in` inches, and return ``(legend, (width, + height))`` in inches, measured on a real draw. + + Every label is broken at spaces into lines of at most the same number + of characters (a single longer word is broken), and that number is + lowered until the legend fits or reaches `_SHARED_LEGEND_MIN_WRAP` + (the legend is then as narrow as it gets). A label holding mathtext + (``$...$``) is left whole: breaking it could split a formula. `call` + is the keyword arguments of the `Figure.legend` call that drew the + unwrapped legend. + """ + import textwrap + labels = [str(label) for label in labels] + chars = max([len(label) for label in labels] + [1]) + while True: + wrapped = [label if label.count('$') >= 2 + else (textwrap.fill(label, width=chars) or label) + for label in labels] + legend = fig.legend(handles, wrapped, **call) + box = legend.get_window_extent(_measurement_renderer(fig)) + size_in = (box.width / fig.dpi, box.height / fig.dpi) + if size_in[0] <= limit_in or chars <= _SHARED_LEGEND_MIN_WRAP: + return legend, size_in + legend.remove() + chars = max(_SHARED_LEGEND_MIN_WRAP, + min(chars - 1, int(chars * limit_in / size_in[0]))) + + +def _thin_horizontal_colorbar_ticks(fig, cbar, gap_px=4.0): + """Give a HORIZONTAL colorbar fewer ticks until its tick labels stand + clear of each other (at least `gap_px` apart), measured on a real + draw. + + matplotlib picks a horizontal colorbar's ticks without regard to how + wide their labels are, so values that need many digits (around 1e-4: + ``0.00005``, ``0.00010``, ...) were drawn into each other. The ticks + stay at round values (`MaxNLocator`), down to two of them. Only for + ticks hypertools chose: the caller's own ``ticks`` and a discrete + bar's one tick per group are never dropped. A vertical colorbar's + labels are stacked and cannot collide this way. + """ + if getattr(cbar, 'orientation', None) != 'horizontal': + return + from matplotlib.ticker import MaxNLocator + + def _labels(): + renderer = _measurement_renderer(fig) + return sorted((label.get_window_extent(renderer) + for label in cbar.ax.xaxis.get_ticklabels() + if label.get_visible() and label.get_text()), + key=lambda box: box.x0) + + boxes = _labels() + bins = len(boxes) - 1 + while bins > 1 and any(left.x1 + gap_px > right.x0 + for left, right in zip(boxes, boxes[1:])): + bins -= 1 + cbar.locator = MaxNLocator(nbins=bins, steps=[1, 2, 2.5, 5, 10]) + cbar.update_ticks() + boxes = _labels() + + def _place_shared_furniture(fig, strip): """Position a grid's shared legend and colorbar (`strip`, from `_add_shared_furniture`) in their strips: on the right, the legend @@ -7921,7 +8014,10 @@ def plot( 'bottom'}`` (all keys optional; ``location`` defaults to ``'right'``, the same side as the legend -- when both a legend and a right-side colorbar are shown, the figure is widened so neither - is clipped or overlaps the other). Raises ``ValueError`` if + is clipped or overlaps the other). A ``'top'``/``'bottom'`` + matplotlib colorbar of a continuous `hue` is given fewer ticks + where its tick labels would run into each other (your own + ``ticks`` are never dropped). Raises ``ValueError`` if requested with no color mapping available at all (e.g. a single dataset with no `hue`/`cluster`). A `panels=` grid draws ONE colorbar for the whole figure, over one color scale shared by @@ -9575,7 +9671,12 @@ def plot( one entry per dataset. `legend_kwargs=` styles the one legend; a ``loc``/``bbox_to_anchor`` (plotly: ``x``/``y``) in it places that legend in FIGURE coordinates and no strip is reserved for - it. A `colorbar=` ``location`` other than ``'right'`` attaches + it. A shared matplotlib legend wider than the figure can give it + -- above or below the grid, or beside it at an explicit `size=` + (the default figure widens by the legend instead) -- has its + labels wrapped onto several lines instead of being clipped + (labels with ``$...$`` mathtext are left whole). A `colorbar=` + ``location`` other than ``'right'`` attaches the one colorbar to that side of the whole grid. No legend or colorbar is added that the call did not ask for. On the returned matplotlib figure the shared legend is a figure-level legend @@ -9655,12 +9756,21 @@ def plot( made taller by a `caption=`, and enlarged for axis labels as just described. A STATIC 3-D grid keeps its axis labels inside each panel the same way (its default figure grows where the - cubes would otherwise become very small; an explicit `size=` is - honored). `caption=` adds a line of text under the grid, updated + cubes would otherwise become very small). An explicit `size=` is + always honored for a static grid: where it cannot hold the + labeled grid legibly -- a cube would be under half its unlabeled + size, or a panel's own labels would be drawn over each other -- + the cubes are kept at half their unlabeled size, so the labels + may overlap, and one ``UserWarning`` names a size that works and + the alternative ``xlabel='', ylabel='', zlabel=''``. + `caption=` adds a line of text under the grid, updated every frame. A per-frame `title=` (callable or ``{index}`` pattern, one for all panels or a list with one per panel) is - given its room above each panel like a fixed title. `on_frame=` is called ONCE per frame for the whole - figure: its ``FrameContext`` has ``axes`` as a tuple of the panel + given its room above each panel like a fixed title, sized for + the tallest of the first, middle and last frames' titles (see + `title=`). `on_frame=` is called once for the whole figure each + time a frame is drawn, not once per panel (see `on_frame=`: a + save draws frame 0 twice): its ``FrameContext`` has ``axes`` as a tuple of the panel axes, ``artists`` and ``datasets`` as every panel's in panel order, and ``panels`` as one ordinary per-panel ``FrameContext`` each (that panel's own axes, artists and reveal state). @@ -16621,6 +16731,10 @@ def _add_colorbar(fig, ax, colorbar_info, font=None, attached=False): if label: cbar.set_label(label) _apply_font_to_colorbar(cbar, font) + if ticks is None and colorbar_info['kind'] == 'continuous': + # (a top/bottom bar: its tick labels must not run into each + # other) + _thin_horizontal_colorbar_ticks(fig, cbar) # A VERTICAL discrete colorbar ('right'/'left') must read top-to-bottom # in the SAME order as the legend (first group at the TOP) -- matplotlib's diff --git a/tests/test_panel_layout_review.py b/tests/test_panel_layout_review.py index f6fb96f90..4d08bbda8 100644 --- a/tests/test_panel_layout_review.py +++ b/tests/test_panel_layout_review.py @@ -566,3 +566,127 @@ def test_a_static_labeled_grid_that_fits_its_size_does_not_warn( assert not messages _assert_labels_clear(fig, 4) assert _own_label_overlaps(fig, 4) == 0 + + +# -------------------------------------------------------------------------- +# Round 2, R11a: a shared legend wider than its figure can hold +# -------------------------------------------------------------------------- + +WORDY_NAMES = [f'a very long label indeed that goes on and on for dataset ' + f'{i} of the experiment' for i in range(4)] + + +@pytest.mark.parametrize('ndims', [2, 3]) +@pytest.mark.parametrize('loc', [None, 'center left', 'upper center', + 'lower center']) +def test_a_legend_too_wide_for_an_explicit_size_is_wrapped_not_clipped( + loc, ndims): + """The legend of four 78-character names was 547 px wide on a 400 px + canvas and cut off at its edge. Its labels are wrapped.""" + fig = hyp.plot(DATA, '-', panels=(2, 2), ndims=ndims, size=(4, 3), + legend=WORDY_NAMES, show=False, + legend_kwargs={} if loc is None else {'loc': loc}) + assert tuple(fig.get_size_inches()) == (4.0, 3.0) + renderer = _draw(fig) + width, height = fig.canvas.get_width_height() + legend = _legend(fig) + box = legend.get_window_extent(renderer) + assert box.x0 >= -0.5 and box.x1 <= width + 0.5 + assert box.y0 >= -0.5 and box.y1 <= height + 0.5 + texts = [text.get_text() for text in legend.get_texts()] + assert any('\n' in text for text in texts) + assert [' '.join(text.split()) for text in texts] == WORDY_NAMES + for text in legend.get_texts(): + inner = text.get_window_extent(renderer) + assert inner.x0 >= 0 and inner.x1 <= width + if ndims == 2: + for ax in fig.axes[:4]: + assert not _shrunk(box).overlaps(ax.get_window_extent(renderer)) + + +def test_a_long_legend_at_the_default_size_widens_the_figure_unwrapped(): + fig = hyp.plot(DATA, '-', panels=(2, 2), ndims=2, legend=WORDY_NAMES, + show=False) + renderer = _draw(fig) + legend = _legend(fig) + assert [text.get_text() for text in legend.get_texts()] == WORDY_NAMES + assert legend.get_window_extent(renderer).x1 <= ( + fig.canvas.get_width_height()[0] + 0.5) + + +def test_a_mathtext_legend_label_is_never_broken(): + names = [r'$\alpha + \beta + \gamma + \delta + \epsilon + \zeta$ ' + r'and then some more words after the formula'] + WORDY_NAMES[1:] + fig = hyp.plot(DATA, '-', panels=(2, 2), ndims=2, size=(4, 3), + legend=names, show=False) + texts = [text.get_text() for text in _legend(fig).get_texts()] + assert texts[0] == names[0] + assert all('\n' in text for text in texts[1:]) + + +# -------------------------------------------------------------------------- +# Round 2, R11b: a top/bottom colorbar's tick labels +# -------------------------------------------------------------------------- + +def _colorbar_tick_boxes(fig): + """The drawn boxes of the (one) colorbar's visible tick labels along + its long axis, left to right, and their texts.""" + renderer = _draw(fig) + (bar,) = [ax for ax in fig.axes if ax.get_label() == ''] + place = bar.get_position() + axis = bar.xaxis if place.width > place.height else bar.yaxis + labels = [label for label in axis.get_ticklabels() + if label.get_visible() and label.get_text()] + boxes = [label.get_window_extent(renderer) for label in labels] + order = np.argsort([box.x0 for box in boxes]) + return ([boxes[i] for i in order], + [labels[i].get_text() for i in order], bar) + + +@pytest.mark.parametrize('scale', [1e-4, 1.0, 1e5], ids=['1e-4', '1', '1e5']) +@pytest.mark.parametrize('location', ['top', 'bottom']) +@pytest.mark.parametrize('call', [ + dict(panels=(2, 2)), dict(panels=(2, 2), ndims=2), dict(panels=(1, 4)), + dict(panels=(1, 2), ndims=2, size=(3, 2.5)), dict(), + dict(animate=True, duration=1, frame_rate=4, panels=(1, 2)), +], ids=['2x2-3d', '2x2-2d', '1x4', 'small', 'single', 'animated']) +def test_a_horizontal_colorbars_tick_labels_do_not_overlap(call, location, + scale): + """Values around 1e-4 drew nine labels like '0.00005' into each other + on a top/bottom bar: it gets fewer ticks, at round values.""" + n = (call['panels'][0] * call['panels'][1]) if 'panels' in call else 1 + hue = [np.linspace(0, scale * (i + 1), 30) for i in range(n)] + data = DATA[:n] if n > 1 else DATA[0] + result = hyp.plot(data, 'o', hue=hue if n > 1 else hue[0], show=False, + colorbar={'location': location, 'label': 'a label'}, + title='t', **call) + fig = result.figure if 'animate' in call else result + boxes, texts, bar = _colorbar_tick_boxes(fig) + assert len(boxes) >= 2, texts + for left, right in zip(boxes, boxes[1:]): + assert left.x1 < right.x0, texts + low, high = bar.get_xlim() + for tick in bar.xaxis.get_majorticklocs(): + assert low - 1e-12 * scale <= tick <= high + 1e-12 * scale + + +def test_thinning_leaves_the_callers_ticks_and_vertical_bars_alone(): + hue = [np.linspace(0, 1e-4 * (i + 1), 30) for i in range(4)] + mine = [0.0, 0.5e-4, 1e-4, 1.5e-4, 2e-4, 2.5e-4, 3e-4, 3.5e-4, 4e-4] + fig = hyp.plot(DATA, 'o', hue=hue, panels=(2, 2), show=False, + colorbar={'location': 'top', 'ticks': mine}) + _, _, bar = _colorbar_tick_boxes(fig) + assert np.allclose(bar.xaxis.get_majorticklocs(), mine) + plt.close('all') + fig = hyp.plot(DATA, 'o', hue=hue, panels=(2, 2), show=False, + colorbar=True) + boxes, texts, _ = _colorbar_tick_boxes(fig) + assert len(texts) == 9, texts + + +def test_a_discrete_horizontal_colorbar_keeps_one_tick_per_group(): + hue = [['a'] * 15 + ['b'] * 15, ['b'] * 15 + ['c'] * 15] + fig = hyp.plot(DATA[:2], 'o', hue=hue, panels=(1, 2), show=False, + colorbar={'location': 'bottom'}) + _, texts, _ = _colorbar_tick_boxes(fig) + assert texts == ['a', 'b', 'c'] From 5e842f2959037755c898db5509c95829ae833d9c Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 07:23:08 -0500 Subject: [PATCH 29/58] docs: changelog, animation guide and notes for review round 2 (GH #295) Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- CHANGELOG.md | 29 ++++++++++++++++--- docs/animation.rst | 4 ++- ...sion_2026-11-22_feat295-animated-panels.md | 10 +++++++ 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 831007fa8..7d663a77c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,7 +26,8 @@ draws into a figure the caller built, found by executing notebooks with unlabeled one's size, and an explicit `size=` that would leave cubes under half their unlabeled size raises, naming a size that works (`xlabel='', ylabel='', zlabel=''` drops the labels). Per-frame titles (a callable, an `'{index...}'` pattern, or a - list with one per panel) get their room above each panel, and + list with one per panel) get their room above each panel, sized for the + tallest of the first, middle and last frames' titles, and `animate={...}` dictionaries work as for a single plot. Without `size=`, the figure is sized by the grid (3.2 in per panel each way, at least 6.4 in wide) instead of matplotlib's fixed 6.4 x 4.8 in, so a @@ -34,7 +35,10 @@ draws into a figure the caller built, found by executing notebooks with widened by a shared legend or colorbar strip and made taller by a caption. A static grid's default size is unchanged, except as noted for axis labels under "Fixed". - `on_frame=` is called once per frame for the whole figure, with a + `on_frame=` is called once per frame drawn, for the whole figure (a + save draws frame 0 twice: matplotlib draws it once while setting up and + again as the first frame, so a callback must give the same result when + called again for the same frame), with a `FrameContext` whose `axes` is a tuple of the panel axes and whose new `panels` field holds one per-panel context each. `return_model=True` returns the panel bundle with `'animation'` added. Refused with an error @@ -170,8 +174,25 @@ draws into a figure the caller built, found by executing notebooks with the canvas. A labeled panel's cube is now drawn smaller until its labels fit its own cell; where that would leave the cubes very small the default figure grows in the direction that limits them (a 1 x 4 grid of - labeled 3-D panels is wider than 6.4 in), and an explicit `size=` is - honored as given. Grids without axis labels are unchanged. + labeled 3-D panels is wider than 6.4 in). An explicit `size=` is + honored as given; where it cannot hold the labeled grid legibly, the + cubes are kept at half their unlabeled size at least and one + `UserWarning` names a size that works (and + `xlabel='', ylabel='', zlabel=''` as the alternative). Grids without + axis labels are unchanged. +- **An animated title that grows after the first frame stays on the + canvas.** Room for a per-frame `title=` is sized for the tallest of the + first, middle and last frames' titles (it was sized for frame 0), in a + grid and in a single plot; a 2-D animation's figure grows upward for a + title taller than its default margin (a fixed eight-line title left the + canvas). +- **A shared grid legend too wide for its figure is wrapped.** With a + small explicit `size=`, long legend labels were clipped at the canvas + edge; they are wrapped onto more lines instead. +- **A horizontal colorbar's tick labels do not overlap.** A top or bottom + colorbar of a continuous `hue=` with long tick labels (values around + 1e-4) gets fewer ticks until its labels are clear of each other; + `ticks=` given by the caller are kept. - **A failed `panels=` call leaves no figure behind.** Whatever makes a grid call raise (a refused combination, an unknown `predict=` model, a `title=`/`caption=` callable that raises, a failed save), every figure diff --git a/docs/animation.rst b/docs/animation.rst index 97f1fabf5..9de1d2e20 100644 --- a/docs/animation.rst +++ b/docs/animation.rst @@ -780,7 +780,9 @@ A few things are specific to a grid: that needs more lines than all three runs above its room). * Colors, the legend and the colorbar belong to the whole grid, as in a static grid: each dataset keeps the color the single-axes call of all the - datasets gives it, ``hue=`` is mapped through one scale, and one legend + datasets gives it, ``hue=`` is read (categorical or continuous) and + mapped through one scale, a ``legend=`` list names the grid's datasets or + its categories, and one legend and/or one colorbar is drawn in a strip right of the panels. They are static across frames, and every rotating cube stays clear of the strip. ``legend_kwargs={'loc': ...}`` moves the legend's strip to another side of diff --git a/notes/session_2026-11-22_feat295-animated-panels.md b/notes/session_2026-11-22_feat295-animated-panels.md index eaad84383..4542f789d 100644 --- a/notes/session_2026-11-22_feat295-animated-panels.md +++ b/notes/session_2026-11-22_feat295-animated-panels.md @@ -170,3 +170,13 @@ Structure of the color/legend fix (one mechanism instead of per-item cases): - Plotly: `_legend_trace_look` compares line width and marker size; `merge_panel_legends(order=)` ranks the kept entries; a grid's legend is wanted by `legend=` or by `names=` alone. + +Layout half of round 2 (done by a subagent in a side worktree, cherry-picked): +R1 static labeled grid at a too-small explicit `size=` clamps cubes at 50% +(`_REFUSED_LABELED_CUBE_SHARE`), warns once with a size that works; Codex 9 +title room = tallest of first/middle/last frames (`_caption_sample_frames`), +single-axes too (2-D figure grows upward); R11 `_wrap_shared_legend`, +`_thin_horizontal_colorbar_ticks`; R8 `Animation.save` -> +`FuncAnimation._init_draw` draws frame 0 before the loop (documented); R9 +example text. Left open: an animated grid's figure is not enlarged for a +tall title (panels shrink under it). From fb9a5b2995da13e40ed3b8517e385639e3ac060d Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 08:07:58 -0500 Subject: [PATCH 30/58] feat: a static panels= grid's default figure is sized by the grid (GH #295) Owner decision 2026-11-22 for 1.2.0: with no size=, a static panels=/subplots= grid gets the figure an animated one already had -- 3.2 in per panel each way, at least 6.4 in wide, then the shared legend/colorbar strip, caption and axis-label room as before -- instead of a fixed 6.4 x 4.8 in whatever the grid's shape. The plotly grid follows the same rule at 100 px per inch. An explicit size= is honored exactly; the grid's shape (panels=True/'auto') is still chosen first from the given or default aspect; hyp.subplots() called directly keeps its own default size. _ANIMATED_PANEL_CELL_INCHES is now _PANEL_CELL_INCHES, with _default_panel_grid_size() shared by both backends. Tests: new tests/test_static_panel_grid_size.py; the two tests that asserted the old static default are rewritten for the new one. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/plot/plot.py | 89 +++++-- hypertools/plot/plotly_backend.py | 13 +- tests/test_animated_panels.py | 9 +- tests/test_panel_layout_review.py | 7 +- tests/test_static_panel_grid_size.py | 340 +++++++++++++++++++++++++++ 5 files changed, 425 insertions(+), 33 deletions(-) create mode 100644 tests/test_static_panel_grid_size.py diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index 4785d2675..b2d0edcbb 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -3459,7 +3459,10 @@ def subplots(nrows=1, ncols=1, ndims=3, size=None, backend='auto', 3 (default) gives every panel a 3-D projection; 1 or 2 gives ordinary 2-D axes. Matches `hyp.plot`'s `ndims=`. size : [width, height] or None - Figure size in inches (`figsize`); `None` keeps matplotlib's. + Figure size in inches (`figsize`); `None` keeps matplotlib's + default (6.4 x 4.8 in; 640 x 480 px on plotly) whatever the grid's + shape. (Only `hyp.plot(..., panels=)` sizes its default figure by + the grid, 3.2 in per panel.) **fig_kw Forwarded to `matplotlib.pyplot.subplots` (`sharex=`, `dpi=`, `gridspec_kw=`, an explicit `subplot_kw=`, ...) or, under plotly, @@ -4789,9 +4792,19 @@ def _reemit_panel_warnings(probe_caught, draw_caught): registry=registry) -#: side (inches) of one panel's cell in an animated `panels=` grid's default -#: figure (no `size=`); see `_plot_panels` -_ANIMATED_PANEL_CELL_INCHES = 3.2 +#: side (inches) of one panel's cell in a `panels=` grid's default figure +#: (no `size=`), static or animated; see `_default_panel_grid_size` +_PANEL_CELL_INCHES = 3.2 + + +def _default_panel_grid_size(nrows, ncols): + """The default figure (inches) of an `nrows` x `ncols` `panels=` grid, + before any room for a legend/colorbar, axis labels or a caption is + added: one `_PANEL_CELL_INCHES` square cell per panel, and never + narrower than hypertools' default single figure (6.4 in), so a single + column keeps the usual width. The plotly grid uses the same size at + its 100 px per inch.""" + return (max(6.4, _PANEL_CELL_INCHES * ncols), _PANEL_CELL_INCHES * nrows) # -------------------------------------------------------------------------- @@ -6139,15 +6152,15 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): return grid _grid_size = call_kwargs.get('size') - if animated and _grid_size is None: - # an animated grid's default figure is sized BY the grid, one - # square cell per panel: every frame of the saved clip carries the - # figure's whole canvas, and matplotlib's 6.4 x 4.8 in default - # leaves a 1 x 4 row of cubes with more blank canvas above and - # below it than the cubes themselves fill (GH #295). Never narrower - # than that default, so a single column keeps its usual width. - _grid_size = (max(6.4, _ANIMATED_PANEL_CELL_INCHES * ncols), - _ANIMATED_PANEL_CELL_INCHES * nrows) + if _grid_size is None: + # a grid's default figure is sized BY the grid, one square cell + # per panel, static or animated (static since 1.2.0): matplotlib's + # 6.4 x 4.8 in default leaves a 1 x 4 row of cubes with more blank + # canvas above and below it than the cubes themselves fill, and + # every frame of a saved clip carries that canvas (GH #295). The + # grid's SHAPE was chosen before this, from `size=` or the default + # figure's aspect (`_auto_panel_grid`). + _grid_size = _default_panel_grid_size(nrows, ncols) def _draw_grid(consolidate): """Draw every panel into a fresh grid figure. With `consolidate` @@ -6462,8 +6475,8 @@ def _common(name): _PANEL_LABELED_CUBE_SHARE = 0.7 #: ...the least a labeled STATIC panel cube may be before its default figure -#: grows (a static grid's default figure is one fixed size whatever the -#: grid, so it is enlarged only where the cubes would become very small)... +#: grows (a static cube has one view, so its labels need less room than a +#: rotating one's and the figure is enlarged a little later)... _STATIC_LABELED_CUBE_SHARE = 0.65 #: ...and the legible floor at an explicit `size=` (a size the caller chose @@ -7062,6 +7075,10 @@ def _draw_panels(consolidate): strip_px += PANEL_GUTTER_PAD_PX if strip_px else 0 fig = make_panel_grid(nrows, ncols, ndims, size=call_kwargs.get('size'), + # no `size=`: sized by the grid, as the matplotlib + # grid is (the gutters/strip are added to it) + default_size=_default_panel_grid_size(nrows, + ncols), gutter_px=(0 if consolidate else panel_gutter_px( legend_present, colorbar_present)), title_px=title_px, strip_px=strip_px) @@ -8227,7 +8244,12 @@ def plot( size : list A [width, height] pair of numbers, in inches, to resize the figure - (anything else raises ``ValueError`` naming size) + (anything else raises ``ValueError`` naming size). Default: 6.4 x + 4.8 in for a single plot. A `panels=` grid without `size=` is + sized by its grid instead -- 3.2 in per panel each way, at least + 6.4 in wide, plus room for a shared legend or colorbar, a caption + and axis labels (see `panels=`) -- and with `size=` it is drawn + at exactly that size. elev : int or float The camera elevation angle, in degrees, for 3-D plots: the angle @@ -9571,7 +9593,24 @@ def plot( tall one, four form 2x2, six form 2x3; an ``int`` is the number of COLUMNS; an ``(nrows, ncols)`` pair is used verbatim and must have room for every panel. Spare cells are hidden, the - layout is tightened, and the one `Figure` is returned. Every cell + layout is tightened, and the one `Figure` is returned. + + THE FIGURE IS SIZED BY THE GRID when `size=` is not given, static + or animated, on matplotlib and on plotly (1.2; a static grid was + a fixed 6.4 x 4.8 in before, whatever its shape): 3.2 in per + panel each way and at least 6.4 in wide, so a 1 x 4 row is 12.8 x + 3.2 in, a 2 x 2 grid 6.4 x 6.4 in and a 2 x 3 grid 9.6 x 6.4 in + (plotly: 100 px per inch). To that is added the strip of a shared + legend or colorbar (wider), a `caption=` (taller) and, for 3-D + panels, room for axis labels where they need it (see below). The + grid's shape is chosen first -- for ``True``/``'auto'``, from the + aspect of `size=` or of the default 6.4 x 4.8 in figure -- and + the default figure is then sized by that shape. An explicit + `size=` is the whole figure's size, as for a single plot. Only + `panels=` does this: a grid from `hyp.subplots()` keeps + matplotlib's default figure size (or the `size=` given to it). + + Every cell has ONE projection, decided from the ANALYZED data (the rows the pipeline hands each panel to draw, not the raw column count: two raw columns through a feature-expanding ``manip='Delay'`` come out @@ -9749,14 +9788,14 @@ def plot( cubes half their unlabeled size and raises below that, naming a size that works; ``xlabel='', ylabel='', zlabel=''`` drops the labels instead. Without `size=` the figure - is sized BY THE GRID -- 3.2 in per panel each way, at least - 6.4 in wide -- so a saved clip of a row of panels is not mostly - blank canvas (a static grid keeps the 6.4 x 4.8 in default); it - is then widened by the strip of a shared legend or colorbar, - made taller by a `caption=`, and enlarged for axis labels as - just described. A STATIC 3-D grid keeps its axis labels inside - each panel the same way (its default figure grows where the - cubes would otherwise become very small). An explicit `size=` is + is sized by the grid, as a static grid's is (above) -- so a + saved clip of a row of panels is not mostly blank canvas -- then + widened by the strip of a shared legend or colorbar, made taller + by a `caption=`, and enlarged for axis labels as just described. + A STATIC 3-D grid keeps its axis labels inside each panel the + same way, at its one view (its default figure grows only where a + cube would otherwise be under 65% of an unlabeled one's size, + which the grid-sized cells seldom need). An explicit `size=` is always honored for a static grid: where it cannot hold the labeled grid legibly -- a cube would be under half its unlabeled size, or a panel's own labels would be drawn over each other -- diff --git a/hypertools/plot/plotly_backend.py b/hypertools/plot/plotly_backend.py index 3347e6288..f7e85ffe8 100644 --- a/hypertools/plot/plotly_backend.py +++ b/hypertools/plot/plotly_backend.py @@ -3160,11 +3160,14 @@ def __repr__(self): def make_panel_grid(nrows, ncols, ndims, titles=None, size=None, gutter_px=0, title_px=None, strip_px=0, - **make_subplots_kw): + default_size=None, **make_subplots_kw): """The empty plotly grid `panels=` and `hyp.subplots(backend='plotly')` fill: a `plotly.subplots.make_subplots` figure with ``'scene'`` cells for 3-D and ``'xy'`` cells otherwise, sized like the matplotlib grid - (`size` inches x 100 px, default `DEFAULT_FIGSIZE`), with `gutter_px` + (`size` inches x 100 px; without one, `default_size` inches -- what + `panels=` passes: one 3.2 in square per cell, see + `plot._default_panel_grid_size` -- or `DEFAULT_FIGSIZE`, which is what + `hyp.subplots(backend='plotly')` keeps), with `gutter_px` reserved to the right of EVERY cell (and in the right margin) for a per-panel legend/colorbar (see `panel_gutter_px`). When `size` is not given the figure is widened by the gutters, so the default grid stays @@ -3193,8 +3196,10 @@ def make_panel_grid(nrows, ncols, ndims, titles=None, size=None, if size is not None: width, height = int(size[0] * 100), int(size[1] * 100) else: - width = int(DEFAULT_FIGSIZE[0] * 100) + gutter_px * ncols + strip_px - height = int(DEFAULT_FIGSIZE[1] * 100) + base_w, base_h = (DEFAULT_FIGSIZE if default_size is None + else default_size) + width = int(round(base_w * 100)) + gutter_px * ncols + strip_px + height = int(round(base_h * 100)) # the strip is taken off the right; the grid is laid out in the rest full_width, width = width, max(width - int(strip_px), 1) titles = list(titles) if titles is not None else [] diff --git a/tests/test_animated_panels.py b/tests/test_animated_panels.py index a2237a4fe..36e5daa83 100644 --- a/tests/test_animated_panels.py +++ b/tests/test_animated_panels.py @@ -127,9 +127,14 @@ def test_an_explicit_size_is_kept_for_a_bare_grid(): assert tuple(ani.figure.get_size_inches()) == pytest.approx((9, 4)) -def test_a_static_grid_keeps_its_default_size(): +def test_a_static_grid_is_sized_by_its_grid_too(): + # CHANGED for 1.2.0 (owner decision 2026-11-22): static grids are sized + # by the grid (this asserted the fixed 6.4 x 4.8 in default) fig = hyp.plot(DATA, panels=(1, 4), show=False) - assert tuple(fig.get_size_inches()) == pytest.approx((6.4, 4.8)) + assert tuple(fig.get_size_inches()) == pytest.approx((12.8, 3.2)) + animated = _grid() + assert tuple(fig.get_size_inches()) == pytest.approx( + tuple(animated.figure.get_size_inches())) def test_subplots_alias_animates_the_same_grid(): diff --git a/tests/test_panel_layout_review.py b/tests/test_panel_layout_review.py index 4d08bbda8..53eb07eb8 100644 --- a/tests/test_panel_layout_review.py +++ b/tests/test_panel_layout_review.py @@ -145,8 +145,11 @@ def test_static_grid_without_axis_labels_is_not_resized_or_rezoomed(): plain = hyp.plot(DATA, panels=(2, 2), show=False) unlabeled = hyp.plot(XYZ, panels=(2, 2), xlabel='', ylabel='', zlabel='', show=False) - assert tuple(plain.get_size_inches()) == (6.4, 4.8) - assert tuple(unlabeled.get_size_inches()) == (6.4, 4.8) + # CHANGED for 1.2.0 (owner decision 2026-11-22): static grids are sized + # by the grid -- 3.2 in per panel, so 6.4 x 6.4 in for 2 x 2 (this + # compared to the fixed 6.4 x 4.8 in default) + assert tuple(plain.get_size_inches()) == (6.4, 6.4) + assert tuple(unlabeled.get_size_inches()) == (6.4, 6.4) for a, b in zip(plain.axes, unlabeled.axes): assert np.allclose(a.get_box_aspect(), b.get_box_aspect()) diff --git a/tests/test_static_panel_grid_size.py b/tests/test_static_panel_grid_size.py new file mode 100644 index 000000000..732269297 --- /dev/null +++ b/tests/test_static_panel_grid_size.py @@ -0,0 +1,340 @@ +"""A static `panels=` grid's default figure is sized BY THE GRID (1.2.0). + +Owner decision 2026-11-22: with no `size=`, a static `panels=`/`subplots=` +grid gets the figure an animated one already had -- one 3.2 in square cell +per panel, never narrower than matplotlib's 6.4 in -- instead of the fixed +6.4 x 4.8 in figure that left a 1 x 4 row of cubes small between two white +bands. An explicit `size=` is honored exactly, `hyp.subplots()` called +directly keeps its own default, and the plotly grid follows the same rule +at its 100 px per inch. + +Real figures, really drawn (Agg) or really built (plotly): every assertion +reads sizes, artists and pixels back off the returned figure. Nothing is +mocked. +""" +import itertools +import warnings + +import matplotlib +matplotlib.use('Agg') + +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +import pytest + +import hypertools as hyp +from hypertools.plot import plot as plot_module + +RNG = np.random.default_rng(295) +DATA = [RNG.normal(size=(30, 3)).cumsum(axis=0) for _ in range(6)] +FRAMES = [pd.DataFrame(d, columns=['first axis', 'second axis', + 'third axis']) for d in DATA] +ANIM = dict(animate='spin', duration=1, frame_rate=4, show=False) + +#: grid shape -> the default figure of a bare grid (inches) +SHAPES = [((1, 2), (6.4, 3.2)), ((1, 3), (9.6, 3.2)), ((1, 4), (12.8, 3.2)), + ((2, 2), (6.4, 6.4)), ((2, 3), (9.6, 6.4)), ((3, 1), (6.4, 9.6)), + ((4, 1), (6.4, 12.8))] + + +@pytest.fixture(autouse=True) +def _close_figures(): + yield + plt.close('all') + + +def _size(fig): + return tuple(float(v) for v in fig.get_size_inches()) + + +def _draw(fig): + fig.canvas.draw() + return fig.canvas.get_renderer() + + +# -------------------------------------------------------------------------- +# matplotlib: the default size +# -------------------------------------------------------------------------- + +def test_the_cell_constant_is_not_named_for_animation(): + assert plot_module._PANEL_CELL_INCHES == 3.2 + assert not hasattr(plot_module, '_ANIMATED_PANEL_CELL_INCHES') + + +@pytest.mark.parametrize('ndims', [2, 3]) +@pytest.mark.parametrize('shape, expected', SHAPES) +def test_a_bare_static_grid_is_sized_by_its_grid(shape, expected, ndims): + n = shape[0] * shape[1] + fig = hyp.plot(DATA[:n], panels=shape, ndims=ndims, show=False) + assert _size(fig) == pytest.approx(expected) + + +def test_a_grid_with_an_empty_cell_is_sized_by_the_grid_not_the_panels(): + fig = hyp.plot(DATA[:5], panels=(2, 3), show=False) + assert _size(fig) == pytest.approx((9.6, 6.4)) + + +def test_subplots_alias_is_sized_the_same_way(): + fig = hyp.plot(DATA[:4], subplots=(1, 4), show=False) + assert _size(fig) == pytest.approx((12.8, 3.2)) + + +@pytest.mark.parametrize('extras', [ + {}, dict(title=['a', 'b', 'c', 'd']), dict(legend=True), + dict(legend=['one', 'two', 'three', 'four'], title=['a', 'b', 'c', 'd']), + dict(hue=[np.arange(30)] * 4, colorbar=True), +], ids=['bare', 'titles', 'legend', 'legend-titles', 'colorbar']) +@pytest.mark.parametrize('shape', [(1, 4), (2, 2), (4, 1)]) +def test_static_and_animated_default_sizes_are_equal(shape, extras): + """Nothing here is animation-specific (no axis labels for a rotating + cube to swing, no caption), so the two figures are the same size.""" + static = hyp.plot(DATA[:4], panels=shape, show=False, **extras) + animated = hyp.plot(DATA[:4], panels=shape, **dict(ANIM, **extras)) + assert _size(static) == pytest.approx(_size(animated.figure)) + + +@pytest.mark.parametrize('shape', [(1, 4), (2, 2)]) +def test_static_and_animated_2d_default_sizes_are_equal(shape): + static = hyp.plot(DATA[:4], panels=shape, ndims=2, show=False) + animated = hyp.plot(DATA[:4], panels=shape, ndims=2, animate=True, + duration=1, frame_rate=4, show=False) + assert _size(static) == pytest.approx(_size(animated.figure)) + + +def test_a_shared_legend_widens_the_grid_sized_figure_by_its_strip(): + bare = hyp.plot(DATA[:4], panels=(1, 4), show=False) + legend = hyp.plot(DATA[:4], panels=(1, 4), legend=True, show=False) + assert _size(legend)[0] > _size(bare)[0] + assert _size(legend)[1] == pytest.approx(_size(bare)[1]) + + +@pytest.mark.parametrize('extras', [ + {}, dict(legend=True), dict(title=['a', 'b', 'c', 'd']), + dict(legend=True, title=['a', 'b', 'c', 'd']), + dict(hue=[np.arange(30)] * 4, colorbar=True), +], ids=['bare', 'legend', 'titles', 'legend-titles', 'colorbar']) +@pytest.mark.parametrize('size', [(6.4, 4.8), (8, 3), (5, 9), (12.8, 3.2)]) +@pytest.mark.parametrize('ndims', [2, 3]) +def test_an_explicit_size_is_honored_exactly(size, extras, ndims): + fig = hyp.plot(DATA[:4], panels=(1, 4), ndims=ndims, size=size, + show=False, **extras) + assert _size(fig) == pytest.approx(size) + + +@pytest.mark.parametrize('size', [(6.4, 4.8), (8, 3), (12.8, 3.2)]) +@pytest.mark.parametrize('ndims', [2, 3]) +def test_a_caption_only_adds_its_own_room_to_an_explicit_size(size, ndims): + """`caption=` makes any figure taller by the caption's height where + the canvas has no room for it (its documented rule, unchanged): the + width given is kept, and the height grows by one line at most.""" + fig = hyp.plot(DATA[:4], panels=(1, 4), ndims=ndims, size=size, + caption='a caption', show=False) + width, height = _size(fig) + assert width == pytest.approx(size[0]) + assert size[1] - 1e-9 <= height <= size[1] + 0.3 + + +# -------------------------------------------------------------------------- +# panels=True/'auto': the shape comes from the aspect, then the size from +# the shape +# -------------------------------------------------------------------------- + +@pytest.mark.parametrize('n, shape, expected', [ + (2, (1, 2), (6.4, 3.2)), (3, (1, 3), (9.6, 3.2)), + (4, (2, 2), (6.4, 6.4)), (5, (2, 3), (9.6, 6.4)), + (6, (2, 3), (9.6, 6.4))]) +@pytest.mark.parametrize('panels', [True, 'auto']) +def test_auto_grid_shape_is_chosen_first_then_sized(n, shape, expected, + panels): + """The shape is the one the default 6.4 x 4.8 in ASPECT picks (as + documented and as before); the default figure is then sized by it.""" + result = hyp.plot(DATA[:n], panels=panels, show=False, + return_model=True) + assert tuple(result['panels']) == shape + assert _size(result['fig']) == pytest.approx(expected) + + +def test_auto_grid_with_an_explicit_size_uses_that_aspect_and_that_size(): + result = hyp.plot(DATA[:4], panels=True, size=(12, 3), show=False, + return_model=True) + assert tuple(result['panels']) == (1, 4) + assert _size(result['fig']) == pytest.approx((12, 3)) + + +# -------------------------------------------------------------------------- +# what the sizing is for +# -------------------------------------------------------------------------- + +def test_a_row_of_cubes_fills_most_of_the_canvas_height(): + """A 1 x 4 row of cubes spanned under a fifth of the 6.4 x 4.8 in + figure's height, between two white bands; in a 3.2 in tall figure it + spans what matplotlib draws a cube at in a square 3-D axes.""" + fig = hyp.plot(DATA[:4], panels=(1, 4), show=False) + renderer = _draw(fig) + ink = np.asarray(fig.canvas.buffer_rgba())[..., :3].min(axis=2) < 128 + rows = np.flatnonzero(ink.any(axis=1)) + assert (rows[-1] - rows[0]) / ink.shape[0] > 0.5 + # ...and each panel's square is its whole cell: about 3.2 in a side + for ax in fig.axes[:4]: + box = ax.get_window_extent(renderer) + assert min(box.width, box.height) / fig.dpi > 2.4 + + +@pytest.mark.parametrize('shape', [(1, 4), (2, 2), (3, 1)]) +def test_axis_labels_enlarge_a_static_grid_little(shape): + """The grid-sized cells hold a labeled cube almost as they are: the + figure grows by a tenth at most (the old fixed figure grew a 1 x 4 + row from 6.4 to more than 10 in wide), and the cube keeps a real + share of its cell.""" + n = shape[0] * shape[1] + plain = hyp.plot(DATA[:n], panels=shape, show=False) + labeled = hyp.plot(FRAMES[:n], panels=shape, show=False) + assert _size(labeled)[0] <= 1.1 * _size(plain)[0] + assert _size(labeled)[1] <= 1.1 * _size(plain)[1] + assert _size(labeled)[0] >= _size(plain)[0] + assert _size(labeled)[1] >= _size(plain)[1] + + +def test_a_default_size_labeled_grid_does_not_warn(): + with warnings.catch_warnings(): + warnings.simplefilter('error') + hyp.plot(FRAMES[:4], panels=(1, 4), show=False) + + +def _furniture_boxes(ax, renderer): + """The drawn boxes of everything a 2-D panel hangs outside its axes: + title, axis labels and tick labels.""" + texts = [ax.title, ax.xaxis.label, ax.yaxis.label] + texts += list(ax.get_xticklabels()) + list(ax.get_yticklabels()) + return [t.get_window_extent(renderer) for t in texts + if t.get_visible() and t.get_text()] + + +def _overlap(a, b, slack=1.0): + return (min(a.x1, b.x1) - max(a.x0, b.x0) > slack + and min(a.y1, b.y1) - max(a.y0, b.y0) > slack) + + +@pytest.mark.parametrize('legend', [False, True], ids=['plain', 'legend']) +@pytest.mark.parametrize('shape, n', [((1, 4), 4), ((2, 2), 4), ((4, 1), 4), + ((2, 3), 6), ((2, 3), 5)]) +def test_2d_grid_furniture_does_not_collide(shape, n, legend): + """Titles, axis labels (from DataFrame columns) and tick labels of a + 2-D grid at its default size: none is drawn over another panel's axes + or furniture, over the shared legend, or off the canvas.""" + frames = [f[['first axis', 'second axis']] for f in FRAMES[:n]] + fig = hyp.plot(frames, panels=shape, ndims=2, reduce=None, + title=[f'panel {i}' for i in range(n)], + legend=True if legend else None, show=False) + renderer = _draw(fig) + panels = [ax for ax in fig.axes[:n] if ax.get_visible()] + assert len(panels) == n + for ax in panels: + assert ax.get_xlabel() == 'first axis' + assert ax.get_ylabel() == 'second axis' + width, height = fig.canvas.get_width_height() + furniture = [_furniture_boxes(ax, renderer) for ax in panels] + for i, boxes in enumerate(furniture): + for box in boxes: + assert box.x0 >= -1 and box.y0 >= -1, i + assert box.x1 <= width + 1 and box.y1 <= height + 1, i + for legend_artist in fig.legends: + assert not _overlap( + box, legend_artist.get_window_extent(renderer)), i + # a panel's own furniture: no two pieces on each other + for one, other in itertools.combinations(boxes, 2): + assert not _overlap(one, other), i + for (i, a), (j, b) in itertools.combinations(enumerate(panels), 2): + for box in furniture[i]: + assert not _overlap(box, b.get_window_extent(renderer)), (i, j) + for theirs in furniture[j]: + assert not _overlap(box, theirs), (i, j) + for box in furniture[j]: + assert not _overlap(box, a.get_window_extent(renderer)), (i, j) + # square-ish, roomy cells: no panel's axes is squeezed thin + for ax in panels: + box = ax.get_window_extent(renderer) + assert box.width / fig.dpi > 1.6 and box.height / fig.dpi > 1.6 + + +# -------------------------------------------------------------------------- +# hyp.subplots() called directly keeps its own default +# -------------------------------------------------------------------------- + +@pytest.mark.parametrize('shape', [(1, 4), (2, 2), (4, 1)]) +def test_hyp_subplots_keeps_matplotlibs_default_size(shape): + fig, axes = hyp.subplots(*shape, backend='matplotlib') + assert _size(fig) == pytest.approx((6.4, 4.8)) + for ax, data in zip(axes, DATA): + hyp.plot(data, ax=ax, show=False) + assert _size(fig) == pytest.approx((6.4, 4.8)) + + +@pytest.mark.parametrize('shape', [(1, 4), (2, 2), (4, 1)]) +def test_hyp_subplots_plotly_keeps_its_default_size(shape): + pytest.importorskip('plotly') + fig, _ = hyp.subplots(*shape, backend='plotly') + assert (fig.layout.width, fig.layout.height) == (640, 480) + + +# -------------------------------------------------------------------------- +# plotly: the same rule at 100 px per inch +# -------------------------------------------------------------------------- + +@pytest.mark.parametrize('ndims', [2, 3]) +@pytest.mark.parametrize('shape, expected', SHAPES) +def test_a_bare_plotly_grid_is_sized_by_its_grid(shape, expected, ndims): + pytest.importorskip('plotly') + n = shape[0] * shape[1] + fig = hyp.plot(DATA[:n], panels=shape, ndims=ndims, backend='plotly', + show=False) + assert (fig.layout.width, fig.layout.height) == ( + round(expected[0] * 100), round(expected[1] * 100)) + + +def test_a_plotly_grid_is_as_large_as_the_matplotlib_one(): + pytest.importorskip('plotly') + for extras in ({}, dict(title=['a', 'b', 'c', 'd'])): + mpl = hyp.plot(DATA[:4], panels=(1, 4), show=False, **extras) + ply = hyp.plot(DATA[:4], panels=(1, 4), backend='plotly', + show=False, **extras) + assert (ply.layout.width, ply.layout.height) == tuple( + round(100 * v) for v in _size(mpl)) + + +def test_a_plotly_shared_legend_widens_the_grid_sized_figure(): + pytest.importorskip('plotly') + from hypertools.plot.plotly_backend import (PANEL_GUTTER_PAD_PX, + PANEL_LEGEND_PX) + fig = hyp.plot(DATA[:4], panels=(1, 4), legend=True, backend='plotly', + show=False) + assert fig.layout.width == 1280 + PANEL_LEGEND_PX + PANEL_GUTTER_PAD_PX + assert fig.layout.height == 320 + + +def test_plotly_3d_cells_are_square_and_fill_the_row(): + """Each scene of a 1 x 4 row is a square nearly the figure's height + (it was a 147 px square in a 480 px tall figure).""" + pytest.importorskip('plotly') + fig = hyp.plot(DATA[:4], panels=(1, 4), backend='plotly', show=False) + width, height = fig.layout.width, fig.layout.height + plot_w = width - fig.layout.margin.l - fig.layout.margin.r + plot_h = height - fig.layout.margin.t - fig.layout.margin.b + for key in ('scene', 'scene2', 'scene3', 'scene4'): + domain = fig.layout[key].domain + side_w = (domain.x[1] - domain.x[0]) * plot_w + side_h = (domain.y[1] - domain.y[0]) * plot_h + assert side_w == pytest.approx(side_h, abs=1.5) + assert side_h > 0.85 * height + + +@pytest.mark.parametrize('size', [(6.4, 4.8), (8, 3), (5, 9)]) +@pytest.mark.parametrize('extras', [{}, dict(legend=True)], + ids=['bare', 'legend']) +def test_plotly_explicit_size_is_honored_exactly(size, extras): + pytest.importorskip('plotly') + fig = hyp.plot(DATA[:4], panels=(1, 4), size=size, backend='plotly', + show=False, **extras) + assert (fig.layout.width, fig.layout.height) == ( + int(size[0] * 100), int(size[1] * 100)) From 5c33d679bec26679c8f23820bb11d4bc5f9c886c Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 08:07:58 -0500 Subject: [PATCH 31/58] docs: static panel grids are sized by the grid; shapes-zoo example drops its size= (GH #295) CHANGELOG (Changed: default figure size of static grids vs 1.1.0, with a table; Added and Fixed sentences corrected), docs/animation.rst, the stored output of the one static panels= cell in docs/tutorials/reduce.ipynb (re-executed), examples/plot_shapes_zoo.py (its size=(12, 6) worked around the old fixed default), and the session notes. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- CHANGELOG.md | 39 ++++++++++++++++--- docs/animation.rst | 7 +++- docs/tutorials/reduce.ipynb | 4 +- examples/plot_shapes_zoo.py | 5 ++- ...sion_2026-11-22_feat295-animated-panels.md | 31 +++++++++++++++ 5 files changed, 74 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d663a77c..4917e4eae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,8 +33,8 @@ draws into a figure the caller built, found by executing notebooks with way, at least 6.4 in wide) instead of matplotlib's fixed 6.4 x 4.8 in, so a saved clip of a row of panels is not mostly blank canvas; it is then widened by a shared legend or colorbar strip and made taller by a - caption. A static grid's default size is unchanged, except as noted for - axis labels under "Fixed". + caption. A static grid's default figure is now sized the same way (see + "Changed"). `on_frame=` is called once per frame drawn, for the whole figure (a save draws frame 0 twice: matplotlib draws it once while setting up and again as the first frame, so a callback must give the same result when @@ -147,6 +147,33 @@ draws into a figure the caller built, found by executing notebooks with works in a one-panel-per-dataset grid whose panels each hold only some of the categories (it raised "names a category this plot does not have"). + - *Default figure size.* A static `panels=`/`subplots=` grid drawn + without `size=` is now sized by its grid, as an animated one is: 3.2 in + per panel each way and at least 6.4 in wide, then widened by the shared + legend or colorbar strip and made taller by a `caption=`. In 1.1.0 + every static grid was 6.4 x 4.8 in whatever its shape, so a 1 x 4 row + of cubes was small between white bands above and below. Every static + grid drawn without `size=` therefore changes size from 1.1.0: + + | grid | 1.1.0 | now | + |-|-|-| + | 1 x 2 | 6.4 x 4.8 in | 6.4 x 3.2 in | + | 1 x 3 | 6.4 x 4.8 in | 9.6 x 3.2 in | + | 1 x 4 | 6.4 x 4.8 in | 12.8 x 3.2 in | + | 2 x 2 | 6.4 x 4.8 in | 6.4 x 6.4 in | + | 2 x 3 | 6.4 x 4.8 in | 9.6 x 6.4 in | + | 3 x 1 | 6.4 x 4.8 in | 6.4 x 9.6 in | + + The plotly grid follows the same rule at 100 px per inch (a 1 x 4 row + is 1280 x 320 px; it was 640 x 480 px). An explicit `size=` is honored + exactly as before, so `size=(6.4, 4.8)` restores the old figure. + `panels=True`/`'auto'` still chooses the grid's shape from the aspect + of `size=` or of the default 6.4 x 4.8 in figure; the default figure is + then sized by the shape chosen. A static and an animated grid of the + same call have the same default size, except with axis labels on 3-D + panels, which need more room around a rotating cube. A grid built with + `hyp.subplots()` and filled by hand keeps matplotlib's default size. + The gallery example `plot_shapes_zoo.py` no longer passes `size=`. ### Fixed @@ -172,14 +199,14 @@ draws into a figure the caller built, found by executing notebooks with layout accounts for them, so in a grid they were drawn over the next panel's cube, over the title of the panel below, over the legend, or off the canvas. A labeled panel's cube is now drawn smaller until its labels - fit its own cell; where that would leave the cubes very small the - default figure grows in the direction that limits them (a 1 x 4 grid of - labeled 3-D panels is wider than 6.4 in). An explicit `size=` is + fit its own cell; where that would leave the cubes very small (under + 65% of an unlabeled cube's size) the default figure grows in the + direction that limits them. An explicit `size=` is honored as given; where it cannot hold the labeled grid legibly, the cubes are kept at half their unlabeled size at least and one `UserWarning` names a size that works (and `xlabel='', ylabel='', zlabel=''` as the alternative). Grids without - axis labels are unchanged. + axis labels are not zoomed or enlarged by this. - **An animated title that grows after the first frame stays on the canvas.** Room for a per-frame `title=` is sized for the tallest of the first, middle and last frames' titles (it was sized for frame 0), in a diff --git a/docs/animation.rst b/docs/animation.rst index 9de1d2e20..8a8d328db 100644 --- a/docs/animation.rst +++ b/docs/animation.rst @@ -753,8 +753,11 @@ A few things are specific to a grid: way, and at least 6.4 in wide -- so a saved clip of a row of panels is not mostly blank canvas. It is then widened by the strip of a shared legend or colorbar, made taller by a ``caption=``, and enlarged for axis labels where - they need it (below). (A static grid keeps matplotlib's 6.4 x 4.8 in - default.) ``size=`` sets the whole figure's size as usual. + they need it (below). A static grid is sized the same way (since 1.2.0; it + was a fixed 6.4 x 4.8 in before), so a still and a clip of the same grid + have the same default size unless axis labels are drawn: labels swing + around a rotating cube and need more room than they do at a static grid's + one view. ``size=`` sets the whole figure's size as usual. * ``animate=`` may be given in its dictionary form (``animate={'style': 'spin', 'rotations': 2}``) exactly as for a single plot; per-dataset values inside it go to their panels, and diff --git a/docs/tutorials/reduce.ipynb b/docs/tutorials/reduce.ipynb index 896329c83..a6ec3b204 100644 --- a/docs/tutorials/reduce.ipynb +++ b/docs/tutorials/reduce.ipynb @@ -346,9 +346,9 @@ "outputs": [ { "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAA1IAAAFVCAYAAADlvN6WAAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjgsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvwVt1zgAAAAlwSFlzAAAPYQAAD2EBqD+naQAAhzRJREFUeJztnQd8FHX6xt8NNUAIIUBCR6RIR8GuYKEIKlhRPFHBXk8P/3dnO/XsJ+ed7VTsBcUuqChYsSAKNqSDgFJDCCEkJCCQ/X+eX/JbZjczuzOb3dnZ3ef7+Swhm7Y7yc47z1ue1+f3+/1CCCGEEEIIIcQ2GfY/lRBCCCGEEEIIhR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g2PqtKHcQW2jX+3D6vxscy/H7ZffetsmvdOvHv3av660l8wd8gXaiSm1deeUWuuOIKadmypSQDFFLeJdK5AOfkn2+9UWa+/Va1iNonmt42iKgAGRly5PyvA217OMePbZopf834Qx5snSMXHXmYtOsZuXU89HGpd12elWVrn3vQ/jw1eCUOsSkhQioVL9adYGWCoO23rUA7WadJD0ubv92i3uL9aL+XFekqciGyDs/OkkvatAq8KPB21Kx3JLu0RPziV9W+eMylkeQ0m8DfQfmSRa78PWzfvl1l0Pr16yeDBw+WKVOmyEUXXSSvv/66+vi3334rJ510kixdulROPvlk6d27t5SUlKiPffjhh3LiiSeq+4YPHx74GrBu3Trp3r27/Pbbb0E/D/fNmTNH/f+tt96SCRMmyBtvvCFHHXWUHHLIITJx4kT1mKwyt99995288MIL0qVLF0kGOCOVXELKOPME44hJF0+UV0eNNRVNPn/w9QYE1GmDjpb76+6WG3ObyMMH7CejO7aTg3r2VK2AdjCLu35fhlQcOdjVLgVWpNwjmSpSjE3bXY1NCbE/T9eL9XBzOXgfDnKRCG0ns5rx+bVil6rCOCXdfzfGVsDs31fLzl++V/dX6sNCm/O4kwytfW4vZL7rrrvk999/l6lTp6pj88ADDyjxBGGkWb9+vdx2221y0003SceOHSU7O1sWLFgg//d//ye33HKLHHHEEbJw4UK5+eabpWHDhkpw2WX+/PmSk5Mjzz//vFRUVMiNN94o119/vUyePNl03ug///mPJBP64oiufd4XUsaZJymvFBl2iqVhBETTqSWF8nZ2SyWy8P648mJp0/dQ9fF2UT4m01jt98uen76XPUOHuSamtDkKK/jxJ1n2SDE23eh6bHJdSMGDP10u1q12PpnN5eCIwIbb6XwTvhf2Ik0pCM6KY1/Skc2yHBtPpMLvpra7tnDMcNuTny9rAnNpuGCmzblbWVZUrr2K2wuZS0tL5b333pOnn35aevTooe6744475Oijjw76vPLyctWycNhhhwXue+655+SEE06QMWPGqPfbtWsny5cvl2effdaRkMJFBMRYs2bN1Ps33HCDjB8/XoqKiiQ3N/nnBHVFSmediX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YQQIxTeaUj//v1D/2/RokUo64TstgaZ7eHDh8vf//730HUnnXSS6eNBsL/wwgtywQUXWN4mkn79+kn37t0TeBeEEL9yzjnnyLRp01TGukmTJmF/e/7551X80LErEiQCkFy499575eabb1aZczMBDw499FBp2LB6GDzjjDNUgmHSpEly9913S+PGjVPwzggh6Q6tJsQUZIH27dtn6+gg2z1o0CAl1isqKnhECSEJMX78eNm6dasS0JE8++yz6u9WIFPerFkzufbaa2XAgAEq620X2E127txpaZ0jhJBEofAmllnsTz75RFlNMABGo0GDBvL000/LunXr5I9//COPKCEkIbACd+yxx4btDwFffPGFLF++XK2uWQGhPXbsWJUpv/jii1XmfPv27baed9GiRcqi0rp1a36ChJCUQOFNTLnlllvksssukwcffFA6dOggl19+ufz000+WR2vgwIFyww03qM1JGBxjAT+32YZOQggByGrDy11UVBSW7T755JPVhm4zEHt++eWXUEYcAn3Hjh3yyiuvWB5U7HdZuXKl/OUvfwl5wrX9hBBCkg2FNzEF2SJksX/44Qc1eE2fPl0OPvhgVQ3Airvuuku6du2qRPqePXuiHtk33nhDFixYEHYhhBCjzxtx6D//+Y/6HQL65ZdfjmozQcxCDDrooIPUSh3uf9xxx1naTRo1aiRNmzaVAw88UJ544gm1p+VPf/oTPwRCSMrgtJ7E3Ij55JNPyv33368y4BDXWAI+/vjja902MzNTVUMZMWKE3HPPPfLnP//Z8nFRmpCbKwnxPxkZ1fmdYDBo+ndcr28TWdkE4huebaymzZgxQ2WiTz/9dNPHKS8vV8IctpK8vLxaf1+8eLH06tUr7Lr58+cr4Y0KKW3btq3jOySEEPsw401s0bJlS5URAl9//bXl7U488USVkYJQX7hwIY8uIWlOq1at1E/sAYkEG7hRyq+goMD0vqjTjVU3rIjBZnL++edbVhvBqhyqkqAfwEcffRS6zJkzR222nDx5cq37YPNl3759KboJIY5B4U1ss2nTJvXTyl+peeihh1TGCRlyercJSW9OOOEEFQe0ZcQINj7CljZy5EjT+2J1DdYR9BnAZu9YNhM8DprrwF6iL3j+MWP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CCGEEAeg8CaEEEIIIcQBKLwJIYQQQghxAApvQgghhBBCHIDCmxBCCCGEEAeg8CaEEEIIIcQBKLwJIYQQQghxAApvQgghhBBCHIDCmxBCCCGEEAeg8CaEEEIIIcQBKLwJIYQQQghxAApvQgghhBBCHIDCmxBCCCGEEAeg8CaEEEIIIcQBKLwJIYQQQghxAApvQgghhBBCHIDCmxBCCCGEEAeg8CaEEEIIIcQBKLwJIYQQQghxAApvQgghhBBCHIDCmxBCCCGEEAeg8CaEEEIIIcQBKLwJIYQQQghxAApvQgghhBBCHIDCmxBCCCGEEAeg8CaEEEIIIcQBKLwJIYQQQghxAApvQgghhBBCJPX8P3m3UDW9Idh/AAAAAElFTkSuQmCC", "text/plain": [ - "
" + "
" ] }, "metadata": {}, diff --git a/examples/plot_shapes_zoo.py b/examples/plot_shapes_zoo.py index 8d060b2ba..0934c9fdc 100644 --- a/examples/plot_shapes_zoo.py +++ b/examples/plot_shapes_zoo.py @@ -27,8 +27,9 @@ # enough in scale that one shared fit would be dominated by the largest. # The biplane loads as a DataFrame with columns x, y and z, which hypertools # would write beside that one panel as axis labels; the empty labels keep -# all seven panels alike. +# all seven panels alike. No size= is needed: the figure is sized by the +# grid (3.2 in per panel each way, so 12.8 x 6.4 in here). hyp.plot([hyp.load(shape) for shape in shapes], ',', color='k', panels=(2, 4), panel_fit='independent', - title=[shape.capitalize() for shape in shapes], size=(12, 6), + title=[shape.capitalize() for shape in shapes], xlabel='', ylabel='', zlabel='') diff --git a/notes/session_2026-11-22_feat295-animated-panels.md b/notes/session_2026-11-22_feat295-animated-panels.md index 4542f789d..782ee780f 100644 --- a/notes/session_2026-11-22_feat295-animated-panels.md +++ b/notes/session_2026-11-22_feat295-animated-panels.md @@ -180,3 +180,34 @@ single-axes too (2-D figure grows upward); R11 `_wrap_shared_legend`, `FuncAnimation._init_draw` draws frame 0 before the loop (documented); R9 example text. Left open: an animated grid's figure is not enlarged for a tall title (panels shrink under it). + +## Static grids sized by the grid (owner decision 2026-11-22, for 1.2.0) + +Owner chose: static `panels=` grids get 3.2 in per panel, like animated ones; +explicit `size=` still honored. + +- `_PANEL_CELL_INCHES` (was `_ANIMATED_PANEL_CELL_INCHES`) and + `_default_panel_grid_size(nrows, ncols)` = + `(max(6.4, 3.2 * ncols), 3.2 * nrows)`; `_plot_panels_impl` uses it for + static and animated alike. The grid's shape is still chosen first + (`_auto_panel_grid` from `size=` or the 6.4 x 4.8 in aspect). +- Plotly: `make_panel_grid(default_size=)`; `_plot_panels_plotly` passes the + same inches (x 100 px), gutters/strip added as before. + `hyp.subplots()` (both backends) keeps its own default (6.4 x 4.8 in / + 640 x 480 px). +- Static vs animated default size differ only for 3-D panels WITH axis + labels (measured on 1x4, 2x2, 3x1 with titles, captions, legends, + colorbars, per-panel legends, 2-D labels: all equal). Animated: labels + swing with the cube, floor 70% (`_PANEL_LABELED_CUBE_SHARE`), cube drawn at + the animation zoom; static: one view, floor 65% + (`_STATIC_LABELED_CUBE_SHARE`). Also differs with `rotations=0`. +- New tests: tests/test_static_panel_grid_size.py. Rewritten (old default + asserted): tests/test_animated_panels.py + (`test_a_static_grid_is_sized_by_its_grid_too`), + tests/test_panel_layout_review.py. +- examples/plot_shapes_zoo.py: dropped `size=(12, 6)` (a workaround for the + old default). docs/tutorials/reduce.ipynb: the one static `panels=` cell's + stored output re-executed (scripts/execute_tutorial.py --out-dir, cell 19 + copied in). +- docs/prebuilt_gallery.json NOT touched: every static `panels=` gallery + figure changes size and needs republishing at release. From f31a022b1207cb45816b96e7d792b2aaebd0b369 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 08:09:47 -0500 Subject: [PATCH 32/58] release: version 1.2.0 (changelog heading, README image links, checklist preface, release notes draft) The 1.1.1 patch release was drafted but never tagged or uploaded; its fixes ship in 1.2.0 together with GH #295. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- CHANGELOG.md | 23 ++++++++--- RELEASE_CHECKLIST.md | 61 ++++++++++++++--------------- docs/animation.rst | 4 ++ notes/release_notes_v1.1.1_draft.md | 42 -------------------- notes/release_notes_v1.2.0_draft.md | 50 +++++++++++++++++++++++ pyproject.toml | 12 +++--- readme.md | 26 ++++++------ 7 files changed, 121 insertions(+), 97 deletions(-) delete mode 100644 notes/release_notes_v1.1.1_draft.md create mode 100644 notes/release_notes_v1.2.0_draft.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 4917e4eae..6b90c18c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,10 +1,16 @@ # Changelog -## 1.1.1 (2026-11-22) - -A patch release: three fixes for noise and side effects met when `hyp.plot` -draws into a figure the caller built, found by executing notebooks with -`jupyter nbconvert` under matplotlib 3.11. No API changes. +## 1.2.0 (2026-11-22) + +A feature release. `animate=` now works with `panels=` (one animation of the +whole grid, GH #295), `caption=` adds a figure-level caption that can change +every frame, and saved `.mp4` files start playing before they have fully +downloaded. Panel grids changed in look: each dataset keeps one color across +the figure, the grid has one legend and one colorbar, and the default figure +is sized by the grid (see "Changed"). The release also carries the fixes for +noise and side effects met when `hyp.plot` draws into a figure the caller +built (GH #290, #291, #292), first drafted as a 1.1.1 patch release that was +never published. ### Added @@ -67,6 +73,13 @@ draws into a figure the caller built, found by executing notebooks with Matplotlib only: `backend='plotly'` raises `NotImplementedError`, and a caller-supplied `ax=` raises `ValueError`. +- **Saved `.mp4`, `.m4v` and `.mov` animations are written "fast start" + (GH #295).** The file's index is placed before the media data + (`-movflags +faststart`), so a browser starts playing a saved clip while it + is still downloading instead of fetching the whole file first. This applies + to `save_path=`, `HyperAnimation.save`, the streaming recorder and the + plotly export; `.avi` and `.mkv` files are unchanged. + ### Changed - **Panel grids share their colors, one legend and one colorbar.** In a diff --git a/RELEASE_CHECKLIST.md b/RELEASE_CHECKLIST.md index c8bb14746..3de6a9453 100644 --- a/RELEASE_CHECKLIST.md +++ b/RELEASE_CHECKLIST.md @@ -1,42 +1,41 @@ # HyperTools 1.1 release checklist -## The 1.1.1 patch release: read this first +## The 1.2.0 release: read this first -`pyproject.toml` and `CHANGELOG.md` declare **1.1.1** (fixes for GH #290, -#291 and #292; no API changes). The steps below were written for 1.1.0 and -keep its history. For 1.1.1, follow the same steps in the same order and read -`1.1.1` for `1.1.0` (and `v1.1.1` for `v1.1.0`) in every command, with these +`pyproject.toml` and `CHANGELOG.md` declare **1.2.0** (GH #295: animated +panel grids, `caption=`, fast-start mp4; panel grids with shared colors, one +legend, one colorbar and a figure sized by the grid; and the fixes for GH +#290, #291 and #292, first drafted as a 1.1.1 patch release that was never +tagged or uploaded). The steps below were written for 1.1.0 and keep its +history. For 1.2.0, follow the same steps in the same order and read `1.2.0` +for `1.1.0` (and `v1.2.0` for `v1.1.0`) in every command, with these differences: -- **Nothing is in release form yet.** The 1.1.1 pull request changes code, - tests, the changelog, the version, this checklist and a session note, - and nothing that puts the repository in release form. `readme.md` still pins its - images to the `v1.1.0` tag (the `v1.1.1` tag does not exist until step 5, - so flipping earlier would break the images), and - `docs/prebuilt_gallery.json` still records the 1.1.0 gallery. Until step 2 - is done on `master`, the `release-gate` job fails there on those two - checks and on the gallery manifest; that is the expected state between - the merge and the release. -- **Step 2, README:** this time it is a real flip, not a verify-only step: - `sed -E -i '' 's#(/ContextLab/hypertools/)[^/]+(/images/)#\1v1.1.1\2#g' readme.md`, - then `grep -c '/ContextLab/hypertools/v1.1.1/images/' readme.md` → 13. -- **Step 2, CHANGELOG date:** the `## 1.1.1 (YYYY-MM-DD)` heading must not be +- **The release commit is pushed to `master` by fast-forward**, never by a + merge commit: the gallery record and the notebook manifest pin the exact + commit, and a merge commit would be a different one. +- **Step 2, README:** the image links name the `v1.2.0` tag: + `grep -c '/ContextLab/hypertools/v1.2.0/images/' readme.md` → 13. The tag + does not exist until step 5, so the images do not resolve before it. +- **Step 2, CHANGELOG date:** the `## 1.2.0 (YYYY-MM-DD)` heading must not be earlier than the release commit's date. -- **Step 2, galleries:** `docs-notebooks/v1.1.1/` and the - `docs-gallery-v1.1.1` branch do not exist yet; the two publish scripts - create them (`publish_gallery_notebooks.py --ref v1.1.1`; - `publish_prebuilt_gallery.py` takes the version from `pyproject.toml`). - The generated gallery notebooks install - `hypertools[interactive]>=1.1.1` (`docs/conf.py` reads the package - version), so they cannot be run on Colab until the PyPI upload. The +- **Step 2, galleries:** `publish_gallery_notebooks.py --ref v1.2.0` creates + `docs-notebooks/v1.2.0/`; `publish_prebuilt_gallery.py` takes the version + from `pyproject.toml` and creates the `docs-gallery-v1.2.0` branch. Run + `scripts/add_colab_install_cell.py` on the `master` branch only (on another + branch it retargets the tutorials to that branch). The generated gallery + notebooks install `hypertools[interactive]>=1.2.0` (`docs/conf.py` reads the + package version), so they cannot be run on Colab until the PyPI upload. The committed tutorials keep their `>=1.1.0` floor. - **Step 5, tag:** there is no draft tag to move. Create it: - `git tag -a v1.1.1 -m "HyperTools 1.1.1" ` and - `git push origin refs/tags/v1.1.1` (no `--force`). -- **Step 6, GitHub Release:** there is no draft release. Create one for - `v1.1.1` from the `## 1.1.1` section of `CHANGELOG.md` and attach the - step-3 wheel and sdist. -- **Step 6, Read the Docs:** point "stable" at `v1.1.1`, replacing `v1.1.0`. + `git tag -a v1.2.0 -m "HyperTools 1.2.0" ` and + `git push origin refs/tags/v1.2.0` (no `--force`). +- **Step 6, GitHub Release:** a draft release for `v1.2.0` (no tag yet) + carries the step-3 wheel and sdist; set its tag and publish it. +- **Step 6, Read the Docs:** point "stable" at `v1.2.0`, replacing `v1.1.0`. +- **Leftovers of the 1.1.1 draft** (never released): the draft GitHub release + "HyperTools 1.1.1", the `release/1.1.1` branch, the `docs-gallery-v1.1.1` + branch and `docs-notebooks/v1.1.1/` can be deleted once 1.2.0 is out. The docs, notebooks, and README ship in **release form** on `master` (the 1.1.0 draft: `master` == tag `v1.1.0` == `96ac8b7f`, gallery published under diff --git a/docs/animation.rst b/docs/animation.rst index 8a8d328db..ad4695760 100644 --- a/docs/animation.rst +++ b/docs/animation.rst @@ -728,6 +728,8 @@ about what a morph means, not a gap to be filled later. Animated panel grids -------------------- +.. versionadded:: 1.2.0 + ``panels=`` (alias ``subplots=``) draws one panel per dataset, and with ``animate=`` the whole grid is ONE animation (matplotlib only): every panel runs on the same clock, and a single ``HyperAnimation`` is returned for the @@ -811,6 +813,8 @@ A few things are specific to a grid: Captions -------- +.. versionadded:: 1.2.0 + ``caption=`` (matplotlib only) draws one line of text centered under the figure -- under a single plot, or under a whole ``panels=`` grid -- and updates it on every frame. It takes the forms a per-frame ``title=`` takes: diff --git a/notes/release_notes_v1.1.1_draft.md b/notes/release_notes_v1.1.1_draft.md deleted file mode 100644 index 24897412d..000000000 --- a/notes/release_notes_v1.1.1_draft.md +++ /dev/null @@ -1,42 +0,0 @@ -# HyperTools 1.1.1 - -A patch release with no API changes. It fixes noise and side effects met when `hyp.plot` draws into a figure the caller built (`ax=`), found by executing notebooks with `jupyter nbconvert` under matplotlib 3.11, and one misleading error message from the Yahoo Finance loader. - -Every change is listed in the [changelog](https://github.com/ContextLab/hypertools/blob/v1.1.1/CHANGELOG.md); these notes summarize it. - -## Install - -```bash -pip install --upgrade hypertools -``` - -Python 3.10 through 3.13. Extras are unchanged from 1.1.0. - -## Fixed - -- **The backend warning is issued once, and only when it applies ([#290](https://github.com/ContextLab/hypertools/issues/290)).** When hypertools cannot set up an interactive matplotlib backend at import (for example in a notebook kernel without `ipympl`), `hyp.plot` repeated the warning on every call, including static plots and calls that show no live figure. It is now issued only by a call that displays an animated or interactive plot that matplotlib renders, and once per session per message. -- **`hyp.plot(..., ax=ax)` leaves the layout of the caller's figure alone ([#291](https://github.com/ContextLab/hypertools/issues/291)).** Static plots ended with `plt.tight_layout()` even when the caller passed its own axes, which moved every axes of the figure, discarded `subplots_adjust` margins, replaced a `layout='constrained'` engine, and acted on pyplot's current figure rather than the one that owns `ax`. A figure the caller built is now left as the caller arranged it. Figures hypertools makes itself (its own figure, a `panels=` grid, a `hyp.subplots` grid) are laid out as before. -- **A legend or title added to the caller's axes is fitted automatically, inside that axes' own room.** Through 1.1.0 a `legend=` beside a caller's axes was fitted by widening the caller's figure, which stretched its other axes and switched off its layout engine. Now, when the figure is drawn, only the axes passed as `ax=` is narrowed just far enough that its legend ends before the canvas edge or the next panel, and lowered just far enough that its title stays on the canvas. No call is needed, and the fit follows a later `fig.tight_layout()`, `fig.subplots_adjust(...)`, resize or save. A legend with no room beside the axes is drawn inside it; one too large for its panel either way is left in place with a `UserWarning` naming the remedies. -- **No `findfont` log lines for ordinary text under matplotlib 3.11 ([#292](https://github.com/ContextLab/hypertools/issues/292)).** matplotlib 3.11 logs a line each time a family in the font list has no face at a text's exact weight; one of the fallback families hypertools listed has no regular face on macOS, so every figure logged the line several times. Fallback families with no regular-weight face are now left out of the list. -- **A Yahoo Finance rate limit is reported as one.** `hyp.load('yahoo:')` reported an HTTP 429 from Yahoo as a JSON decoding failure. The error now says that Yahoo is rate-limiting the address and to try again later. -- **A seeded UMAP no longer warns about `n_jobs`.** A seed passed in the `reduce` dict (`reduce={'model': 'UMAP', 'kwargs': {'random_state': 0}}`) drew umap-learn's "n_jobs value 1 overridden to 1" warning; it is now quiet, like the top-level `random_state=`. - -## Documentation - -- Two gallery examples (`plot_colorbar.py`, `plot_digits.py`) are now seeded, so their figures are the same on every docs build, and `plot_shapes_zoo.py` no longer shows stray axis labels beside one panel. - -## Upgrading from 1.1.0 - -- **If you relied on the automatic `tight_layout`** of a figure made with `plt.subplots`, call `fig.tight_layout()` after plotting, create the figure with `layout='constrained'`, or build the grid with `hyp.subplots`. -- On an axes whose legend or title was fitted, `ax.get_position()` reports the position of the last draw (the fit is an axes locator, recomputed on each draw). - -## Known limitations - -- The automatic fit does not detect an inset or other axes placed by hand where the legend goes, or a legend over the tick labels of its own axes' twin. -- Bold or other non-regular text can still log `findfont` lines under matplotlib 3.11 when an installed fallback family ships a regular face only; see "Documented limitations" in the changelog. - -## Links - -- Documentation: https://hypertools.readthedocs.io/en/stable/ -- Changelog: https://github.com/ContextLab/hypertools/blob/v1.1.1/CHANGELOG.md -- PyPI: https://pypi.org/project/hypertools/1.1.1/ diff --git a/notes/release_notes_v1.2.0_draft.md b/notes/release_notes_v1.2.0_draft.md new file mode 100644 index 000000000..aac2bef7f --- /dev/null +++ b/notes/release_notes_v1.2.0_draft.md @@ -0,0 +1,50 @@ +# HyperTools 1.2.0 + +A feature release: animated panel grids, a per-frame caption, and panel grids whose colors, legend and colorbar are shared across the figure. It also carries the fixes for noise and side effects met when `hyp.plot` draws into a figure the caller built. + +Every change is listed in the [changelog](https://github.com/ContextLab/hypertools/blob/v1.2.0/CHANGELOG.md); these notes summarize it. + +## Install + +```bash +pip install --upgrade hypertools +``` + +Python 3.10 through 3.13. Extras are unchanged from 1.1.0. + +## Added + +- **Animated panel grids ([#295](https://github.com/ContextLab/hypertools/issues/295)).** `hyp.plot([a, b, c, d], panels=(1, 4), animate=True, save_path='grid.mp4')` gives one animation of the whole grid: every panel runs on the same clock, each panel is animated as the single-axes call for its data is, and one `HyperAnimation` is returned for the figure. The combination used to raise `ValueError`. Animated grids are drawn with matplotlib. +- **`caption=`.** One line of text under a plot or a grid, given as a string, a `'{index}'` pattern or a function of the frame, for example `caption=lambda ctx: f'timepoint {ctx.frame + 1} of {ctx.n_frames}'`. It is updated on every frame of an animation, wrapped to the figure's width, and drawn once on a static plot. +- **Fast-start video files.** Saved `.mp4`, `.m4v` and `.mov` files start playing in a browser before the whole file has downloaded. + +## Changed + +- **Panel grids share their colors, one legend and one colorbar.** In a `panels=` grid each dataset is drawn in the color it has in the single-axes plot of all the datasets, `hue=` uses one scale (or one label-to-color mapping) for the whole figure, and the grid shows one legend and one colorbar beside the panels instead of one per panel. Legends stay per panel only where the colors mean different things in each panel (for example clusters fit separately per panel). +- **A panel grid's default figure is sized by the grid:** 3.2 in per panel each way, at least 6.4 in wide, instead of a fixed 6.4 x 4.8 in. `size=` is honored as before, and `hyp.subplots()` keeps its default. + +## Fixed + +- **The backend warning is issued once, and only when it applies ([#290](https://github.com/ContextLab/hypertools/issues/290)).** +- **`hyp.plot(..., ax=ax)` leaves the layout of the caller's figure alone ([#291](https://github.com/ContextLab/hypertools/issues/291)).** A legend or title added to the caller's axes is fitted inside that axes' own room, automatically, on every draw. +- **No `findfont` log lines for ordinary text under matplotlib 3.11 ([#292](https://github.com/ContextLab/hypertools/issues/292)).** +- **A Yahoo Finance rate limit is reported as one.** +- **A seeded UMAP no longer warns about `n_jobs`.** +- **A `legend=` list names the categories of a categorical `hue=` on line plots too,** as it already did for markers. + +## Upgrading from 1.1.0 + +- **Static `panels=` figures look different:** per-dataset colors, one shared legend and colorbar, and a figure sized by the grid. Pass `size=` to set the figure size yourself. +- **If you relied on the automatic `tight_layout`** of a figure made with `plt.subplots` and drawn into with `ax=`, call `fig.tight_layout()` after plotting, create the figure with `layout='constrained'`, or build the grid with `hyp.subplots`. +- On a single line plot with a categorical `hue=`, `legend=[...]` now takes one name per category (it took one per drawn run). + +## Known limitations + +- Animated panel grids and `caption=` are matplotlib-only; with `backend='plotly'` they raise `NotImplementedError`. Static plotly grids are supported. +- The automatic legend fit on a caller's axes does not detect an inset or other axes placed by hand where the legend goes. + +## Links + +- Documentation: https://hypertools.readthedocs.io/en/stable/ +- Changelog: https://github.com/ContextLab/hypertools/blob/v1.2.0/CHANGELOG.md +- PyPI: https://pypi.org/project/hypertools/1.2.0/ diff --git a/pyproject.toml b/pyproject.toml index 8dbaf0469..a3843ff79 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,13 +5,13 @@ build-backend = "setuptools.build_meta" [project] name = "hypertools" -# the 1.1 line: this branch's unreleased work now includes the hierarchy -# features AND seven rejections of previously-accepted input (CHANGELOG 1.1.0, -# "Changed / validation"), which cannot ship as a patch release. 1.1.1 is a -# patch release on that line: fixes only (CHANGELOG 1.1.1). The version -# and the top CHANGELOG heading are held equal by +# 1.2.0 is a feature release on the 1.x line: animated panel grids, +# `caption=`, and panel grids that share colors, one legend and one colorbar +# and are sized by the grid (CHANGELOG 1.2.0, "Added" and "Changed"), plus the +# fixes first drafted as a 1.1.1 patch release that was never published. The +# version and the top CHANGELOG heading are held equal by # tests/test_release_readiness_gate.py::test_changelog_top_version_matches_pyproject. -version = "1.1.1" +version = "1.2.0" description = "A python package for visualizing and manipulating high-dimensional data" readme = "readme.md" # PEP 639 SPDX expression (the `license = { text = ... }` table form is diff --git a/readme.md b/readme.md index c0bea7f7c..38b4e9f2e 100644 --- a/readme.md +++ b/readme.md @@ -1,4 +1,4 @@ -![Hypertools logo](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/hypercube.png) +![Hypertools logo](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/hypercube.png) [![Tests](https://img.shields.io/github/actions/workflow/status/ContextLab/hypertools/test.yml?label=tests)](https://github.com/ContextLab/hypertools/actions/workflows/test.yml) [![Documentation Status](https://readthedocs.org/projects/hypertools/badge/?version=latest)](https://hypertools.readthedocs.io/en/latest/?badge=latest) @@ -7,7 +7,7 @@ "_To deal with hyper-planes in a 14 dimensional space, visualize a 3D space and say 'fourteen' very loudly. Everyone does it._" - Geoff Hinton -![Hypertools example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/story_trajectories.gif) +![Hypertools example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/story_trajectories.gif) ## Overview @@ -52,7 +52,7 @@ the link under a clip for the full code and the full-length animation. Six stock-market sectors, each reduced to 3-D on its own and then hyperaligned into a shared space, with a heavier path for the market as a whole. -![Market sectors example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/tour_market_sectors.gif) +![Market sectors example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/tour_market_sectors.gif) [Tutorial: market sectors](https://hypertools.readthedocs.io/en/latest/tutorials/market_sectors.html) @@ -62,7 +62,7 @@ Give `hyp.plot` a list of strings and it embeds them, projects them into 2-D or 3-D, and plots the result. Here a paragraph about each of five paintings becomes its own cloud, drawn in a color pulled from the canvas itself. -![Painting embeddings example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/tour_painting_embeddings.gif) +![Painting embeddings example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/tour_painting_embeddings.gif) [Tutorial: painting embeddings](https://hypertools.readthedocs.io/en/latest/tutorials/painting_embeddings.html) @@ -72,7 +72,7 @@ becomes its own cloud, drawn in a color pulled from the canvas itself. Tea-Party from *Alice's Adventures in Wonderland*: each segment is one turn of the conversation, colored by speaker and placed by what is being said. -![Conversation example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/tour_conversation_shape.gif) +![Conversation example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/tour_conversation_shape.gif) [Tutorial: the shape of a conversation](https://hypertools.readthedocs.io/en/latest/tutorials/conversation_shape.html) @@ -81,7 +81,7 @@ the conversation, colored by speaker and placed by what is being said. Monthly temperatures in 20 cities around the globe, from 1875 to 2013, drawn as a single path and colored by the average temperature that month. -![Weather example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/tour_weather_decades.gif) +![Weather example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/tour_weather_decades.gif) [Tutorial: weather across the decades](https://hypertools.readthedocs.io/en/latest/tutorials/weather_decades.html) @@ -97,7 +97,7 @@ shapes = [hyp.load(n) for n in names] hyp.plot(shapes, '.', color='k', animate='morph', title=names) ``` -![Morph example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/tour_morph_shapes_zoo.gif) +![Morph example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/tour_morph_shapes_zoo.gif) [Tutorial: morphing the shapes zoo](https://hypertools.readthedocs.io/en/latest/tutorials/morph_shapes_zoo.html) @@ -256,7 +256,7 @@ list_of_labels = ['A'] * 300 + ['B'] * 300 # one label per observation hyp.plot(list_of_arrays, animate=True, hue=list_of_labels) ``` -![Plot example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/plot.gif) +![Plot example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/plot.gif) ## Align @@ -275,11 +275,11 @@ hyp.plot(list_of_arrays, align='hyper') ### BEFORE -![Align before example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/align_before.gif) +![Align before example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/align_before.gif) ### AFTER -![Align after example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/align_after.gif) +![Align after example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/align_after.gif) ## Cluster @@ -299,7 +299,7 @@ array = np.vstack([rng.standard_normal((100, 3)) + offset hyp.plot(array, 'o', cluster='GaussianMixture', n_clusters=3) ``` -![Cluster Example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/cluster_example.png) +![Cluster Example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/cluster_example.png) ## Surfaces @@ -317,7 +317,7 @@ blob_b = rng.standard_normal((100, 3)) + [4, 0, 0] hyp.plot([blob_a, blob_b], '.', surface=True) ``` -![Surface Example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/surface_example.png) +![Surface Example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/surface_example.png) ## Describe @@ -332,4 +332,4 @@ list_of_arrays = [np.cumsum(rng.standard_normal((200, 20)), axis=0) hyp.describe(list_of_arrays, reduce='PCA', max_dims=14) ``` -![Describe Example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.1.1/images/describe_example.png) +![Describe Example](https://raw.githubusercontent.com/ContextLab/hypertools/v1.2.0/images/describe_example.png) From 2597fd1338dc4edd01c97592311c24972e845906 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 08:39:16 -0500 Subject: [PATCH 33/58] test: the per-point color spy forwards whatever arguments the call passes The pass-through wrapper pinned _multicolor_line_colors' signature, so it broke when the function gained a keyword (warn_non_finite); the assertion is unchanged. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- tests/test_animation_hue.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/test_animation_hue.py b/tests/test_animation_hue.py index 81c47d4bc..3f9f9708c 100644 --- a/tests/test_animation_hue.py +++ b/tests/test_animation_hue.py @@ -45,8 +45,10 @@ def test_animate_hue_uses_per_point_colors(): captured = {} orig = plot_mod._multicolor_line_colors - def _spy(hue_src, orig_lengths, xform, palette, is_rgb=False): - res = orig(hue_src, orig_lengths, xform, palette, is_rgb=is_rgb) + def _spy(*args, **kwargs): + # a pass-through recorder: forwards whatever the call passes, so it + # does not pin the helper's signature + res = orig(*args, **kwargs) captured['colors'] = res return res From 8d8d3e012d36a75e475047de9f2fde12b2b8ffce Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 09:01:30 -0500 Subject: [PATCH 34/58] feat: shared axis labels on a panel grid's outer panels only; one layout path for static and animated grids (GH #295) Owner decision 2026-11-22, for 1.2.0. - `_outer_label_panels` is the one decision function: a label that is the same in every occupied panel of a column (x; in 3-D x and y) is drawn under the column's lowest panel, one that is the same along a row (y in 2-D, z in 3-D) on one panel of the row; labels that differ are all kept. matplotlib static and animated grids apply it through `_apply_outer_labels`, the plotly grid through `_apply_outer_labels_plotly`. - 3-D z label: on the panel at the end of the row matplotlib draws it toward (measured, `_z_label_side`); plotly writes first-column z titles in the left margin (a scene's own z title was clipped in a grid cell). - One layout: `_tighten_panel_grid` + `_lay_out_panel_grid` for static and animated grids; one 70% labeled-cube floor; every cube starts at matplotlib's default box zoom, so a static grid and the same grid animated with rotations=0 have the same figure size, axes positions and cubes. `_fit_static_cube_labels` and `_STATIC_LABELED_CUBE_SHARE` removed. - Seen from one view, outer 3-D labels hang toward the grid's outer edge and the default figure grows there (`_open_label_sides`, `_outer_label_margins`); every cube of a grid is drawn the same size. - Fixes met on the way: overlapping 3-D panel boxes after tight_layout in labeled grids; `panel_fit='independent'` grids of DataFrames with different column names were refused by the grid color resolution. - Tests: tests/test_panel_outer_labels.py (new); tests that asserted labels on every panel rewritten, each marked "CHANGED for 1.2.0". - Docs: plot() docstring, docs/animation.rst, CHANGELOG, session notes. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- CHANGELOG.md | 58 +- docs/animation.rst | 34 +- hypertools/plot/matplotlib_backend.py | 12 +- hypertools/plot/plot.py | 773 +++++++++++++---- ...sion_2026-11-22_feat295-animated-panels.md | 75 ++ tests/test_animated_panels.py | 17 +- tests/test_panel_layout_review.py | 7 +- tests/test_panel_outer_labels.py | 810 ++++++++++++++++++ tests/test_panels_shared_legend_colors.py | 7 +- tests/test_plot_panels.py | 6 +- tests/test_plot_panels_fit.py | 28 +- tests/test_static_panel_grid_size.py | 11 +- 12 files changed, 1632 insertions(+), 206 deletions(-) create mode 100644 tests/test_panel_outer_labels.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b90c18c5..c530c2466 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -182,11 +182,44 @@ never published. exactly as before, so `size=(6.4, 4.8)` restores the old figure. `panels=True`/`'auto'` still chooses the grid's shape from the aspect of `size=` or of the default 6.4 x 4.8 in figure; the default figure is - then sized by the shape chosen. A static and an animated grid of the - same call have the same default size, except with axis labels on 3-D - panels, which need more room around a rotating cube. A grid built with + then sized by the shape chosen. A grid built with `hyp.subplots()` and filled by hand keeps matplotlib's default size. The gallery example `plot_shapes_zoo.py` no longer passes `size=`. + - *Shared axis labels on the outer panels only.* An axis label + (`xlabel=`/`ylabel=`/`zlabel=`, or the one taken from a DataFrame's + column or index name) that is the same in every panel of a column or + row is drawn once instead of on every panel, on both backends, static + or animated. A label along the bottom of a panel (x in 2-D and + `ndims=1` panels; x and y, the floor axes, in 3-D) goes under the + lowest panel of each column; a label up the side of a panel (y in 2-D, + z in 3-D) goes on one panel of each row: the left-most in 2-D, and in + 3-D the panel at the end of the row the z label is drawn toward + (matplotlib: the right-most at the default view; plotly: the + left-most). Where the labels of a column or row differ, every panel of + it keeps its own; spare cells count for nothing, so a panel above an + empty cell draws the x label; tick labels (`axis_scale='data'`) stay + on every panel. In 1.1.0 every panel drew every label. The room of the + labels no longer drawn goes back to the panels: 2-D panels are laid + out closer and larger, and a 3-D grid seen from one view (static, or + animated with `rotations=0`) lets its outer panels' labels hang toward + the grid's outer edge, where the default figure is given a little room + for them, so its cubes keep nearly their unlabeled size (they were + drawn at 65-70% of it). A rotating grid's labels still swing through + every side of their cube and are kept inside their own cells, as + before. On plotly, the z titles of a 3-D grid's first column are + written in the left margin (a scene's own z title falls outside a + grid cell and was clipped away on every panel). + - *One layout for static and animated grids.* A static grid and the + same grid animated with `rotations=0` now have the same figure size, + the same panel positions and the same cubes; a rotating grid differs + only by the room its cubes' sweep needs. A grid's cubes are drawn at + the size a static panel's always was (matplotlib's default box zoom, + scaled by an animation's `zoom=`) and zoomed out only as far as their + cell requires; every cube of a grid is drawn the same size, labeled or + not; and the default figure of a labeled 3-D grid grows where its + cubes would be under 70% of their unlabeled size, static or animated. + An explicit `size=` too small for a labeled 3-D grid still raises for + an animated grid and warns for a static one. ### Fixed @@ -211,15 +244,28 @@ never published. panel.** matplotlib hangs a 3-D axes' labels outside its cube, where no layout accounts for them, so in a grid they were drawn over the next panel's cube, over the title of the panel below, over the legend, or off - the canvas. A labeled panel's cube is now drawn smaller until its labels - fit its own cell; where that would leave the cubes very small (under - 65% of an unlabeled cube's size) the default figure grows in the + the canvas. The labels are now kept clear of every other panel, the + legend and the caption: at the grid's outer edges the default figure is + given room for them, and a label drawn on an inner panel has its cube + (and with it every cube of the grid) drawn smaller until it fits its own + cell; where that would leave the cubes very small (under + 70% of an unlabeled cube's size) the default figure grows in the direction that limits them. An explicit `size=` is honored as given; where it cannot hold the labeled grid legibly, the cubes are kept at half their unlabeled size at least and one `UserWarning` names a size that works (and `xlabel='', ylabel='', zlabel=''` as the alternative). Grids without axis labels are not zoomed or enlarged by this. +- **A `panels=` grid of DataFrames with different column names is drawn + with `panel_fit='independent'`.** Each panel then fits its own features, + but the grid's color resolution stacked the frames by column name and + refused them ("DataFrame columns do not match across datasets"); it now + resolves the colors on the bare rows. (With the default shared fit such + a list is still refused, as on one axes: features are matched by name.) +- **3-D panels of a labeled grid no longer overlap.** `tight_layout` + measures a 3-D axes that draws axis labels by its cube alone and closed + the gaps between such panels past zero, so one panel's square, and the + labels fitted inside it, reached into the next panel's. - **An animated title that grows after the first frame stays on the canvas.** Room for a per-frame `title=` is sized for the tallest of the first, middle and last frames' titles (it was sized for frame 0), in a diff --git a/docs/animation.rst b/docs/animation.rst index ad4695760..852bccfbc 100644 --- a/docs/animation.rst +++ b/docs/animation.rst @@ -754,12 +754,16 @@ A few things are specific to a grid: * Without ``size=`` the figure is sized by the grid -- 3.2 in per panel each way, and at least 6.4 in wide -- so a saved clip of a row of panels is not mostly blank canvas. It is then widened by the strip of a shared legend or - colorbar, made taller by a ``caption=``, and enlarged for axis labels where - they need it (below). A static grid is sized the same way (since 1.2.0; it - was a fixed 6.4 x 4.8 in before), so a still and a clip of the same grid - have the same default size unless axis labels are drawn: labels swing - around a rotating cube and need more room than they do at a static grid's - one view. ``size=`` sets the whole figure's size as usual. + colorbar, made taller by a ``caption=``, and given room for axis labels where + they need it (below). A static grid is laid out by the same code (since + 1.2.0; it was a fixed 6.4 x 4.8 in before): a still and a clip of the same + grid animated with ``rotations=0`` have the same figure size, panel + positions and cubes, and a rotating grid differs only by the room its + cubes' sweep needs. ``size=`` sets the whole figure's size as usual. +* Shared axis labels are drawn on the outer panels only, as in a static + grid: a label that is the same in every panel of a column is drawn under + the column's lowest panel, one that is the same along a row on one panel + of the row (see ``panels=`` in :func:`hypertools.plot`). * ``animate=`` may be given in its dictionary form (``animate={'style': 'spin', 'rotations': 2}``) exactly as for a single plot; per-dataset values inside it go to their panels, and @@ -767,14 +771,18 @@ A few things are specific to a grid: * Every panel must draw the same number of frames, or the call raises ``ValueError`` (``animate='morph'`` needs the same number of datasets in each panel). -* Each 3-D panel's cube is zoomed out as far as it takes to stay inside its +* Each 3-D panel's cube starts at the size a static panel's is drawn at + (scaled by ``zoom=``) and is zoomed out as far as it takes to stay inside its own cell through the whole rotation, so ``zoom=`` can shrink a panel's - cube but not enlarge it past its cell. With axis labels (``xlabel=``/ - ``ylabel=``/``zlabel=``, or a DataFrame's column names) the cube is drawn - smaller still, so the labels stay inside the panel's own cell at every - view the animation takes (the whole turn, or the one view of - ``rotations=0``). The figure is enlarged only where that would leave a - cube under 70% of an unlabeled one's size, and by no more than restores + cube but not enlarge it past its cell. The axis labels a panel draws + (``xlabel=``/``ylabel=``/``zlabel=``, or a DataFrame's column names) swing + around its cube, so the cubes are drawn smaller still -- all of them + alike -- until the labels stay inside the panel's own cell at every view + the animation takes. With ``rotations=0`` there is one view: the outer + panels' labels hang toward the grid's outer edge, the figure is given + room for them there, and the cubes keep nearly their unlabeled size. The + figure is enlarged only where the cubes would be under 70% of their + unlabeled size, and by no more than restores that. An explicit ``size=`` is honored down to cubes half their unlabeled size and raises below that, naming a size that works; pass ``xlabel='', ylabel='', zlabel=''`` to drop the labels instead. * A per-frame ``title=`` (a callable or an ``'{index...}'`` pattern, one for diff --git a/hypertools/plot/matplotlib_backend.py b/hypertools/plot/matplotlib_backend.py index 3c5d3409b..1ad66613d 100644 --- a/hypertools/plot/matplotlib_backend.py +++ b/hypertools/plot/matplotlib_backend.py @@ -725,9 +725,19 @@ class PanelAnimationStub: `zoom_scale` is the panel's handle on its own 3-D camera zoom: the grid lowers ``zoom_scale[0]`` until the panel's rotating cube fits its cell - (`plot._fit_panel_cubes`). + (`plot._fit_panel_cubes`), starting from `start_scale`. """ + #: the ``zoom_scale`` the grid's cube fit starts from: the one that + #: undoes the extra box zoom a single animated plot is drawn with + #: (`_anim_box_zoom`, 1.125 at the default ``zoom=1``; it fills a whole + #: canvas), so a panel at the default `zoom=` starts at matplotlib's + #: default box zoom -- the size a STATIC grid's cube is drawn at. A + #: static grid and the same grid animated with ``rotations=0`` then + #: draw the same cubes, and `zoom=` still scales a panel's cube + #: relative to that. + start_scale = 1.0 / _anim_box_zoom(1) + def __init__(self, func, args, n_frames, interval, zoom_scale=None): self._func = func self._args = tuple(args) diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index b2d0edcbb..bbe6b7869 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -5543,17 +5543,7 @@ def _finish(cbar): # the panel's own box afterwards -- `_fit_panel_cubes` -- so nothing # of an outer column reaches into a strip) fig.set_size_inches(grid_w, grid_h) - with warnings.catch_warnings(): - # the colorbar's axes is placed by hand (below), which - # `tight_layout` reports as an axes it cannot lay out - warnings.filterwarnings( - 'ignore', message='This figure includes Axes that are not ' - 'compatible with tight_layout') - # the panels were last laid out around their own legends, which - # are gone: one pass from there under-reserves a 3-D panel's - # title room (its box is aspect-constrained), a second settles it - for _ in range(3): - fig.tight_layout() + _tighten_panel_grid(fig) if not widen: # an explicit size too small for the strips: they keep their size # and the grid the 30% floor above @@ -5711,6 +5701,222 @@ def _place_shared_furniture(fig, strip): _SHARED_COLORBAR_WIDTH_IN / width_in, height]) +#: which line of a grid shares each axis label (`_outer_label_panels`): a +#: label that runs along the BOTTOM of a panel is shared down a column, one +#: that runs up its SIDE is shared along a row. In 3-D both floor axes (x +#: and y) are drawn under the cube and z up its side. +_LABEL_SHARED_ALONG = { + 2: {'x': 'column', 'y': 'row'}, + 3: {'x': 'column', 'y': 'column', 'z': 'row'}, +} + +#: the end of a row a plotly 3-D grid's shared z title is drawn at: at +#: hypertools' default camera plotly writes a scene's z title at the cube's +#: left edge (matplotlib's side is measured, `_z_label_side`; a plotly +#: scene's is decided in the browser and cannot be) +_PLOTLY_Z_LABEL_SIDE = 'left' + + +def _outer_label_panels(labels, nrows, ncols, ndims=2, z_side='right'): + """Which axis labels each panel of a `panels=` grid DRAWS: shared + labels go on the outer panels only (owner decision, 1.2.0). The one + decision function of every grid -- static and animated matplotlib + grids (`_apply_outer_labels`) and the plotly grid + (`_plot_panels_plotly`). + + `labels` holds, per occupied panel in row-major order, that panel's + ``{'x': text, 'y': text, 'z': text}`` (a missing key, None and ``''`` + all mean "no label"). Spare cells of the ``nrows x ncols`` grid are not + listed and count for nothing. Returns, per panel, the set of axis + names whose label it draws: + + - a label shared down a COLUMN (`_LABEL_SHARED_ALONG`: x; in 3-D also + y) is drawn by the lowest occupied panel of that column, when every + occupied panel of the column has the same text for it; + - a label shared along a ROW (y in 2-D, z in 3-D) is drawn by one + panel of that row, when every occupied panel of the row has the same + text for it: the left-most one, or for a 3-D grid's z label the + panel at the `z_side` end of the row (``'right'``: the right-most + occupied panel), which is the side of the cube the z label is drawn + on, so the label sits at the grid's outer edge; + - where the texts of a column (or row) differ -- including a panel + with no label beside labeled ones -- every panel of it keeps its + own. + """ + n = len(labels) + drawn = [set() for _ in range(n)] + + def _text(i, name): + value = labels[i].get(name) + return '' if value is None else str(value) + + columns = [[i for i in range(n) if i % ncols == col] + for col in range(ncols)] + rows = [[i for i in range(n) if i // ncols == row] + for row in range(nrows)] + for name, along in _LABEL_SHARED_ALONG[3 if ndims >= 3 else 2].items(): + for members in (columns if along == 'column' else rows): + if not members: + continue + texts = {_text(i, name) for i in members} + if len(texts) > 1: + keepers = [i for i in members if _text(i, name)] + elif not texts.pop(): + keepers = [] + elif along == 'column': + keepers = [members[-1]] + else: + keepers = [members[-1] if name == 'z' and z_side == 'right' + else members[0]] + for i in keepers: + drawn[i].add(name) + return drawn + + +def _axis_label_artists(ax): + """``{'x': Text, 'y': Text[, 'z': Text]}``: the axis-label artists of + a matplotlib 2-D or 3-D axes.""" + return {name: getattr(ax, name + 'axis').label + for name in ('x', 'y', 'z') if hasattr(ax, name + 'axis')} + + +def _z_label_side(fig, panel_axes): + """``'left'`` or ``'right'``: the side of its cube matplotlib draws a + 3-D panel's z label on, at the grid's view (it depends on the camera + angle, `azim=`/`elev=`). Measured on a real layout of the first panel + that has a z label, at frame 0 of an animation; ``'right'`` (the side + at hypertools' default view) when no panel has one.""" + for ax in panel_axes: + label = _axis_label_artists(ax).get('z') + if label is None or not (label.get_text() and label.get_visible()): + continue + box = label.get_window_extent(_measurement_renderer(fig)) + center = ax.get_window_extent() + return ('right' if 0.5 * (box.x0 + box.x1) + >= 0.5 * (center.x0 + center.x1) else 'left') + return 'right' + + +def _apply_outer_labels(fig, panel_axes, nrows, ncols): + """Keep a matplotlib grid's SHARED axis labels on its outer panels + only (`_outer_label_panels`), static or animated: every other panel's + copy of a shared label is emptied (``ax.get_xlabel()`` is then ``''``), + so nothing downstream -- `tight_layout`, the 3-D cube fit + (`_fit_panel_cubes`), a ``bbox_inches='tight'`` save -- reserves room + for a label that is not drawn. Called once the panels are drawn and + BEFORE the grid is laid out. Tick labels are not touched.""" + if not panel_axes: + return + cubes = hasattr(panel_axes[0], 'get_proj') + artists = [_axis_label_artists(ax) for ax in panel_axes] + texts = [{name: (label.get_text() if label.get_visible() else '') + for name, label in found.items()} for found in artists] + if not any(text for found in texts for text in found.values()): + return + drawn = _outer_label_panels( + texts, nrows, ncols, ndims=3 if cubes else 2, + z_side=_z_label_side(fig, panel_axes) if cubes else 'left') + for found, keep in zip(artists, drawn): + for name, label in found.items(): + if name not in keep and label.get_text(): + label.set_text('') + + +#: room (pixels) a plotly 3-D grid's left margin is given for the z titles +#: written beside its first column (`_apply_outer_labels_plotly`) +_PLOTLY_Z_TITLE_PX = 30 + +#: the ``name`` of the paper annotation that writes panel ``i``'s z title +#: beside a plotly 3-D grid's first column +PLOTLY_Z_TITLE_NAME = 'hyp_panel_ztitle_{}' + + +def _apply_outer_labels_plotly(panel_figs, nrows, ncols, ndims): + """The plotly grid's `_apply_outer_labels`: keep SHARED axis titles + on the outer panels only, by the same decision + (`_outer_label_panels`). `panel_figs` are the drawn single-axes panel + figures, before they are transplanted into the grid; every other + panel's copy of a shared title is emptied (the axis itself, and its + ticks when ``axis_scale='data'`` shows them, are left as drawn). A + 3-D grid's z title goes to the `_PLOTLY_Z_LABEL_SIDE` end of each + row. + + Returns ``{panel index: z title}`` for the FIRST-COLUMN panels of a + 3-D grid that draw one. plotly writes a scene's z title left of its + cube, and a grid's cube fills its cell's width, so there the title + fell outside the scene and was clipped away (on every panel, before + 1.2.0). Those titles are taken out of their scenes, and the caller + writes them in the grid's left margin instead + (`_add_plotly_z_titles`), where an outer label belongs.""" + def _axes(panel): + holder = panel.layout.scene if ndims >= 3 else panel.layout + return {name: holder[name + 'axis'] + for name in (('x', 'y', 'z') if ndims >= 3 else ('x', 'y'))} + + found = [_axes(panel) for panel in panel_figs] + texts = [{name: (axis.title.text if axis.visible is not False else '') + for name, axis in axes.items()} for axes in found] + drawn = _outer_label_panels(texts, nrows, ncols, ndims=ndims, + z_side=_PLOTLY_Z_LABEL_SIDE) + margin_titles = {} + for i, (axes, panel_texts, keep) in enumerate(zip(found, texts, drawn)): + for name, axis in axes.items(): + if not panel_texts[name]: + continue + if name not in keep: + axis.title.text = '' + elif name == 'z' and i % ncols == 0: + margin_titles[i] = panel_texts[name] + axis.title.text = '' + return margin_titles + + +def _add_plotly_z_titles(fig, margin_titles, scene_keys): + """Write a plotly 3-D grid's first-column z titles (`margin_titles`, + from `_apply_outer_labels_plotly`) in the left margin, each rotated + and centered on its panel's scene (``scene_keys[i]``), as a paper + annotation named `PLOTLY_Z_TITLE_NAME`.""" + for i, text in margin_titles.items(): + domain = fig.layout[scene_keys[i]].domain + fig.add_annotation( + text=text, x=domain.x[0], y=0.5 * (domain.y[0] + domain.y[1]), + xref='paper', yref='paper', xanchor='center', yanchor='middle', + xshift=-0.5 * _PLOTLY_Z_TITLE_PX, textangle=-90, + showarrow=False, name=PLOTLY_Z_TITLE_NAME.format(i)) + + +def _tighten_panel_grid(fig): + """Lay a grid's panels out in the figure as it is (`tight_layout`): + the one layout pass of every matplotlib `panels=` grid, with or + without a shared legend/colorbar strip, static or animated. + + Run to convergence: the panels were last laid out around what each + drew itself (its own legend, since merged into the grid's; axis + labels since left to the outer panels), and one pass from there + under-reserves a 3-D panel's title room (its box is + aspect-constrained); a second settles it. + + The panels' cells never overlap afterwards. `tight_layout` measures a + 3-D axes that draws axis labels by its cube alone, which is smaller + than its box, and so closes the gaps between such panels past zero + (negative ``wspace``/``hspace``): the boxes then overlap, a panel's + square -- which `_fit_panel_cubes` keeps its cube and labels inside -- + reaches into the next panel's, and so did its labels. A negative gap + is set back to none.""" + with warnings.catch_warnings(): + # a shared colorbar's axes is placed by hand, which `tight_layout` + # reports as an axes it cannot lay out + warnings.filterwarnings( + 'ignore', message='This figure includes Axes that are not ' + 'compatible with tight_layout') + for _ in range(3): + fig.tight_layout() + pars = fig.subplotpars + if pars.wspace < 0 or pars.hspace < 0: + fig.subplots_adjust(wspace=max(pars.wspace, 0.0), + hspace=max(pars.hspace, 0.0)) + + def _plot_panels(x, panels, call_kwargs, _name='panels'): """`_plot_panels_impl` (the `panels=` implementation), leaving no figure behind when it fails: whatever the reason a grid call raises -- a @@ -6025,6 +6231,14 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): # panels of unequal width (independent fits) share no axes _rows = _placeholder_rows([len(xf[0]) for xf in panel_xforms], width=panel_ndims) + elif len({tuple(map(str, row.columns)) for row in _rows + if is_frame_dataset(row)}) > 1: + # panels whose DataFrames name their columns differently + # (independent fits: each panel has its own features) cannot be + # stacked by feature name; colors, legend entries and the + # colorbar do not depend on the names, so resolve them on the + # bare rows (this call refused such a grid outright) + _rows = [np.asarray(row) for row in _rows] resolution = _resolve_grid_colors( _rows, shared, panel_ndims, probe_warnings, clustering=grid_clustering) @@ -6239,6 +6453,10 @@ def _draw_grid(consolidate): _reemit_panel_warnings(probe_warnings, draw_warnings) for spare in axes[n_panels:]: spare.set_visible(False) + # shared axis labels are drawn on the outer panels only (1.2.0), static + # or animated; decided here, before anything is laid out, so every + # later step reserves room for the labels actually drawn + _apply_outer_labels(fig, panel_axes, nrows, ncols) strip = None if (consolidate and legend_spec is not None) \ or colorbar_info is not None: @@ -6268,7 +6486,7 @@ def _draw_grid(consolidate): if _extra: _w, _h = fig.get_size_inches() fig.set_size_inches(_w + _extra, _h) - fig.tight_layout() + _tighten_panel_grid(fig) #: the bundle's ``'colors'``: the one scale the panels share grid_colors = None @@ -6292,23 +6510,16 @@ def _draw_grid(consolidate): strip=strip, grid_colors=grid_colors, rotations=call_kwargs.get('rotations', 1)) - # a static 3-D panel's axis labels stay inside the panel's own box - _fit_static_cube_labels(fig, panel_axes, - resize=call_kwargs.get('size') is None) - _place_shared_furniture(fig, strip) - - if caption is not None or dynamic_caption is not None: - # a static grid's caption: fixed text, or the dynamic forms - # resolved once for the finished figure (as a dynamic title= is on - # a static plot) - _add_grid_caption( - fig, caption, dynamic_caption, call_kwargs.get('font'), - context=(_static_grid_context( - fig, panel_axes, panel_xforms, order='parallel') - if dynamic_caption is not None else None)) - # the caption's room was added under the grid: re-center the - # shared legend/colorbar on the panels - _place_shared_furniture(fig, strip) + # the layout an animated grid gets, at the one view; a dynamic caption + # is resolved once, for the finished figure (as a dynamic title= is on + # a static plot) + _lay_out_panel_grid( + fig, panel_axes, (nrows, ncols), strip, + resize=call_kwargs.get('size') is None, + caption=caption, dynamic_caption=dynamic_caption, + font=call_kwargs.get('font'), + frame_context=lambda _frame: _static_grid_context( + fig, panel_axes, panel_xforms, order='parallel'), _name=_name) if save_path is not None: fig.savefig(save_path) @@ -6469,16 +6680,12 @@ def _common(name): #: fill, at most _PANEL_CUBE_FILL = 0.96 -#: the least a LABELED animated panel cube may be, as a share of the size -#: the same cube has without axis labels: below this the cube is too small -#: beside its own labels, and the default figure grows instead +#: the least a panel cube that draws axis labels may be, static or +#: animated, as a share of the size the same cube has without them: below +#: this the cube is too small beside its own labels, and the default figure +#: grows instead... _PANEL_LABELED_CUBE_SHARE = 0.7 -#: ...the least a labeled STATIC panel cube may be before its default figure -#: grows (a static cube has one view, so its labels need less room than a -#: rotating one's and the figure is enlarged a little later)... -_STATIC_LABELED_CUBE_SHARE = 0.65 - #: ...and the legible floor at an explicit `size=` (a size the caller chose #: is honored down to cubes half their unlabeled size): under it an #: animated grid is refused, and a static grid is drawn with its cubes AT @@ -6526,11 +6733,13 @@ def _cube_reach(axis, azimuths): def _axis_label_reach(fig, cells, rotations): """Per cell, how far its 3-D AXIS LABELS reach from the center of the - axes' square over the views the panel is seen from (0.5 is the - square's edge; 0.0 for a cell without labels). Label placement is - matplotlib's, decided at draw time, so this draws the figure once per - sampled camera angle (every 30 degrees of the rotation).""" - reaches = [0.0] * len(cells) + axes' square in each direction -- ``{'left', 'right', 'down', 'up'}`` + -- over the views the panel is seen from (0.5 is the square's edge; + 0.0 where a cell draws no label). Label placement is matplotlib's, + decided at draw time, so this draws the figure once per sampled camera + angle (every 30 degrees of the rotation).""" + reaches = [dict.fromkeys(('left', 'right', 'down', 'up'), 0.0) + for _ in cells] views = [(cell['axes'].elev, cell['axes'].azim) for cell in cells] sweeps = [_camera_azimuths(cell['axes'], rotations, 30.0) for cell in cells] @@ -6539,7 +6748,7 @@ def _axis_label_reach(fig, cells, rotations): cell['axes'].view_init(elev=elev, azim=sweep[min(step, len(sweep) - 1)]) renderer = _measurement_renderer(fig) - for k, cell in enumerate(cells): + for reach, cell in zip(reaches, cells): axis = cell['axes'] to_square = axis.transAxes.inverted() for axis3d in axis._axis_map.values(): @@ -6547,19 +6756,118 @@ def _axis_label_reach(fig, cells, rotations): if not (label.get_text() and label.get_visible()): continue box = label.get_window_extent(renderer) - frac = to_square.transform(box.get_points()) - reaches[k] = max(reaches[k], - float(np.abs(frac - 0.5).max())) + (x0, y0), (x1, y1) = to_square.transform(box.get_points()) + for side, value in (('left', 0.5 - min(x0, x1)), + ('right', max(x0, x1) - 0.5), + ('down', 0.5 - min(y0, y1)), + ('up', max(y0, y1) - 0.5)): + reach[side] = max(reach[side], float(value)) for cell, (elev, azim) in zip(cells, views): cell['axes'].view_init(elev=elev, azim=azim) return reaches +#: blank room (inches) kept between an outer panel's axis label and the +#: edge of the room the figure is given for it (`_outer_label_margins`) +_OUTER_LABEL_PAD_IN = 0.06 + + +def _open_label_sides(fig, panel_axes, grid, strip): + """Per panel of a 3-D grid, the sides of its cell that hold nothing + its axis labels could run into, so the labels may hang past the + panel's square there instead of the cube being drawn smaller to keep + them inside it: ``{side: 'edge' | 'spare'}`` with sides ``'left'``, + ``'right'``, ``'down'`` (never up: a title sits above a panel). + + ``'edge'`` is the outer edge of the grid -- the left of the first + column, the right of the last one, the bottom of the last row -- where + the figure is given the room the labels need (`_outer_label_margins`); + ``'spare'`` is a spare (hidden) cell of the grid, right of the last + panel or under a panel of the row above. Shared axis labels are drawn + on exactly these panels (`_outer_label_panels`), which is what gives + the inner panels' room back without drawing the labeled cubes smaller + than the rest. + + No side is open where something else is drawn there: a panel's own + legend or colorbar (colors that mean something different per panel), + a shared legend placed left of or under the grid, a shared colorbar + anywhere but the right-hand strip (which starts past the labels' + room). + """ + nrows, ncols = grid + n = len(panel_axes) + closed = [{} for _ in range(n)] + known = set(panel_axes) + if any(ax.get_legend() is not None for ax in panel_axes) or any( + ax.get_visible() and ax not in known + and ax.get_gid() != SHARED_COLORBAR_GID for ax in fig.axes): + return closed + blocked = set() + if strip is not None: + if strip.get('colorbar') is not None and not strip.get('colorbar_in'): + return closed + if strip.get('legend') is not None: + blocked.add({'left': 'left', 'bottom': 'down'}.get( + strip.get('side'))) + sides = [] + for i in range(n): + row, col = divmod(i, ncols) + found = {} + if col == 0: + found['left'] = 'edge' + if col == ncols - 1: + found['right'] = 'edge' + elif i + 1 >= n: + found['right'] = 'spare' + if row == nrows - 1: + found['down'] = 'edge' + elif i + ncols >= n: + found['down'] = 'spare' + sides.append({side: where for side, where in found.items() + if side not in blocked}) + return sides + + +def _outer_label_margins(fig, cubes, strip): + """``{'left', 'right', 'bottom'}``: the inches a grid's figure must + grow by on each side for the axis labels its outer 3-D panels hang + past their squares (`_open_label_sides`' ``'edge'`` sides; the reach + is the one `_fit_panel_cubes` measured), beyond the blank room already + there. On the right the room ends where the shared legend/colorbar + strip begins.""" + width, height = fig.get_size_inches() + right_edge = 1.0 if strip is None else float(strip['rect_right']) + grow = {'left': 0.0, 'right': 0.0, 'bottom': 0.0} + for cell in cubes: + reach = cell.get('label_reach') + if reach is None: + continue + box = cell['axes'].get_position() + for side, where in cell.get('open', {}).items(): + if where != 'edge' or reach[side] <= 0.0: + continue + if side == 'down': + need = (reach['down'] - 0.5) * box.height * height + have, key = box.y0 * height, 'bottom' + else: + need = (reach[side] - 0.5) * box.width * width + have = ((right_edge - box.x1) if side == 'right' + else box.x0) * width + key = side + grow[key] = max(grow[key], need + _OUTER_LABEL_PAD_IN - have) + return grow + + class _StaticCubeZoom: """A STATIC 3-D panel's zoom handle, in the shape of an animated - panel's `PanelAnimationStub` (``zoom_scale`` and ``draw``), so - `_fit_panel_cubes` fits either: ``draw`` applies ``zoom_scale[0]`` to - the axes' own box aspect.""" + panel's `PanelAnimationStub` (``zoom_scale``, ``start_scale`` and + ``draw``), so `_fit_panel_cubes` fits either: ``draw`` applies + ``zoom_scale[0]`` to the axes' own box aspect, whose default zoom + (``start_scale`` 1.0) is the size a static cube is drawn at.""" + + #: the ``zoom_scale`` the cube fit starts from: matplotlib's default + #: box zoom + start_scale = 1.0 def __init__(self, axis): self._axis = axis @@ -6596,66 +6904,58 @@ def _axis_labels_collide(fig, cells): return False -def _fit_static_cube_labels(fig, panel_axes, resize=True): - """Keep every STATIC 3-D panel's axis labels inside the panel's own - box (`_fit_panel_cubes`): matplotlib hangs a 3-D axes' labels outside - its cube, where no layout accounts for them, so in a grid they landed - on the next panel's cube, on the title of the panel below and on the - shared legend. A labeled panel's cube is drawn smaller until its - labels fit, and where that would leave the cube too small the figure - is enlarged instead (`resize`: no explicit `size=`, which is honored - as given -- with a warning that names a size that works when it cannot - hold the labeled grid legibly, see `_fit_panel_cubes`). Panels without - axis labels are not touched.""" - cells = [{'axes': ax, 'stub': _StaticCubeZoom(ax)} - for ax in panel_axes - if ax.get_visible() and hasattr(ax, 'get_proj') - and _has_axis_labels(ax)] - if cells: - _fit_panel_cubes(fig, cells, resize=resize, rotations=0, - static=True) - - def _fit_panel_cubes(fig, cells, resize=True, rotations=1, static=False, _name='panels'): - """Zoom every 3-D panel out until its cube -- and its axis labels, - when it has any -- stay inside the panel's own box at EVERY camera - angle the panel is seen from (GH #295). - - A single animated 3-D plot gives its axes the whole canvas, because the - cube an animation draws -- zoomed, and wider on screen when seen - corner-on -- overflows a normal subplot box at some angles (the frame - and the data are drawn unclipped). In a grid that overflow would run - into the panel's own title and legend and into the next panel. So the - cube's projected extent is measured over the views the animation - takes (`_camera_azimuths`: the whole turn, the arc of a partial one, - or the single view of ``rotations=0``), at the panel's own elevation - and zoom, and the panel's box zoom is lowered - (`PanelAnimationStub.zoom_scale`) until the widest view fits the square - matplotlib draws a 3-D axes in -- which the title sits above and the - legend beside. A panel whose cube already fits is left alone, and 2-D - panels have no camera and are never touched. - - Axis labels (`xlabel=`/`ylabel=`/`zlabel=`) hang outside the cube, at - a distance that scales with the cube, and swing around with it, so a - labeled panel's cube is drawn smaller still, until the labels fit - too. The figure is enlarged only where that leaves a cube smaller - than `_PANEL_LABELED_CUBE_SHARE` of its unlabeled size -- and then by - no more than brings it back to that (`resize`, i.e. no explicit - `size=`). An explicit `size=` is honored down to - `_REFUSED_LABELED_CUBE_SHARE`; below that this raises, naming a size - that works (it is found by fitting the grid at that size). - - `static` fits a STATIC grid's labeled panels (see - `_fit_static_cube_labels`): only the labels are fitted, at the one - view. An explicit `size=` is never refused for a static grid (the call - always drew). Where it cannot hold the labeled grid legibly -- a cube - would fall under `_REFUSED_LABELED_CUBE_SHARE` of its unlabeled size, - or a panel's own labels would be drawn over each other - (`_axis_labels_collide`) -- the cubes are kept at that share at least, - the labels fall where they fall, and ONE `UserWarning` names a size - that works (found the same way) and the alternative of dropping the - labels. + """Zoom every 3-D panel out until its cube -- and the axis labels it + draws, when it draws any -- stay inside the panel's own box at EVERY + camera angle the panel is seen from (GH #295). The one cube fit of + every matplotlib grid, static or animated (`_lay_out_panel_grid`). + + A grid's cubes start at the size a static panel's is drawn at -- + matplotlib's default box zoom, times an animation's own `zoom=` + (each stub's ``start_scale``: an animated panel's undoes the extra + zoom a single animated plot fills its whole canvas with) -- and a + cube can overflow a subplot box at some angles, wider on screen when + seen corner-on (the frame and the data are drawn unclipped). In a + grid that overflow would run into the panel's own title and legend + and into the next panel. So the cube's projected + extent is measured over the views the panel is seen from + (`_camera_azimuths`: the whole turn of a rotating animation, the arc + of a partial one, or the single view of ``rotations=0`` and of a + static grid), at the panel's own elevation and zoom, and the panel's + box zoom is lowered (the stub's ``zoom_scale``) until the widest view + fits the square matplotlib draws a 3-D axes in -- which the title + sits above and the legend beside. A panel whose cube already fits is + left alone, and 2-D panels have no camera and are never touched. The + views are the ONLY thing an animation changes here: a static grid and + the same grid animated with ``rotations=0`` come out the same. + + Axis labels hang outside the cube, at a distance that scales with + the cube, and swing around with it, so a panel that draws labels has + its cube drawn smaller still, until the labels fit too. Only the + labels a panel actually draws count (`_apply_outer_labels` leaves + shared labels on the outer panels alone), and only where they could + run into something: past a cell's ``'open'`` sides + (`_open_label_sides`, set by `_lay_out_panel_grid` for a grid seen + from one view) a label may hang out of the panel's square, and its + final reach is recorded as the cell's ``'label_reach'`` for the room + the figure gives it (`_outer_label_margins`). Every cube of the grid + is then drawn at the SAME share of its unlabeled size, the smallest + any panel's labels leave, so the panels stay comparable. The figure + is enlarged only where that share is under + `_PANEL_LABELED_CUBE_SHARE` -- and then by no more than brings it + back to that (`resize`, i.e. no explicit `size=`). + + An explicit `size=` is honored down to `_REFUSED_LABELED_CUBE_SHARE`. + Below that an animated grid raises, naming a size that works (it is + found by fitting the grid at that size). A STATIC grid (`static`) is + never refused -- the call always drew, before the labels were fitted + at all: where the size cannot hold the labeled grid legibly (a cube + would fall under that share, or a panel's own labels would be drawn + over each other, `_axis_labels_collide`) the cubes are kept at that + share at least, the labels fall where they fall, and ONE + `UserWarning` names a size that works (found the same way) and the + alternative of dropping the labels. """ cubes = [cell for cell in cells if hasattr(cell['axes'], 'get_proj')] limit = 0.5 * _PANEL_CUBE_FILL @@ -6681,9 +6981,11 @@ def _fit(least=0.0): drawn smaller than the share `least` of its unlabeled size (its labels then reach past the panel's box).""" for cell in cubes: - cell['stub'].zoom_scale[0] = 1.0 - # (a static cube is only ever moved for its labels) - _fit_cube(cell, 10.0 * limit if static else limit) + # every grid cube starts at the size a static panel's is drawn + # at (matplotlib's default box zoom, times the animation's own + # `zoom=`): the stub's `start_scale` + cell['stub'].zoom_scale[0] = cell['stub'].start_scale + _fit_cube(cell, limit) # what the cube reaches without labels, over these views cell['free'] = cell['reach'] pending = list(labeled) @@ -6691,8 +6993,13 @@ def _fit(least=0.0): if not pending: break over = [] - for cell, label_reach in zip( + for cell, sides in zip( pending, _axis_label_reach(fig, pending, rotations)): + # (an open side holds nothing the labels could run into: + # `_open_label_sides`) + label_reach = max([0.0] + [ + reach for side, reach in sides.items() + if side not in cell.get('open', {})]) if label_reach - limit <= 0.004: continue # the labels' distance from the cube scales with the cube @@ -6704,12 +7011,20 @@ def _fit(least=0.0): _fit_cube(cell, max(0.02, target)) over.append(cell) pending = over - return min([1.0] + [cell['reach'] / cell['free'] - for cell in labeled]) + share = min([1.0] + [cell['reach'] / cell['free'] + for cell in labeled]) + for cell in cubes: + # ONE cube size for the grid: the panels are read side by + # side, so every cube is drawn at the share of its unlabeled + # size that the panel needing the most room for its labels is + # left with (a grid whose labeled cubes alone were drawn + # smaller looked broken) + if cell['reach'] > (share + 0.002) * cell['free']: + _fit_cube(cell, share * cell['free']) + return share smallest = _fit() floor = (_REFUSED_LABELED_CUBE_SHARE if not resize - else _STATIC_LABELED_CUBE_SHARE if static else _PANEL_LABELED_CUBE_SHARE) # a static grid at an explicit `size=` must also keep each panel's own # labels off each other (around a small cube they converge) @@ -6793,6 +7108,98 @@ def _illegible(): for cell in cubes: # leave every panel showing frame 0 at its final zoom cell['stub'].draw(0) + outer = [cell for cell in labeled if cell.get('open')] + for cell, sides in zip(outer, _axis_label_reach(fig, outer, rotations)): + # what the labels reach past an open side, for the room the + # figure gives them there (`_outer_label_margins`) + cell['label_reach'] = sides + + +def _lay_out_panel_grid(fig, panel_axes, grid, strip, cells=None, + resize=True, rotations=0, caption=None, dynamic_caption=None, + font=None, frame_context=None, sample_frames=(), + _name='panels'): + """Finish the layout of a drawn matplotlib `panels=` grid -- the ONE + path of static and animated grids (1.2.0). When this is called the + panels are drawn, shared axis labels are on the outer panels only + (`_apply_outer_labels`), and the grid has its strip for a shared + legend/colorbar (`strip`, from `_add_shared_furniture`) or was laid + out by `tight_layout` (titles and 2-D axis labels have their room). + This then + + 1. fits every 3-D panel's cube, and the axis labels it draws, inside + the panel's own cell, enlarging a default-sized figure (`resize`) + only as far as legible labeled cubes need (`_fit_panel_cubes`); + 2. re-centers the shared legend/colorbar on the panels + (`_place_shared_furniture`); + 3. adds the caption's room under the grid and draws it + (`_add_grid_caption`), then re-centers the strip again. + + An animated grid passes its `cells` (each panel's + `PanelAnimationStub`) and differs in exactly two inputs, both of them + things only an animation has: the VIEWS a cube is fitted over (the + arc `rotations` sweeps, instead of the one view; ``rotations=0`` is + the static grid's layout), and the per-frame texts a dynamic caption's + room is sized for (`sample_frames`, each resolved through + `frame_context(frame)`; a static grid resolves ``frame_context(0)``, + its finished figure, alone). What an explicit `size=` too small for + labeled cubes does also differs (an animated grid raises, a static + one warns; see `_fit_panel_cubes`). + + Returns the caption's ``Text`` (None without a caption). + """ + animated = cells is not None + rotations = rotations if animated else 0 + cubes = cells if animated else [ + {'axes': ax, 'stub': _StaticCubeZoom(ax)} + for ax in panel_axes if hasattr(ax, 'get_proj')] + if cubes and resize and len(cubes) == len(panel_axes) and all( + hasattr(ax, 'get_proj') + and len(_camera_azimuths(ax, rotations, 30.0)) == 1 + for ax in panel_axes): + # seen from ONE view, the labels of the outer panels hang toward + # the grid's outer edge, where the default figure is given room + # for them; a rotating panel's labels swing through every side + # and are kept inside its own cell (below) + for cell, sides in zip(cubes, _open_label_sides( + fig, panel_axes, grid, strip)): + cell['open'] = sides + _fit_panel_cubes(fig, cubes, resize=resize, rotations=rotations, + static=not animated, _name=_name) + margins = _outer_label_margins(fig, cubes, strip) + if any(value > 0.0 for value in margins.values()): + margins = {side: max(value, 0.0) for side, value in margins.items()} + _grow_figure(fig, **margins) + if strip is not None: + # the strip keeps its width, right of the labels' room + total = fig.get_size_inches()[0] + strip['rect_right'] = ( + strip['rect_right'] * (total - margins['left'] + - margins['right']) + + margins['left'] + margins['right']) / total + _place_shared_furniture(fig, strip) + if animated: + for cell in cells: + # a still of the grid shows frame 0 (a 2-D panel was laid out + # showing its tallest per-frame title; see `plot`) + cell['stub'].draw(0) + caption_artist = None + if caption is not None or dynamic_caption is not None: + dynamic = dynamic_caption is not None + # frame 0's text is what a still of the figure shows, and with + # the sampled frames' it sizes the caption's room; an animated + # grid's panels are drawn at each to get its real context (frames + # are idempotent, see `FrameContext`) + samples = ([frame_context(frame) for frame in sample_frames] + if dynamic else ()) + caption_artist = _add_grid_caption( + fig, caption, dynamic_caption, font, + context=frame_context(0) if dynamic else None, + sample_contexts=samples) + # the caption's room was added under the grid: re-center the + # shared legend/colorbar on the panels + _place_shared_furniture(fig, strip) + return caption_artist def _animate_panel_grid(fig, cells, panel_axes, panel_models, grid, @@ -6841,43 +7248,23 @@ def _abandon(): "animate='morph', and scalar duration=/frame_rate=/rotations=.") n_frames = frame_counts[0] interval = cells[0]['stub']._interval - try: - _fit_panel_cubes(fig, cells, resize=resize, rotations=rotations, - _name=_name) - _place_shared_furniture(fig, strip) - for cell in cells: - # a still of the grid shows frame 0 (a 2-D panel was laid out - # showing its tallest per-frame title; see `plot`) - cell['stub'].draw(0) - except Exception: - _abandon() - raise - def _draw_panels(num): for cell in cells: cell['stub'].draw(num) return _panel_grid_context(fig, cells, num, n_frames) - caption_artist = None - if caption is not None or dynamic_caption is not None: - try: - # frame 0's text is what a still of the figure shows, and with - # the middle and last frames' it sizes the caption's room; the - # panels are drawn at each to get its real context (frames are - # idempotent, see `FrameContext`) - contexts = ([_draw_panels(frame) - for frame in _caption_sample_frames(n_frames)] - if dynamic_caption is not None else [None]) - caption_artist = _add_grid_caption( - fig, caption, dynamic_caption, font, - context=(_draw_panels(0) if dynamic_caption is not None - else None), - sample_contexts=contexts if dynamic_caption is not None - else ()) - _place_shared_furniture(fig, strip) - except Exception: - _abandon() - raise + try: + # the layout a static grid gets, over the views this animation + # takes, with the caption's room sized for its per-frame texts + caption_artist = _lay_out_panel_grid( + fig, panel_axes, grid, strip, cells=cells, resize=resize, + rotations=rotations, caption=caption, + dynamic_caption=dynamic_caption, font=font, + frame_context=_draw_panels, + sample_frames=_caption_sample_frames(n_frames), _name=_name) + except Exception: + _abandon() + raise def _grid_frame(num, *_): context = _draw_panels(num) @@ -7066,6 +7453,10 @@ def _draw_panels(consolidate): _position = _explicit_legend_position( panel_figs[0].layout.legend.to_plotly_json() if panel_figs[0].layout.legend is not None else {}) + # shared axis titles are drawn on the outer panels only, by the same + # decision the matplotlib grid makes + margin_titles = _apply_outer_labels_plotly(panel_figs, nrows, ncols, + ndims) strip_px = 0 if shared_legend and _position is None: strip_px += PANEL_LEGEND_PX @@ -7082,12 +7473,21 @@ def _draw_panels(consolidate): gutter_px=(0 if consolidate else panel_gutter_px( legend_present, colorbar_present)), title_px=title_px, strip_px=strip_px) + if margin_titles: + # room in the left margin for the first column's z titles: the + # default figure is widened by it, an explicit `size=` is kept + _extra = max(0, _PLOTLY_Z_TITLE_PX - int(fig.layout.margin.l or 0)) + fig.update_layout( + margin_l=int(fig.layout.margin.l or 0) + _extra, + **({'width': fig.layout.width + _extra} + if call_kwargs.get('size') is None else {})) panel_axes = [] for i, panel in enumerate(panel_figs): keys = transplant_panel(fig, panel, i // ncols + 1, i % ncols + 1, i, ndims) panel_axes.append(keys['scene'] if ndims >= 3 else (keys['xaxis'], keys['yaxis'])) + _add_plotly_z_titles(fig, margin_titles, panel_axes) if shared_legend or colorbar_info is not None: place_shared_furniture( fig, shared_legend, @@ -8240,7 +8640,9 @@ def plot( (`ndims` < 3, or data that is intrinsically lower-dimensional) raises `ValueError` (no z-axis to label) -- pass `ndims=3` (the default) to use `zlabel=`, or use `xlabel=`/`ylabel=` for 2-D - data. + data. In a `panels=` grid an axis label that is the same in every + panel of a column (or row) is drawn once, on the grid's outer + panels (see `panels=`). size : list A [width, height] pair of numbers, in inches, to resize the figure @@ -9641,7 +10043,24 @@ def plot( Axis labels are derived per panel from that panel's own DataFrame column names, under the same rule a single-axes call uses (2-D or 3-D, one drawn axis per named column); an explicit - `xlabel=`/`ylabel=`/`zlabel=` still wins. + `xlabel=`/`ylabel=`/`zlabel=` still wins. SHARED axis labels are + drawn on the outer panels only (since 1.2.0), on both backends, + static or animated. A label drawn along the bottom of a panel -- + x in 2-D and in ``ndims=1`` panels; x and y, the floor axes, in + 3-D -- is drawn under the lowest panel of each column when every + panel of that column has the same text for it. A label drawn up + the side of a panel -- y in 2-D, z in 3-D -- is drawn on one + panel of each row when every panel of that row has the same text + for it: the left-most panel in 2-D, and in 3-D the panel at the + end of the row the z label is drawn toward (matplotlib: the + right-most at the default view, the left-most at an `azim=` that + puts the z label on the cube's left; plotly: the left-most, its z + title written beside the grid). Where the texts of a column (or + row) differ, every panel of it keeps its own, and spare cells of + the grid count for nothing (a panel above a spare cell draws the + x label). Tick labels (``axis_scale='data'``) stay on every + panel. The room of the labels that are not drawn is given back + to the panels. Like the single-axes path, ``show=True`` registers the figure with pyplot and does NOT call ``plt.show()`` itself (see `show=`). @@ -9775,33 +10194,41 @@ def plot( simply reveals its own), and the panels never take turns. Every panel must draw the same number of frames (``animate='morph'`` needs the same number of datasets in each panel), or the call - raises ``ValueError``. Each 3-D panel's cube is zoomed out as far - as it takes to stay inside its own cell through the whole + raises ``ValueError``. Each 3-D panel's cube starts at the size a + static panel's is drawn at (scaled by `zoom=`) and is zoomed out + as far as it takes to stay inside its own cell through the whole rotation, so `zoom=` can shrink a panel's cube but cannot enlarge - it past its cell. With axis labels (`xlabel=`/`ylabel=`/`zlabel=`, - or a DataFrame's column names) the cube is drawn smaller still, - so the labels stay inside the panel's own cell at every view the - animation takes (the whole turn, or the single view of - ``rotations=0``); the figure is enlarged only where that would - leave a cube under 70% of an unlabeled one's size, and by no - more than restores that. An explicit `size=` is honored down to - cubes half their unlabeled size and raises below that, naming a - size that works; ``xlabel='', ylabel='', + it past its cell. A static grid's cubes are drawn the same way, + at their one view: a static grid and the same grid animated with + ``rotations=0`` have the same figure size, the same panel + positions and the same cubes, and a rotating grid differs from + them only by the room its cubes' sweep needs. The axis labels a + 3-D panel draws (`xlabel=`/`ylabel=`/`zlabel=`, or a DataFrame's + column names; shared ones on the outer panels only, above) are + kept clear of every other panel. Seen from one view (a static + grid, or ``rotations=0``) the outer panels' labels hang toward + the grid's outer edge, and the default figure is given the room + they need there (right of the last column or left of the first + for the z label, under the last row for the floor labels), so + the cubes keep nearly their unlabeled size. A rotating panel's + labels swing through every side of its cube, and a label kept on + an inner panel has no outer edge, so there the cubes are drawn + smaller, until the labels stay inside the panel's own cell at + every view the animation takes. Every cube of a grid is drawn + the same size (the one the panel needing the most room is left + with). The figure is enlarged only where that would leave the + cubes under 70% of their unlabeled size, and by no more than + restores that. An explicit `size=` is honored down to cubes half + their unlabeled size. Below that an animated grid raises, naming + a size that works; a static grid -- also where a panel's own + labels would be drawn over each other -- keeps its cubes at half + their unlabeled size, so the labels may overlap, and one + ``UserWarning`` names a size that works. ``xlabel='', ylabel='', zlabel=''`` drops the labels instead. Without `size=` the figure - is sized by the grid, as a static grid's is (above) -- so a - saved clip of a row of panels is not mostly blank canvas -- then - widened by the strip of a shared legend or colorbar, made taller - by a `caption=`, and enlarged for axis labels as just described. - A STATIC 3-D grid keeps its axis labels inside each panel the - same way, at its one view (its default figure grows only where a - cube would otherwise be under 65% of an unlabeled one's size, - which the grid-sized cells seldom need). An explicit `size=` is - always honored for a static grid: where it cannot hold the - labeled grid legibly -- a cube would be under half its unlabeled - size, or a panel's own labels would be drawn over each other -- - the cubes are kept at half their unlabeled size, so the labels - may overlap, and one ``UserWarning`` names a size that works and - the alternative ``xlabel='', ylabel='', zlabel=''``. + is sized by the grid (above) -- so a saved clip of a row of + panels is not mostly blank canvas -- then widened by the strip + of a shared legend or colorbar, made taller by a `caption=`, and + given room for axis labels as just described. `caption=` adds a line of text under the grid, updated every frame. A per-frame `title=` (callable or ``{index}`` pattern, one for all panels or a list with one per panel) is diff --git a/notes/session_2026-11-22_feat295-animated-panels.md b/notes/session_2026-11-22_feat295-animated-panels.md index 782ee780f..e0ca616b2 100644 --- a/notes/session_2026-11-22_feat295-animated-panels.md +++ b/notes/session_2026-11-22_feat295-animated-panels.md @@ -211,3 +211,78 @@ explicit `size=` still honored. copied in). - docs/prebuilt_gallery.json NOT touched: every static `panels=` gallery figure changes size and needs republishing at release. + +## Shared axis labels on the outer panels only; one layout path (owner decision 2026-11-22, for 1.2.0) + +Branch `feat/295-outer-labels` (worktree), on top of f31a022b. Tests: +`tests/test_panel_outer_labels.py`. + +Owner: "if x and/or y axis labels are shared across panels, we can just show +them on the left-most columns (shared x labels) and bottom-most rows (shared +y labels)"; implemented as the usual outer-labels convention (x under the +lowest panel of each column, y on the left-most panel of each row), static +and animated through one path. + +- `_outer_label_panels(labels, nrows, ncols, ndims, z_side)` is the ONE + decision function (`_LABEL_SHARED_ALONG`: 2-D x=column, y=row; 3-D x and y + =column, z=row). Same text in every occupied panel of the column/row -> + one carrier; texts differ (a missing label counts) -> every panel keeps + its own. Spare cells are not occupied. +- matplotlib: `_apply_outer_labels` (after the panels are drawn and the + legends merged, before any layout) empties the other panels' label text. + 3-D z carrier: the panel at the end of the row matplotlib draws the z + label toward, measured on a real layout (`_z_label_side`; right at the + default view, left at other azimuths). +- plotly: `_apply_outer_labels_plotly` (same decision, on the drawn panel + figures before the transplant). z titles go to the row's LEFT panel + (`_PLOTLY_Z_LABEL_SIDE`); a scene's own z title falls outside a grid + cell's scene and was clipped on every panel before, so first-column z + titles are written as paper annotations in the left margin + (`_add_plotly_z_titles`, `PLOTLY_Z_TITLE_NAME`, 30 px, default figure + widened). z titles kept on INNER plotly panels (rows whose z texts + differ) are still scene titles and still clipped. +- One layout: `_tighten_panel_grid` (tight_layout to convergence, negative + wspace/hspace set to 0: labeled 3-D boxes used to overlap) -> + `_lay_out_panel_grid` (cube fit, outer-label margins, strip, caption) for + static and animated alike. `_fit_static_cube_labels` and + `_STATIC_LABELED_CUBE_SHARE` (65%) are gone: one 70% floor. + Every cube starts at matplotlib's default box zoom (`start_scale` on + `PanelAnimationStub` = 1 / `_anim_box_zoom(1)`, on `_StaticCubeZoom` = 1), + so static == animated(rotations=0): same figure size, axes positions, + cubes, labels, strip and caption boxes (tested). Static cubes are + unchanged from 1.1 (plotly parity test kept); an animated grid's cubes + are ~7% smaller with rotations=0 and ~1% smaller rotating than in the + first 1.2.0 draft. +- 3-D label room: seen from ONE view (static, rotations=0, default size) + the outer panels' labels may hang past their squares toward the grid's + outer edge (`_open_label_sides`: 'edge' or 'spare' cell) and the figure + grows there by the measured overhang (`_outer_label_margins`, + `_grow_figure`; the right-hand strip moves out with it). Otherwise + (rotating; explicit `size=`; inner panels; per-panel legends/colorbars; + a shared legend left of/under the grid; a shared colorbar not in the + right strip) labels are kept inside the panel's own cell by drawing the + cube smaller. +- EVERY cube of a grid is drawn at the same share of its unlabeled size + (the smallest any panel's labels leave). Drawing only the label + carriers smaller looked broken (kept renders: + scratchpad feat295/outer/evidence_uneven_cubes_*.png). So in a ROTATING + grid the inner panels do not get their room back (all cubes at >= 70%, + as in the first draft); in a one-view grid they do. +- Still different between static and animated: an explicit `size=` too + small for labeled cubes raises for an animated grid and warns for a + static one (existing tests assert both; a static labeled grid always + drew in 1.1). +- Side fixes: `panel_fit='independent'` grids of DataFrames with different + column names were refused by the grid color resolution (stacked by + feature name); it now resolves on the bare rows. +- No opt-out was added. Labels that differ are all kept, so different + column names per panel (needs `panel_fit='independent'`) label every + panel; `xlabel=` etc. take one string for the whole grid. +- Existing tests rewritten to the new behavior (each marked "CHANGED for + 1.2.0 (owner decision 2026-11-22)"): tests/test_plot_panels_fit.py (5), + tests/test_static_panel_grid_size.py (1), tests/test_panel_layout_review.py + (`_assert_labels_clear`), tests/test_plot_panels.py (1), + tests/test_panels_shared_legend_colors.py (1). +- docs/prebuilt_gallery.json and docs/tutorials notebooks NOT touched: + static and animated `panels=` gallery figures with axis labels change and + need republishing at release. diff --git a/tests/test_animated_panels.py b/tests/test_animated_panels.py index 36e5daa83..76ed9c30d 100644 --- a/tests/test_animated_panels.py +++ b/tests/test_animated_panels.py @@ -465,8 +465,23 @@ def test_axis_labels_enlarge_the_figure_and_stay_inside_their_cells(): labeled = _grid(DATA[:3], panels=(1, 3), xlabel='first axis', ylabel='second axis', zlabel='third axis', duration=2, frame_rate=6) + # CHANGED for 1.2.0 (owner decision 2026-11-22): shared axis labels are + # drawn on the outer panels only, and an animated grid's cubes start + # at a static panel's size -- so these labels now fit with the cubes + # at 70% of their unlabeled size or more, and the figure is enlarged + # only when they would not (this asserted that the labeled figure is + # always wider than the plain one) assert (labeled.figure.get_size_inches()[0] - > plain.figure.get_size_inches()[0]) + >= plain.figure.get_size_inches()[0]) + plain.draw_frame(0) + labeled.draw_frame(0) + for bare, ax in zip(_panel_axes(plain.figure), + _panel_axes(labeled.figure)): + widths = [np.ptp(_cube_corners_px(a)[:, 0]) / a.bbox.width + for a in (bare, ax)] + # (the 70% is of the cube's widest reach over the turn, checked + # with a 2% tolerance; its width on frame 0 runs a little under) + assert widths[1] >= 0.65 * widths[0] fig = labeled.figure axes = _panel_axes(fig) for frame in range(labeled.n_frames): diff --git a/tests/test_panel_layout_review.py b/tests/test_panel_layout_review.py index 53eb07eb8..847ccd73f 100644 --- a/tests/test_panel_layout_review.py +++ b/tests/test_panel_layout_review.py @@ -86,7 +86,12 @@ def _assert_labels_clear(fig, n, frame=None): labels[i] = [axis.label.get_window_extent(renderer) for axis in (ax.xaxis, ax.yaxis, ax.zaxis) if axis.label.get_text()] - assert labels[i], i + # CHANGED for 1.2.0 (owner decision 2026-11-22): shared axis labels are + # drawn on the outer panels only, so an inner panel may draw none (this + # asserted that EVERY panel draws labels); the grid as a whole still + # draws each of them + assert len({axis.label.get_text() for ax in panels + for axis in (ax.xaxis, ax.yaxis, ax.zaxis)} - {''}) == 3 for i, ax in enumerate(panels): for label in labels[i]: where = (frame, i) diff --git a/tests/test_panel_outer_labels.py b/tests/test_panel_outer_labels.py new file mode 100644 index 000000000..c89085f8d --- /dev/null +++ b/tests/test_panel_outer_labels.py @@ -0,0 +1,810 @@ +"""Shared axis labels of a `panels=` grid are drawn on the outer panels +only (1.2.0, owner decision 2026-11-22), and a static grid and an animated +one are laid out by one path. + +The rule, for the occupied panels of a grid (spare cells do not count): + +- an axis label that runs along the BOTTOM of a panel (x in 2-D and in + ``ndims=1`` series panels; x and y, the floor axes, in 3-D) is drawn on + the lowest occupied panel of each column, when every occupied panel of + that column has the same text for it; +- an axis label that runs up the SIDE of a panel (y in 2-D; z in 3-D) is + drawn on one panel of each row, when every occupied panel of that row + has the same text for it: the left-most one in 2-D, and in 3-D the + panel at the end of the row on the side of the cube matplotlib draws + the z label on at the grid's view (the right-most at the default view); +- where the texts of a column (or row) differ, every panel of it keeps + its own. + +Everything is measured on real draws of real figures (Agg, and kaleido-free +plotly figure objects); nothing is mocked or patched. +""" +import itertools + +import matplotlib +matplotlib.use('Agg') + +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +import pytest +from mpl_toolkits.mplot3d import proj3d + +import hypertools as hyp +from hypertools.plot.plot import (CAPTION_GID, PLOTLY_Z_TITLE_NAME, + SHARED_COLORBAR_GID, SHARED_LEGEND_GID) + + +def _walk(seed, rows=24, cols=3): + rng = np.random.default_rng(seed) + return np.cumsum(rng.normal(size=(rows, cols)), axis=0) + + +def _frames(n, cols=('alpha', 'beta', 'gamma')): + """`n` DataFrames whose columns are named `cols` (as many columns).""" + return [pd.DataFrame(_walk(seed, cols=len(cols)), columns=list(cols)) + for seed in range(n)] + + +ANIM = dict(animate=True, duration=1, frame_rate=4, show=False) +#: datasets whose column names differ share no features, so they are fitted +#: per panel (a shared fit refuses them: features are matched by name) +OWN = dict(panel_fit='independent') + +#: grid shape -> (number of panels, the lowest occupied panel of each +#: column, the left-most panel of each row, the right-most occupied panel +#: of each row), all as row-major panel numbers +GRIDS = { + (1, 4): (4, {0, 1, 2, 3}, {0}, {3}), + (2, 2): (4, {2, 3}, {0, 2}, {1, 3}), + (4, 1): (4, {3}, {0, 1, 2, 3}, {0, 1, 2, 3}), + (2, 3): (5, {3, 4, 2}, {0, 3}, {2, 4}), + (3, 5): (13, {10, 11, 12, 8, 9}, {0, 5, 10}, {4, 9, 12}), +} +GRID_IDS = ['1x4', '2x2', '4x1', '2x3-with-5', '3x5-with-13'] + + +@pytest.fixture(autouse=True) +def _close_figures(): + yield + plt.close('all') + + +def _figure(result): + """The matplotlib figure of a static or animated grid call.""" + return getattr(result, 'figure', result) + + +def _plot(data, animated, **kwargs): + """A static grid's figure, or an animated grid's (showing frame 0).""" + extra = dict(ANIM) if animated else dict(show=False) + extra.update(kwargs) + return _figure(hyp.plot(data, **extra)) + + +def _drawn(ax): + """``{'x': text, ...}`` of the axis labels `ax` actually draws.""" + out = {} + for name in ('x', 'y', 'z'): + axis = getattr(ax, name + 'axis', None) + if axis is None: + continue + label = axis.label + if label.get_text() and label.get_visible(): + out[name] = label.get_text() + return out + + +def _carriers(fig, n, name): + """The panels (row-major numbers) that draw the `name` axis label.""" + return {i for i, ax in enumerate(fig.axes[:n]) if name in _drawn(ax)} + + +def _draw(fig): + fig.canvas.draw() + return fig.canvas.get_renderer() + + +def _cube_box(ax): + """The drawn box (pixels) of a 3-D axes' cube at its current view.""" + corners = np.array(list(itertools.product( + ax.get_xlim3d(), ax.get_ylim3d(), ax.get_zlim3d()))) + px, py, _ = proj3d.proj_transform( + corners[:, 0], corners[:, 1], corners[:, 2], ax.get_proj()) + points = ax.transData.transform(np.column_stack([px, py])) + return matplotlib.transforms.Bbox.from_extents( + points[:, 0].min(), points[:, 1].min(), + points[:, 0].max(), points[:, 1].max()) + + +def _shrunk(box, pixels=2.0): + """`box` less a couple of pixels of antialiasing on every side.""" + return matplotlib.transforms.Bbox.from_extents( + box.x0 + pixels, box.y0 + pixels, box.x1 - pixels, box.y1 - pixels) + + +# -------------------------------------------------------------------------- +# which panels carry which labels +# -------------------------------------------------------------------------- + +@pytest.mark.parametrize('animated', [False, True], + ids=['static', 'animated']) +@pytest.mark.parametrize('shape', list(GRIDS), ids=GRID_IDS) +def test_2d_shared_labels_are_drawn_on_the_outer_panels(shape, animated): + n, lowest, leftmost, _ = GRIDS[shape] + fig = _plot(_frames(n, ('alpha', 'beta')), animated, ndims=2, + panels=shape) + assert _carriers(fig, n, 'x') == lowest + assert _carriers(fig, n, 'y') == leftmost + for ax in fig.axes[:n]: + assert set(_drawn(ax).values()) <= {'alpha', 'beta'} + assert _drawn(ax).get('x', 'alpha') == 'alpha' + assert _drawn(ax).get('y', 'beta') == 'beta' + + +@pytest.mark.parametrize('animated', [False, True], + ids=['static', 'animated']) +@pytest.mark.parametrize('shape', list(GRIDS), ids=GRID_IDS) +def test_3d_shared_labels_are_drawn_on_the_outer_panels(shape, animated): + n, lowest, _, rightmost = GRIDS[shape] + fig = _plot(_frames(n), animated, panels=shape) + # the floor axes: under the lowest panel of each column + assert _carriers(fig, n, 'x') == lowest + assert _carriers(fig, n, 'y') == lowest + # the vertical axis: once per row, on the panel at the end of the row + # the z label is drawn toward (the cube's right at the default view) + assert _carriers(fig, n, 'z') == rightmost + for ax in fig.axes[:n]: + drawn = _drawn(ax) + assert drawn == {key: {'x': 'alpha', 'y': 'beta', + 'z': 'gamma'}[key] for key in drawn} + + +@pytest.mark.parametrize('azim', [-60, 30, 120, 210]) +def test_the_z_label_goes_to_the_end_of_the_row_it_is_drawn_toward(azim): + """matplotlib draws a cube's z label at its left or its right edge, + depending on the view; the row's one z label is on the panel at that + end of the row, so it sits at the grid's outer edge.""" + fig = hyp.plot(_frames(4), panels=(2, 2), azim=azim, show=False) + carriers = _carriers(fig, 4, 'z') + assert carriers in ({0, 2}, {1, 3}) + renderer = _draw(fig) + for i in carriers: + ax = fig.axes[i] + label = ax.zaxis.label.get_window_extent(renderer) + cube = _cube_box(ax) + center = 0.5 * (cube.x0 + cube.x1) + drawn_right = 0.5 * (label.x0 + label.x1) > center + assert drawn_right == (i % 2 == 1), (azim, i) + if azim == -60: + assert carriers == {1, 3} + + +def test_static_and_animated_grids_carry_the_same_labels(): + for ndims, cols in ((2, ('alpha', 'beta')), + (3, ('alpha', 'beta', 'gamma'))): + data = _frames(5, cols) + static = _plot(data, False, ndims=ndims, panels=(2, 3)) + moving = _plot(data, True, ndims=ndims, panels=(2, 3)) + assert ([_drawn(ax) for ax in static.axes[:5]] + == [_drawn(ax) for ax in moving.axes[:5]]) + + +def test_an_animated_grid_keeps_its_labels_on_every_frame(): + anim = hyp.plot(_frames(4), panels=(2, 2), **ANIM) + first = None + for frame in range(anim.n_frames): + anim.draw_frame(frame) + drawn = [_drawn(ax) for ax in anim.figure.axes[:4]] + first = drawn if first is None else first + assert drawn == first, frame + assert first == [{}, {'z': 'gamma'}, {'x': 'alpha', 'y': 'beta'}, + {'x': 'alpha', 'y': 'beta', 'z': 'gamma'}] + + +@pytest.mark.parametrize('animated', [False, True], + ids=['static', 'animated']) +def test_labels_that_differ_in_a_column_or_row_are_all_kept(animated): + """Column 0's x labels differ (both kept), column 1's agree (bottom + only); row 0's y labels differ (both kept), row 1's agree (left + only).""" + names = [('a', 'p'), ('b', 'q'), ('A', 'r'), ('b', 'r')] + data = [pd.DataFrame(_walk(i, cols=2), columns=list(cols)) + for i, cols in enumerate(names)] + fig = _plot(data, animated, ndims=2, panels=(2, 2), **OWN) + assert [_drawn(ax) for ax in fig.axes[:4]] == [ + {'x': 'a', 'y': 'p'}, {'y': 'q'}, + {'x': 'A', 'y': 'r'}, {'x': 'b'}] + + +def test_3d_labels_that_differ_are_all_kept(): + names = [('a', 'b', 'c'), ('a', 'b', 'C'), + ('a', 'B', 'c'), ('a', 'b', 'c')] + data = [pd.DataFrame(_walk(i), columns=list(cols)) + for i, cols in enumerate(names)] + fig = hyp.plot(data, panels=(2, 2), show=False, **OWN) + assert [_drawn(ax) for ax in fig.axes[:4]] == [ + # x agrees in both columns; y differs in column 0; z differs in + # row 0 and agrees in row 1 + {'y': 'b', 'z': 'c'}, {'z': 'C'}, + {'x': 'a', 'y': 'B'}, {'x': 'a', 'y': 'b', 'z': 'c'}] + + +def test_a_panel_without_a_label_makes_its_column_differ(): + """A column whose panels are not all labeled alike shares nothing: + the labeled panels keep their labels, the unlabeled one has none.""" + data = [pd.DataFrame(_walk(0, cols=2), columns=['a', 'b']), + _walk(1, cols=2), + pd.DataFrame(_walk(2, cols=2), columns=['a', 'b']), + pd.DataFrame(_walk(3, cols=2), columns=['a', 'b'])] + fig = hyp.plot(data, ndims=2, panels=(2, 2), show=False) + assert [_drawn(ax) for ax in fig.axes[:4]] == [ + # column 0 agrees on x (bottom only); column 1 does not; row 0 + # does not agree on y; row 1 does (left only) + {'y': 'b'}, {}, {'x': 'a', 'y': 'b'}, {'x': 'a'}] + + +def test_every_panel_is_labeled_when_every_panel_differs(): + """The existing way to label every panel: labels that are the + panels' own (here each DataFrame's own column names).""" + data = [pd.DataFrame(_walk(i, cols=2), columns=[f'x{i}', f'y{i}']) + for i in range(4)] + for animated in (False, True): + fig = _plot(data, animated, ndims=2, panels=(2, 2), **OWN) + assert [_drawn(ax) for ax in fig.axes[:4]] == [ + {'x': f'x{i}', 'y': f'y{i}'} for i in range(4)] + + +@pytest.mark.parametrize('animated', [False, True], + ids=['static', 'animated']) +def test_explicit_labels_are_shared_labels(animated): + arrays = [_walk(i) for i in range(4)] + fig = _plot(arrays, animated, panels=(2, 2), xlabel='one', + ylabel='two', zlabel='three') + assert [_drawn(ax) for ax in fig.axes[:4]] == [ + {}, {'z': 'three'}, {'x': 'one', 'y': 'two'}, + {'x': 'one', 'y': 'two', 'z': 'three'}] + flat = _plot([a[:, :2] for a in arrays], animated, ndims=2, + panels=(2, 2), xlabel='one', ylabel='two') + assert [_drawn(ax) for ax in flat.axes[:4]] == [ + {'y': 'two'}, {}, {'x': 'one', 'y': 'two'}, {'x': 'one'}] + + +def test_an_explicit_label_beside_derived_ones(): + """`xlabel=` is the whole grid's; the y labels are each panel's own + column name and differ in row 0 only.""" + names = [('a', 'p'), ('b', 'q'), ('c', 'r'), ('d', 'r')] + data = [pd.DataFrame(_walk(i, cols=2), columns=list(cols)) + for i, cols in enumerate(names)] + fig = hyp.plot(data, ndims=2, panels=(2, 2), xlabel='time', + show=False, **OWN) + assert [_drawn(ax) for ax in fig.axes[:4]] == [ + {'y': 'p'}, {'y': 'q'}, {'x': 'time', 'y': 'r'}, {'x': 'time'}] + + +def test_empty_labels_draw_nothing(): + fig = hyp.plot(_frames(4), panels=(2, 2), xlabel='', ylabel='', + zlabel='', show=False) + assert [_drawn(ax) for ax in fig.axes[:4]] == [{}, {}, {}, {}] + + +def test_one_label_dropped_the_others_shared(): + fig = hyp.plot(_frames(4), panels=(2, 2), ylabel='', show=False) + assert [_drawn(ax) for ax in fig.axes[:4]] == [ + {}, {'z': 'gamma'}, {'x': 'alpha'}, {'x': 'alpha', 'z': 'gamma'}] + + +@pytest.mark.parametrize('animated', [False, True], + ids=['static', 'animated']) +def test_series_panels_follow_the_2d_rule(animated): + """``ndims=1``: the x label is the index's name and the y label the + series' name, both derived by each panel's own call.""" + index = pd.Index(np.arange(24), name='trial') + data = [pd.DataFrame({'signal': _walk(i, cols=1)[:, 0]}, index=index) + for i in range(4)] + fig = _plot(data, animated, ndims=1, panels=(2, 2)) + assert [_drawn(ax) for ax in fig.axes[:4]] == [ + {'y': 'signal'}, {}, {'x': 'trial', 'y': 'signal'}, + {'x': 'trial'}] + + +def test_reducer_list_panels_share_explicit_labels(): + fig = hyp.plot([_walk(i, cols=6) for i in range(3)], ndims=2, + reduce=['PCA', 'IncrementalPCA', 'FastICA'], + panels=(1, 3), xlabel='first', ylabel='second', + show=False) + assert [_drawn(ax) for ax in fig.axes[:3]] == [ + {'x': 'first', 'y': 'second'}, {'x': 'first'}, {'x': 'first'}] + + +def test_the_subplots_alias_follows_the_same_rule(): + fig = hyp.plot(_frames(4, ('alpha', 'beta')), ndims=2, + subplots=(2, 2), show=False) + assert [_drawn(ax) for ax in fig.axes[:4]] == [ + {'y': 'beta'}, {}, {'x': 'alpha', 'y': 'beta'}, {'x': 'alpha'}] + + +def test_tick_labels_are_left_alone(): + """Tick labels are not part of the rule: with ``axis_scale='data'`` + every panel keeps its own ticks.""" + fig = hyp.plot(_frames(4, ('alpha', 'beta')), ndims=2, panels=(2, 2), + axis_scale='data', show=False) + _draw(fig) + for ax in fig.axes[:4]: + assert [t.get_text() for t in ax.get_xticklabels() if t.get_text()] + assert [t.get_text() for t in ax.get_yticklabels() if t.get_text()] + assert _carriers(fig, 4, 'x') == {2, 3} + assert _carriers(fig, 4, 'y') == {0, 2} + + +# -------------------------------------------------------------------------- +# the one decision function +# -------------------------------------------------------------------------- + +def test_the_decision_function_on_plain_texts(): + from hypertools.plot.plot import _outer_label_panels + same = [{'x': 'a', 'y': 'b'}] * 5 + assert _outer_label_panels(same, 2, 3, ndims=2) == [ + {'y'}, set(), {'x'}, {'x', 'y'}, {'x'}] + cube = [{'x': 'a', 'y': 'b', 'z': 'c'}] * 5 + assert _outer_label_panels(cube, 2, 3, ndims=3, z_side='right') == [ + set(), set(), {'x', 'y', 'z'}, {'x', 'y'}, {'x', 'y', 'z'}] + assert _outer_label_panels(cube, 2, 3, ndims=3, z_side='left') == [ + {'z'}, set(), {'x', 'y'}, {'x', 'y', 'z'}, {'x', 'y'}] + # None and '' are both "no label"; a column that mixes a label and + # none differs + mixed = [{'x': 'a', 'y': None}, {'x': '', 'y': 'b'}, + {'x': 'a', 'y': 'b'}, {'x': 'a', 'y': 'b'}] + assert _outer_label_panels(mixed, 2, 2, ndims=2) == [ + set(), {'y'}, {'x', 'y'}, {'x'}] + + +# -------------------------------------------------------------------------- +# the plotly grid +# -------------------------------------------------------------------------- + +def _plotly_titles(bundle, ndims): + """Per panel, the axis titles the plotly grid draws.""" + out = [] + for axes in bundle['axes']: + if ndims == 3: + named = {'x': axes.xaxis, 'y': axes.yaxis, 'z': axes.zaxis} + else: + named = {'x': axes[0], 'y': axes[1]} + out.append({name: axis.title.text for name, axis in named.items() + if axis.visible is not False and axis.title.text}) + # a 3-D grid's first-column z titles are written in the left margin + for note in bundle['fig'].layout.annotations: + for i in range(len(out)): + if note.name == PLOTLY_Z_TITLE_NAME.format(i): + assert 'z' not in out[i] + out[i]['z'] = note.text + return out + + +@pytest.mark.parametrize('shape', [(2, 2), (2, 3), (1, 4)], + ids=['2x2', '2x3-with-5', '1x4']) +def test_plotly_2d_grid_draws_shared_titles_on_the_outer_panels(shape): + n, lowest, leftmost, _ = GRIDS[shape] + bundle = hyp.plot(_frames(n, ('alpha', 'beta')), ndims=2, panels=shape, + backend='plotly', show=False, return_model=True) + titles = _plotly_titles(bundle, 2) + assert {i for i, t in enumerate(titles) if 'x' in t} == lowest + assert {i for i, t in enumerate(titles) if 'y' in t} == leftmost + assert all(set(t.values()) <= {'alpha', 'beta'} for t in titles) + + +@pytest.mark.parametrize('shape', [(2, 2), (2, 3), (1, 4)], + ids=['2x2', '2x3-with-5', '1x4']) +def test_plotly_3d_grid_draws_shared_titles_on_the_outer_panels(shape): + from hypertools.plot.plot import _PLOTLY_Z_LABEL_SIDE + n, lowest, leftmost, rightmost = GRIDS[shape] + bundle = hyp.plot(_frames(n), panels=shape, backend='plotly', + show=False, return_model=True) + titles = _plotly_titles(bundle, 3) + assert {i for i, t in enumerate(titles) if 'x' in t} == lowest + assert {i for i, t in enumerate(titles) if 'y' in t} == lowest + # plotly writes a scene's z title LEFT of its cube: one per row, at + # the row's left end + assert _PLOTLY_Z_LABEL_SIDE == 'left' + assert {i for i, t in enumerate(titles) if 'z' in t} == leftmost + assert all(t['z'] == 'gamma' for t in titles if 'z' in t) + + +@pytest.mark.parametrize('size', [None, [8, 6]], ids=['default', 'sized']) +def test_plotly_3d_grid_z_titles_are_written_in_the_left_margin(size): + """A scene's z title falls outside a grid cell's scene and is clipped + away, so the first column's are written beside the grid, in room the + default figure is widened by (an explicit `size=` is kept).""" + plain = hyp.plot([_walk(i) for i in range(4)], panels=(2, 2), + backend='plotly', show=False, size=size) + fig = hyp.plot(_frames(4), panels=(2, 2), backend='plotly', + show=False, size=size) + notes = {note.name: note for note in fig.layout.annotations + if note.name and note.name.startswith('hyp_panel_ztitle_')} + assert sorted(notes) == ['hyp_panel_ztitle_0', 'hyp_panel_ztitle_2'] + assert fig.layout.margin.l >= 30 + if size is None: + assert fig.layout.width == plain.layout.width + ( + fig.layout.margin.l - plain.layout.margin.l) + else: + assert (fig.layout.width, fig.layout.height) == (800, 600) + plot_w = fig.layout.width - fig.layout.margin.l - fig.layout.margin.r + for i, key in ((0, 'scene'), (2, 'scene3')): + note = notes[f'hyp_panel_ztitle_{i}'] + domain = fig.layout[key].domain + assert note.text == 'gamma' and note.textangle == -90 + # left of its scene, inside the canvas, level with its middle + assert note.x == domain.x[0] and note.xshift < 0 + assert fig.layout.margin.l + note.x * plot_w + note.xshift > 5 + assert note.y == pytest.approx(0.5 * (domain.y[0] + domain.y[1])) + assert not fig.layout[key].zaxis.title.text + + +def test_plotly_grid_keeps_labels_that_differ(): + names = [('a', 'p'), ('b', 'q'), ('A', 'r'), ('b', 'r')] + data = [pd.DataFrame(_walk(i, cols=2), columns=list(cols)) + for i, cols in enumerate(names)] + bundle = hyp.plot(data, ndims=2, panels=(2, 2), backend='plotly', + show=False, return_model=True, **OWN) + assert _plotly_titles(bundle, 2) == [ + {'x': 'a', 'y': 'p'}, {'y': 'q'}, + {'x': 'A', 'y': 'r'}, {'x': 'b'}] + + +def test_plotly_and_matplotlib_grids_agree_in_2d(): + data = _frames(5, ('alpha', 'beta')) + fig = hyp.plot(data, ndims=2, panels=(2, 3), show=False) + bundle = hyp.plot(data, ndims=2, panels=(2, 3), backend='plotly', + show=False, return_model=True) + assert _plotly_titles(bundle, 2) == [_drawn(ax) for ax in fig.axes[:5]] + + +# -------------------------------------------------------------------------- +# where the kept labels are drawn +# -------------------------------------------------------------------------- + +def _assert_labels_in_their_cells(fig, n, shape, where=None): + """Every drawn axis label is on the canvas, inside its own panel's + grid cell, and clear of every other panel's drawing, title and + labels, and of the shared legend, colorbar and caption.""" + renderer = _draw(fig) + width, height = fig.canvas.get_width_height() + panels = fig.axes[:n] + nrows, ncols = shape + furniture = [legend.get_window_extent(renderer) + for legend in fig.legends] + furniture += [ax.get_tightbbox(renderer) for ax in fig.axes + if ax.get_gid() == SHARED_COLORBAR_GID] + furniture += [text.get_window_extent(renderer) for text in fig.texts + if text.get_gid() == CAPTION_GID] + labels = {} + for i, ax in enumerate(panels): + labels[i] = [ + getattr(ax, name + 'axis').label.get_window_extent(renderer) + for name in _drawn(ax)] + assert any(labels.values()) + # a panel's cell: half way to the next panels' axes on its inner + # sides, and out to the canvas' edge on its outer ones (where the + # shared legend, colorbar and caption are checked separately) + boxes = [ax.get_window_extent(renderer) for ax in panels] + for i, ax in enumerate(panels): + row, col = divmod(i, ncols) + left = 0.0 if col == 0 else 0.5 * (boxes[i - 1].x1 + boxes[i].x0) + right = (width if col == ncols - 1 or i + 1 >= n + else 0.5 * (boxes[i].x1 + boxes[i + 1].x0)) + top = (height if row == 0 + else 0.5 * (boxes[i - ncols].y0 + boxes[i].y1)) + bottom = (0.0 if row == nrows - 1 or i + ncols >= n + else 0.5 * (boxes[i].y0 + boxes[i + ncols].y1)) + for label in labels[i]: + tag = (where, i) + assert label.x0 >= -0.5 and label.x1 <= width + 0.5, tag + assert label.y0 >= -0.5 and label.y1 <= height + 0.5, tag + assert label.x0 >= left - 1.0 and label.x1 <= right + 1.0, tag + assert label.y0 >= bottom - 1.0 and label.y1 <= top + 1.0, tag + label = _shrunk(label) + for box in furniture: + assert not label.overlaps(box), tag + for j, other in enumerate(panels): + if j == i: + continue + theirs = (_cube_box(other) if hasattr(other, 'get_proj') + else boxes[j]) + assert not label.overlaps(theirs), (tag, j) + if other.get_title(): + assert not label.overlaps( + other.title.get_window_extent(renderer)), (tag, j) + for one in labels[j]: + assert not label.overlaps(_shrunk(one)), (tag, j) + + +FURNITURE = [ + {}, dict(legend=True), + dict(legend=True, caption='a caption under the whole grid', + title=['one', 'two', 'three', 'four', 'five']), + dict(hue='rows', colorbar=True, caption='a caption'), +] +FURNITURE_IDS = ['bare', 'legend', 'legend-caption-titles', + 'colorbar-caption'] + + +def _extras(extras, n, rows=24): + """`extras` cut to `n` panels (titles; a per-row hue for a colorbar).""" + out = dict(extras) + if 'title' in out: + out['title'] = out['title'][:n] + if out.get('hue') == 'rows': + out['hue'] = [np.arange(rows)] * n + return out + + +@pytest.mark.parametrize('extras', FURNITURE, ids=FURNITURE_IDS) +@pytest.mark.parametrize('ndims', [2, 3]) +@pytest.mark.parametrize('shape', [(1, 4), (2, 2), (2, 3)], + ids=['1x4', '2x2', '2x3-with-5']) +def test_static_labels_stay_in_their_cells(shape, ndims, extras): + n = GRIDS[shape][0] + cols = ('first axis', 'second axis', 'third axis')[:ndims] + fig = hyp.plot(_frames(n, cols), ndims=ndims, panels=shape, show=False, + **_extras(extras, n)) + _assert_labels_in_their_cells(fig, n, shape) + + +@pytest.mark.parametrize('extras', [FURNITURE[0], FURNITURE[2], + FURNITURE[3]], + ids=['bare', 'legend-caption-titles', + 'colorbar-caption']) +@pytest.mark.parametrize('ndims', [2, 3]) +@pytest.mark.parametrize('shape', [(1, 4), (2, 2), (2, 3)], + ids=['1x4', '2x2', '2x3-with-5']) +def test_animated_labels_stay_in_their_cells_through_a_full_rotation( + shape, ndims, extras): + n = GRIDS[shape][0] + cols = ('first axis', 'second axis', 'third axis')[:ndims] + anim = hyp.plot(_frames(n, cols), ndims=ndims, panels=shape, + rotations=1, **dict(ANIM, frame_rate=12, + **_extras(extras, n))) + assert anim.n_frames >= 12 + for frame in range(anim.n_frames): + anim.draw_frame(frame) + _assert_labels_in_their_cells(anim.figure, n, shape, frame) + + +# -------------------------------------------------------------------------- +# the room of labels that are not drawn is given back +# -------------------------------------------------------------------------- + +def _cube_share(ax): + """A cube's drawn width as a share of its axes' width.""" + return _cube_box(ax).width / ax.get_window_extent().width + + +LONG = ('first axis', 'second axis', 'third axis') + + +@pytest.mark.parametrize('shape', [(1, 4), (2, 2), (2, 3)], + ids=['1x4', '2x2', '2x3-with-5']) +@pytest.mark.parametrize('mode', ['static', 'still', 'rotating']) +def test_the_cubes_of_a_grid_are_all_drawn_the_same_size(shape, mode): + """The panels are read side by side: the panels that draw labels do + not get a smaller cube than the ones that draw none.""" + n = GRIDS[shape][0] + extra = {'static': {}, 'still': dict(ANIM, rotations=0), + 'rotating': dict(ANIM, rotations=1)}[mode] + fig = _figure(hyp.plot(_frames(n, LONG), panels=shape, + **dict(dict(show=False), **extra))) + _draw(fig) + assert len({frozenset(_drawn(ax)) for ax in fig.axes[:n]}) > 1 + widths = [_cube_box(ax).width for ax in fig.axes[:n]] + assert max(widths) - min(widths) <= 0.01 * max(widths), widths + + +@pytest.mark.parametrize('animated', [False, True], + ids=['static', 'animated']) +@pytest.mark.parametrize('shape', [(1, 4), (2, 2), (2, 3)], + ids=['1x4', '2x2', '2x3-with-5']) +def test_3d_cubes_get_the_room_of_the_undrawn_labels_back(shape, animated): + """Seen from one view (a static grid, or ``rotations=0``), the outer + panels' labels hang toward the grid's outer edge, where the figure + gives them room, so no cube is drawn smaller for the z label and the + cubes keep most of the size they have without any label -- they were + all drawn at 65-70% of it when every panel drew every label. (What + still costs a little is a floor label of an inner column, which + reaches sideways toward the next panel.)""" + n = GRIDS[shape][0] + extra = dict(rotations=0) if animated else {} + plain = _plot([_walk(i) for i in range(n)], animated, panels=shape, + **extra) + labeled = _plot(_frames(n), animated, panels=shape, **extra) + short = _plot(_frames(n, ('x', 'y', 'z')), animated, panels=shape, + **extra) + _draw(plain), _draw(labeled), _draw(short) + for a, b, c in zip(plain.axes[:n], labeled.axes[:n], short.axes[:n]): + assert _cube_share(b) >= 0.9 * _cube_share(a) + assert _cube_share(c) >= 0.99 * _cube_share(a) + # the room is added at the outer edges; the panels keep their size + assert np.all(labeled.get_size_inches() >= plain.get_size_inches()) + assert np.all(labeled.get_size_inches() + <= plain.get_size_inches() + [1.0, 0.6]) + for a, b in zip(plain.axes[:n], labeled.axes[:n]): + size_a = a.get_window_extent().size + size_b = b.get_window_extent().size + assert np.allclose(size_a, size_b, rtol=0.02), (size_a, size_b) + + +def test_labels_kept_on_inner_panels_are_fitted_inside_their_cells(): + """Labels that differ are drawn on inner panels too; there they have + no outer edge to hang toward, so the grid's cubes are drawn smaller + (all of them alike) until those labels fit their own cells.""" + names = ('alpha', 'beta', 'gamma') + data = [pd.DataFrame(_walk(i), columns=[f'{c} {i}' for c in names]) + for i in range(4)] + own = hyp.plot(data, panels=(2, 2), show=False, **OWN) + shared = hyp.plot(_frames(4, names), panels=(2, 2), show=False) + _draw(own), _draw(shared) + assert all(len(_drawn(ax)) == 3 for ax in own.axes[:4]) + assert _cube_share(own.axes[0]) < 0.9 * _cube_share(shared.axes[0]) + _assert_labels_in_their_cells(own, 4, (2, 2)) + + +def test_3d_figure_enlargement_reads_the_labels_actually_drawn(): + """The default figure grows for the labels that are drawn, where + they are drawn: a grid with shared labels is the unlabeled grid plus + the outer labels' room at its edges, with larger cubes than the same + grid with every panel's own (different) labels on every panel.""" + cols = ('first axis', 'second axis', 'third axis') + shared = hyp.plot(_frames(4, cols), panels=(2, 2), show=False, **OWN) + own = hyp.plot( + [pd.DataFrame(_walk(i), columns=[f'{c} {i}' for c in cols]) + for i in range(4)], panels=(2, 2), show=False, **OWN) + plain = hyp.plot([_walk(i) for i in range(4)], panels=(2, 2), + show=False) + assert tuple(plain.get_size_inches()) == (6.4, 6.4) + size = shared.get_size_inches() + assert 6.4 <= size[0] <= 6.4 + 1.0 and 6.4 <= size[1] <= 6.4 + 0.6 + _draw(shared), _draw(own) + for a, b in zip(shared.axes[:4], own.axes[:4]): + assert _cube_box(a).width > 1.05 * _cube_box(b).width + + +def test_a_small_explicit_size_warns_only_for_labels_that_are_drawn(): + """A static 3-D grid at an explicit size too small for labels on every + panel: with shared labels the warning is decided by the panels that + draw them, and a grid whose labels are all dropped never warns.""" + import warnings + with warnings.catch_warnings(): + warnings.simplefilter('error') + hyp.plot(_frames(4), panels=(2, 2), size=[4, 4], xlabel='', + ylabel='', zlabel='', show=False) + with pytest.warns(UserWarning, match='larger size='): + hyp.plot(_frames(4), panels=(1, 4), size=[3, 1], show=False) + + +def test_2d_inner_panels_get_their_label_room_back(): + """With the x labels on the bottom row only, a 2 x 2 grid's panels + are taller than the same grid's with a label under every panel.""" + shared = hyp.plot(_frames(4, ('alpha', 'beta')), ndims=2, + panels=(2, 2), show=False, **OWN) + own = hyp.plot( + [pd.DataFrame(_walk(i, cols=2), columns=[f'alpha{i}', f'beta{i}']) + for i in range(4)], ndims=2, panels=(2, 2), show=False, **OWN) + assert tuple(shared.get_size_inches()) == tuple(own.get_size_inches()) + for a, b in zip(shared.axes[:4], own.axes[:4]): + assert a.get_position().height > b.get_position().height + 0.005 + assert a.get_position().width > b.get_position().width + 0.005 + + +# -------------------------------------------------------------------------- +# one layout path: static == animated with rotations=0 +# -------------------------------------------------------------------------- + +LAYOUTS = { + 'bare': {}, + 'titles': dict(title=['one', 'two', 'three', 'four', 'five']), + 'legend': dict(legend=True), + 'colorbar': dict(hue='rows', colorbar=True), + 'caption': dict(caption='a caption under the whole grid'), + 'everything': dict(legend=True, caption='a caption', + title=['one', 'two', 'three', 'four', 'five']), +} + + +def _layout(fig, n): + """A grid's figure size and its panels' axes positions.""" + return (np.array(fig.get_size_inches()), + np.array([ax.get_position().bounds for ax in fig.axes[:n]])) + + +@pytest.mark.parametrize('labels', [False, True], + ids=['unlabeled', 'labeled']) +@pytest.mark.parametrize('ndims', [2, 3]) +@pytest.mark.parametrize('layout', list(LAYOUTS)) +@pytest.mark.parametrize('shape', [(1, 4), (2, 2), (2, 3)], + ids=['1x4', '2x2', '2x3-with-5']) +def test_static_layout_is_the_animated_layout_without_rotation( + shape, layout, ndims, labels): + """A static grid and frame 0 of the same grid animated with + ``rotations=0`` have the same figure size, the same axes positions, + the same labels, the same shared legend/colorbar/caption boxes and (in + 3-D) the same cubes.""" + n = GRIDS[shape][0] + cols = ('first axis', 'second axis', 'third axis')[:ndims] + data = (_frames(n, cols) if labels + else [_walk(i, cols=ndims) for i in range(n)]) + extras = _extras(LAYOUTS[layout], n) + static = hyp.plot(data, ndims=ndims, panels=shape, show=False, + **extras) + anim = hyp.plot(data, ndims=ndims, panels=shape, rotations=0, + **dict(ANIM, **extras)) + anim.draw_frame(0) + moving = anim.figure + size_a, boxes_a = _layout(static, n) + size_b, boxes_b = _layout(moving, n) + assert np.allclose(size_a, size_b, atol=1e-6), (size_a, size_b) + assert np.allclose(boxes_a, boxes_b, atol=1e-6) + assert ([_drawn(ax) for ax in static.axes[:n]] + == [_drawn(ax) for ax in moving.axes[:n]]) + ra, rb = _draw(static), _draw(moving) + + def _furniture(fig, renderer): + boxes = [legend.get_window_extent(renderer).bounds + for legend in fig.legends + if legend.get_gid() == SHARED_LEGEND_GID] + boxes += [ax.get_position().bounds for ax in fig.axes + if ax.get_gid() == SHARED_COLORBAR_GID] + boxes += [text.get_window_extent(renderer).bounds + for text in fig.texts if text.get_gid() == CAPTION_GID] + return np.array(boxes) + + fa, fb = _furniture(static, ra), _furniture(moving, rb) + assert fa.shape == fb.shape + assert np.allclose(fa, fb, atol=0.5) + if ndims == 3: + for a, b in zip(static.axes[:n], moving.axes[:n]): + assert np.allclose(_cube_box(a).bounds, _cube_box(b).bounds, + atol=0.5) + for name in _drawn(a): + assert np.allclose( + getattr(a, name + 'axis').label + .get_window_extent(ra).bounds, + getattr(b, name + 'axis').label + .get_window_extent(rb).bounds, atol=0.5) + + +@pytest.mark.parametrize('layout', ['bare', 'everything']) +@pytest.mark.parametrize('labels', [False, True], + ids=['unlabeled', 'labeled']) +def test_a_2d_grid_is_laid_out_the_same_static_or_rotating(layout, labels): + """2-D panels have no camera, so `rotations=` changes nothing.""" + data = (_frames(4, ('alpha', 'beta')) if labels + else [_walk(i, cols=2) for i in range(4)]) + extras = _extras(LAYOUTS[layout], 4) + static = hyp.plot(data, ndims=2, panels=(2, 2), show=False, **extras) + moving = hyp.plot(data, ndims=2, panels=(2, 2), rotations=1, + **dict(ANIM, **extras)).figure + size_a, boxes_a = _layout(static, 4) + size_b, boxes_b = _layout(moving, 4) + assert np.allclose(size_a, size_b, atol=1e-6) + assert np.allclose(boxes_a, boxes_b, atol=1e-6) + + +@pytest.mark.parametrize('layout', ['bare', 'everything']) +def test_rotation_changes_only_the_cubes_of_an_unlabeled_3d_grid(layout): + """With rotation, an unlabeled 3-D grid keeps the static grid's + figure size and axes positions; only each cube is drawn smaller, by + the clearance its swept extent needs.""" + data = [_walk(i) for i in range(4)] + extras = _extras(LAYOUTS[layout], 4) + static = hyp.plot(data, panels=(2, 2), show=False, **extras) + anim = hyp.plot(data, panels=(2, 2), rotations=1, + **dict(ANIM, **extras)) + anim.draw_frame(0) + size_a, boxes_a = _layout(static, 4) + size_b, boxes_b = _layout(anim.figure, 4) + assert np.allclose(size_a, size_b, atol=1e-6) + assert np.allclose(boxes_a, boxes_b, atol=1e-6) + _draw(static), _draw(anim.figure) + for a, b in zip(static.axes[:4], anim.figure.axes[:4]): + assert _cube_box(b).width <= _cube_box(a).width + 0.5 + assert _cube_box(b).width >= 0.8 * _cube_box(a).width diff --git a/tests/test_panels_shared_legend_colors.py b/tests/test_panels_shared_legend_colors.py index 99ecadc54..55ae02d38 100644 --- a/tests/test_panels_shared_legend_colors.py +++ b/tests/test_panels_shared_legend_colors.py @@ -205,7 +205,12 @@ def test_shared_legend_clears_a_3d_panels_axis_labels(): labels = [axis.label.get_window_extent(renderer) for ax in grid['axes'] for axis in ax._axis_map.values() if axis.label.get_text()] - assert len(labels) == 9 + # CHANGED for 1.2.0 (owner decision 2026-11-22): shared axis labels are + # drawn on the outer panels only -- in this 1 x 3 row the two floor + # labels under every panel and the z label on the right-most one, + # which is the one beside the legend (this asserted all 9) + assert len(labels) == 7 + assert grid['axes'][-1].zaxis.label.get_text() == 'third axis' for box in labels: assert not box.overlaps(legend) diff --git a/tests/test_plot_panels.py b/tests/test_plot_panels.py index 9806af797..b191b59c3 100644 --- a/tests/test_plot_panels.py +++ b/tests/test_plot_panels.py @@ -479,7 +479,11 @@ def test_plotly_2d_panels_keep_the_unit_frame_and_column_labels(): assert list(fig.layout.xaxis.range) == [-UNIT_FRAME_LIMIT, UNIT_FRAME_LIMIT] assert list(fig.layout.yaxis2.range) == [-UNIT_FRAME_LIMIT, UNIT_FRAME_LIMIT] assert fig.layout.xaxis2.title.text == 'a' - assert fig.layout.yaxis2.title.text == 'b' + # CHANGED for 1.2.0 (owner decision 2026-11-22): shared axis labels are + # drawn on the outer panels only -- in this 1 x 2 row the y title on + # the left-most panel alone (this asserted 'b' on the second panel) + assert fig.layout.yaxis.title.text == 'b' + assert not fig.layout.yaxis2.title.text assert fig.layout.xaxis2.showticklabels is False # one frame square per panel, each on its own cell's axes assert sorted(s.xref for s in fig.layout.shapes) == ['x', 'x2'] diff --git a/tests/test_plot_panels_fit.py b/tests/test_plot_panels_fit.py index 8399a4368..915195fb6 100644 --- a/tests/test_plot_panels_fit.py +++ b/tests/test_plot_panels_fit.py @@ -93,8 +93,12 @@ def test_panels_keep_the_labels_a_single_call_derives(self): assert want == ('x', 'y') fig = hyp.plot([a, b], panels=True, ndims=2, show=False) try: - for ax in fig.axes: - assert (ax.get_xlabel(), ax.get_ylabel()) == want + # CHANGED for 1.2.0 (owner decision 2026-11-22): shared axis + # labels are drawn on the outer panels only -- in this 1 x 2 + # row the x label under both panels, the y label on the + # left-most (this asserted both labels on every panel) + assert [(ax.get_xlabel(), ax.get_ylabel()) for ax in fig.axes] \ + == [want, (want[0], '')] finally: plt.close(fig) @@ -110,8 +114,11 @@ def test_labels_follow_the_column_names(self): pd.DataFrame({'year': t, 'temp': np.cos(t)})] fig = hyp.plot(data, panels=True, ndims=2, show=False) try: + # CHANGED for 1.2.0 (owner decision 2026-11-22): shared axis + # labels are drawn on the outer panels only (this asserted + # ('year', 'temp') on both panels of the row) assert [(ax.get_xlabel(), ax.get_ylabel()) for ax in fig.axes] \ - == [('year', 'temp'), ('year', 'temp')] + == [('year', 'temp'), ('year', '')] finally: plt.close(fig) @@ -121,7 +128,10 @@ def test_explicit_labels_still_win(self): show=False) try: assert all(ax.get_xlabel() == 'mine' for ax in fig.axes) - assert all(ax.get_ylabel() == 'y' for ax in fig.axes) + # CHANGED for 1.2.0 (owner decision 2026-11-22): shared axis + # labels are drawn on the outer panels only (this asserted the + # derived 'y' on both panels of the row) + assert [ax.get_ylabel() for ax in fig.axes] == ['y', ''] finally: plt.close(fig) @@ -137,8 +147,11 @@ def test_independent_fit_derives_them_too(self): fig = hyp.plot([a, b], panels=True, panel_fit='independent', ndims=2, show=False) try: + # CHANGED for 1.2.0 (owner decision 2026-11-22): shared axis + # labels are drawn on the outer panels only (this asserted + # ('x', 'y') on both panels of the row) assert [(ax.get_xlabel(), ax.get_ylabel()) for ax in fig.axes] \ - == [('x', 'y'), ('x', 'y')] + == [('x', 'y'), ('x', '')] finally: plt.close(fig) @@ -348,7 +361,10 @@ def test_P2_series_mode_panels_keep_dates_and_the_column_name(panel_fit): if getattr(ln, '_hyp_forecast_role', None) is None] assert np.allclose(np.asarray(line.get_xdata(), dtype=float), date2num(frame.index.to_pydatetime())) - assert ax.get_ylabel() == 'val' + # CHANGED for 1.2.0 (owner decision 2026-11-22): shared axis labels + # are drawn on the outer panels only -- the column's name on the + # left-most panel of the row (this asserted 'val' on both panels) + assert [ax.get_ylabel() for ax in fig.axes] == ['val', ''] finally: plt.close(fig) diff --git a/tests/test_static_panel_grid_size.py b/tests/test_static_panel_grid_size.py index 732269297..785cfbeaa 100644 --- a/tests/test_static_panel_grid_size.py +++ b/tests/test_static_panel_grid_size.py @@ -230,9 +230,14 @@ def test_2d_grid_furniture_does_not_collide(shape, n, legend): renderer = _draw(fig) panels = [ax for ax in fig.axes[:n] if ax.get_visible()] assert len(panels) == n - for ax in panels: - assert ax.get_xlabel() == 'first axis' - assert ax.get_ylabel() == 'second axis' + # CHANGED for 1.2.0 (owner decision 2026-11-22): shared axis labels are + # drawn on the outer panels only -- the x label under the lowest panel + # of each column, the y label on the left-most panel of each row (this + # asserted both labels on every panel) + nrows, ncols = shape + for i, ax in enumerate(panels): + assert ax.get_xlabel() == ('first axis' if i + ncols >= n else '') + assert ax.get_ylabel() == ('second axis' if i % ncols == 0 else '') width, height = fig.canvas.get_width_height() furniture = [_furniture_boxes(ax, renderer) for ax in panels] for i, boxes in enumerate(furniture): From 8a054be4137ea8a632d96fbb92bfcac8b057df2c Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 09:04:53 -0500 Subject: [PATCH 35/58] test: outer-label tests pass rotations= to 3-D grids only (no ignored-keyword warnings) Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- tests/test_panel_outer_labels.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/tests/test_panel_outer_labels.py b/tests/test_panel_outer_labels.py index c89085f8d..fd5057349 100644 --- a/tests/test_panel_outer_labels.py +++ b/tests/test_panel_outer_labels.py @@ -562,9 +562,10 @@ def test_animated_labels_stay_in_their_cells_through_a_full_rotation( shape, ndims, extras): n = GRIDS[shape][0] cols = ('first axis', 'second axis', 'third axis')[:ndims] + turn = dict(rotations=1) if ndims == 3 else {} anim = hyp.plot(_frames(n, cols), ndims=ndims, panels=shape, - rotations=1, **dict(ANIM, frame_rate=12, - **_extras(extras, n))) + **dict(ANIM, frame_rate=12, **turn, + **_extras(extras, n))) assert anim.n_frames >= 12 for frame in range(anim.n_frames): anim.draw_frame(frame) @@ -735,8 +736,10 @@ def test_static_layout_is_the_animated_layout_without_rotation( extras = _extras(LAYOUTS[layout], n) static = hyp.plot(data, ndims=ndims, panels=shape, show=False, **extras) - anim = hyp.plot(data, ndims=ndims, panels=shape, rotations=0, - **dict(ANIM, **extras)) + # (`rotations=` is the 3-D camera's; a 2-D grid has one view anyway) + still = dict(rotations=0) if ndims == 3 else {} + anim = hyp.plot(data, ndims=ndims, panels=shape, + **dict(ANIM, **extras, **still)) anim.draw_frame(0) moving = anim.figure size_a, boxes_a = _layout(static, n) @@ -781,8 +784,9 @@ def test_a_2d_grid_is_laid_out_the_same_static_or_rotating(layout, labels): else [_walk(i, cols=2) for i in range(4)]) extras = _extras(LAYOUTS[layout], 4) static = hyp.plot(data, ndims=2, panels=(2, 2), show=False, **extras) - moving = hyp.plot(data, ndims=2, panels=(2, 2), rotations=1, - **dict(ANIM, **extras)).figure + with pytest.warns(UserWarning, match='no effect on 2-D animations'): + moving = hyp.plot(data, ndims=2, panels=(2, 2), rotations=1, + **dict(ANIM, **extras)).figure size_a, boxes_a = _layout(static, 4) size_b, boxes_b = _layout(moving, 4) assert np.allclose(size_a, size_b, atol=1e-6) From c7b6d0b27d2969df62e147e224427b6b3185a549 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 09:10:18 -0500 Subject: [PATCH 36/58] test: the default rotations=1 raises no warning on a 2-D grid Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- tests/test_panel_outer_labels.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tests/test_panel_outer_labels.py b/tests/test_panel_outer_labels.py index fd5057349..328fd78c5 100644 --- a/tests/test_panel_outer_labels.py +++ b/tests/test_panel_outer_labels.py @@ -784,9 +784,8 @@ def test_a_2d_grid_is_laid_out_the_same_static_or_rotating(layout, labels): else [_walk(i, cols=2) for i in range(4)]) extras = _extras(LAYOUTS[layout], 4) static = hyp.plot(data, ndims=2, panels=(2, 2), show=False, **extras) - with pytest.warns(UserWarning, match='no effect on 2-D animations'): - moving = hyp.plot(data, ndims=2, panels=(2, 2), rotations=1, - **dict(ANIM, **extras)).figure + moving = hyp.plot(data, ndims=2, panels=(2, 2), rotations=1, + **dict(ANIM, **extras)).figure size_a, boxes_a = _layout(static, 4) size_b, boxes_b = _layout(moving, 4) assert np.allclose(size_a, size_b, atol=1e-6) From ed4a491d1692a08c9c576312f222dbe67bff7eb8 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 09:44:52 -0500 Subject: [PATCH 37/58] fix: a panel grid resolves its colors in the panels' drawing mode, without drawing (GH #295) The grid-wide color resolution (`_resolve_grid_colors`) made the single-axes call of every dataset with a whitelist of arguments and drew a second full figure to read the colors back. It now forwards every argument but the analysis, the per-panel overlays and the figure's own (`_GRID_RESOLUTION_DROPPED_KWARGS`), and the call returns as soon as its colors, legend entries and colorbar are resolved (`resolve_only`): before any line is interpolated, any figure created or anything drawn. With no `hue=`, clusters, legend or colorbar there is nothing to resolve and no call is made at all. - An animated mixture clustering with `colorbar=` is resolved as the quantized groups the panels draw (it was resolved as the static continuous blend and refused); the panels draw each group in the grid's color for it, not in their own members' mean. - Categories are identified by themselves: a `legend=` list that gives two categories one name no longer collapses their colors. - A matrix `hue=` is resolved once: RGB is reduced and scaled over every panel's rows, and signed mixture weights are shifted by the grid's rule, so one hue row is one color in every panel. - Row-MultiIndex frames in a list are datasets like any other: each keeps its palette color. - `font=` reaches the grid's one colorbar. tests/test_panel_color_invariant.py draws 403 grid calls and their single-axes equivalents and compares every artist's color row by row. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/plot/plot.py | 461 +++++++++++++++++++++------- tests/test_panel_color_invariant.py | 315 +++++++++++++++++++ tests/test_panels_review_round3.py | 294 ++++++++++++++++++ 3 files changed, 952 insertions(+), 118 deletions(-) create mode 100644 tests/test_panel_color_invariant.py create mode 100644 tests/test_panels_review_round3.py diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index bbe6b7869..af7c45a5d 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -1688,6 +1688,39 @@ def _validate_hue_mode(hue_mode, color_reduce, hue=None): "reduce.") +def _nonnegative_mixture_rows(weights): + """A mixture-weight matrix as `colors.mat2colors` blends it: when ANY + finite row holds a negative entry, every finite row is shifted by its + own minimum (negative weights have no color meaning); otherwise the + matrix is returned as it is. Decided ONCE, for the whole matrix, so the + rows blend the same whether they are colored together or a `panels=` + grid hands each panel its own -- a panel whose rows happen to hold no + negative entry is still shifted when the grid's matrix is signed.""" + weights = np.asarray(weights, dtype=np.float64) + if weights.ndim != 2: + return weights + finite = np.isfinite(weights).all(axis=1) + if not finite.any() or weights[finite].min() >= 0: + return weights + shifted = weights.copy() + shifted[finite] -= shifted[finite].min(axis=1, keepdims=True) + return shifted + + +def _blend_groups(blended, shared=None): + """`colors.colors2groups` of per-observation `blended` colors: + ``(group_ids, group_colors)``, the quantized color each observation + is grouped under and each group's drawn color (the mean of its + members). `shared` is a `panels=` grid's ``{group id: color}`` for + the whole grid: a panel holds only some of a group's members, so it + draws the group in the GRID's color, not its own members' mean.""" + group_ids, group_colors = colors2groups(blended) + if shared: + group_colors = {gid: tuple(shared.get(gid, color)) + for gid, color in group_colors.items()} + return group_ids, group_colors + + def _matrix_hue_to_rgb(hue_array, color_reduce): """Reduce a matrix hue to 3 min-max scaled columns used AS (r, g, b).""" rgb = np.asarray(hue_array, dtype=np.float64) @@ -4858,8 +4891,14 @@ def _panel_dataset_colors(grid_kw, sources): across the figure. An entry is None where the single-axes call colors the dataset some other way that each panel already reproduces: an explicit `color=`, a color letter in `fmt=`, a per-dataset or - ``{category: color}`` `palette=`, a `hue=`/`cluster=` grouping, or a - MultiIndex frame (drawn as several traces).""" + ``{category: color}`` `palette=`, or a `hue=`/`cluster=` grouping. + + A MultiIndex frame is a dataset like any other here: a hierarchy is + only expanded into several traces for a SINGLE frame, never for a + frame in a list (the single-axes call of the grid's datasets flattens + it, with a warning), and a panel is drawn from its analyzed rows, + which carry no MultiIndex (`_panel_frame`) -- so each such dataset is + one trace in one color, in either figure.""" n = len(sources) none = [None] * n if (grid_kw.get('hue') is not None or grid_kw.get('cluster') @@ -4872,9 +4911,6 @@ def _panel_dataset_colors(grid_kw, sources): if (isinstance(palette, collections.abc.Mapping) or _looks_like_dataset_palettes(palette)): return none - if any(isinstance(getattr(src, 'index', None), pd.MultiIndex) - for src in sources): - return none fmts = _panel_draw_fmts(grid_kw.get('fmt'), n) cycle = iter(_palette_continuation(palette, n)) colors = [] @@ -4887,11 +4923,32 @@ def _panel_dataset_colors(grid_kw, sources): return colors -#: the `plot()` arguments that decide what a figure's colors mean and what -#: explains them: the colors themselves, the legend's entries and the -#: colorbar. A `panels=` grid resolves them ONCE (`_resolve_grid_colors`). -_GRID_COLOR_KWARGS = ('fmt', 'hue', 'palette', 'color', 'colors', 'legend', - 'names', 'colorbar', 'hue_mode', 'color_reduce') +#: the grid kwargs its color resolution (`_resolve_grid_colors`) does NOT +#: forward to the single-axes call it resolves: the analysis (the rows it +#: is given are analyzed already), the overlays and annotations drawn per +#: panel, and what belongs to the figure rather than to its colors. Every +#: OTHER argument is forwarded -- `animate=` and its options, `font=`, +#: `fmt=`, the marker and line styling, `hue=`/`palette=`/`color=`, +#: `legend=`/`names=`/`colorbar=` and their options -- so the resolution +#: runs in the drawing mode the panels are drawn in. An argument added to +#: `plot()` later is forwarded unless it is listed here. +_GRID_RESOLUTION_DROPPED_KWARGS = _PANEL_PROBE_DROPPED_KWARGS + ( + 'reduce', 'normalize', 'align', 'manip', 'pipeline', 'impute', + 'resample', 'transform', 'random_state', 'ndims', 'vectorizer', + 'semantic', 'corpus', 'stream_init', 'stream_chunk', 'stream_max', + 'stream_window', 't', 'labels', 'label_anchor', 'label_alpha', + 'surface', 'density', 'companion', 'explore', 'interactive', + 'on_frame', 'size', 'xlabel', 'ylabel', 'zlabel', 'xlim', 'ylim', + 'axis_scale', 'title', 'title_kwargs', 'title_color', 'title_wrap', + 'frame_kwargs', 'dataset_fade', 'slow_warning_seconds', 'backend', + 'mpl_backend', 'show', 'save_path', 'return_model', 'ax', 'panels', + 'subplots', 'panel_fit', 'caption') + +#: ...and the ones that ask for the legend and the colorbar, left out of +#: the resolution `panel_fit='independent'` runs BEFORE its panels are fit +#: (`_panel_hue_scale_probe`), which only reads the `hue=` scale +_GRID_FURNITURE_KWARGS = ('legend', 'names', 'colorbar', 'legend_colors', + 'legend_kwargs') def _placeholder_rows(lengths, width=3): @@ -4910,34 +4967,57 @@ def _placeholder_rows(lengths, width=3): return rows +def _grid_needs_color_resolution(grid_kw): + """Whether a one-panel-per-dataset grid has anything to resolve for + the whole figure (`_resolve_grid_colors`): a `hue=`, clusters, a + legend (`names=` turns it on) or a colorbar. Without any of them each + panel draws its dataset in its palette color (`_panel_dataset_colors`, + which needs no call at all) and there is nothing else to agree on.""" + legend = grid_kw.get('legend') + colorbar = grid_kw.get('colorbar') + return (grid_kw.get('hue') is not None + or bool(grid_kw.get('cluster')) + or grid_kw.get('n_clusters') is not None + or not (legend is None or legend is False) + or grid_kw.get('names') is not None + or not (colorbar is None or colorbar is False)) + + def _resolve_grid_colors(rows, grid_kw, ndims, caught_warnings, - clustering=None, keys=_GRID_COLOR_KWARGS): + clustering=None, furniture=True): """Resolve, ONCE and for the whole grid, everything a one-panel-per- dataset `panels=` grid's colors mean -- exactly as the equivalent - single-axes call of all the datasets resolves it, by MAKING that call - (on `rows`, the datasets' analyzed rows, with no analysis; the figure - is thrown away). Every panel is then handed its share (``plot``'s - ``_panel_shared``); no panel re-decides any of this from its own - subset of the data. - - `grid_kw` is the grid's own kwargs, of which `keys` are forwarded - (`_GRID_COLOR_KWARGS`); `clustering` the grid's one clustering, replayed - (`_panel_cluster_labels` over every dataset), or None. The call's - errors are the grid's errors (a `legend=` list of the wrong length is - refused with the count of the grid's datasets or groups, a `palette=` - mapping naming a category no dataset has, a `colorbar=` nothing can be - put on), and its warnings are appended to `caught_warnings`, to be - issued once for the grid (the number of non-finite hue values over all - the panels, a legend asked of a continuous hue). + single-axes call of all the datasets resolves it, by running THAT + call's own color resolution (on `rows`, the datasets' analyzed rows, + with no analysis). The call is made in ``resolve_only`` mode (see + `plot`'s ``_panel_shared``): it returns once its colors, legend entries + and colorbar are resolved, before any line is interpolated, any figure + created or anything drawn. Every panel is then handed its share; no + panel re-decides any of this from its own subset of the data. + + `grid_kw` is the grid's own kwargs, forwarded whole but for + `_GRID_RESOLUTION_DROPPED_KWARGS` -- so the call resolves its colors + in the drawing mode the panels use (an animated mixture clustering is + quantized into groups, a static one is a continuous blend; `font=` + reaches the colorbar). `clustering` is the grid's one clustering, + replayed (`_panel_cluster_labels` over every dataset), or None. + Without `furniture` the legend and colorbar arguments are left out + (`_GRID_FURNITURE_KWARGS`). The call's errors are the grid's errors (a + `legend=` list of the wrong length is refused with the count of the + grid's datasets or groups, a `palette=` mapping naming a category no + dataset has, a `colorbar=` nothing can be put on), and its warnings + are appended to `caught_warnings`, to be issued once for the grid (the + number of non-finite hue values over all the panels, a legend asked of + a continuous hue). Returns a dict: - ``'scale'``: the call's color scale (its bundle's ``'colors'``): whether the hue is ``'continuous'`` or ``'discrete'``, its value - range, its ``{category: color}`` mapping; - - ``'categories'``: that mapping keyed by the hue's own categories - (the scale's is keyed by legend label, which a `legend=` list - changes); + range, its ``{legend label: color}`` mapping; + - ``'categories'``: ``{category: color}``, keyed by the hue's own + categories (cluster ids), never by their legend labels: a `legend=` + list may give two categories the same label; - ``'colorbar'``: the colorbar the call draws (`_build_colorbar_info`), or None -- the grid's one colorbar; - ``'legend_names'``: ``{category: legend label}`` where the legend @@ -4946,9 +5026,19 @@ def _resolve_grid_colors(rows, grid_kw, ndims, caught_warnings, (``'_nolegend_'`` for a trace without an entry), or None without a legend; - ``'legend_order'``: the legend's labels in the order the call lists - them, or None without a legend. + them, or None without a legend; + - ``'matrix_hue'``: ``(kind, rows)`` for a matrix `hue=` -- ``'rgb'`` + with the RGB of every observation, reduced and scaled over the whole + grid, or ``'mixture'`` with its weight rows -- else None; + - ``'blend_groups'``: ``{quantized color: drawn color}`` where a + blended coloring is drawn as quantized groups (animated mixture + clusters, a matrix hue on markers), else None. """ - kw = {key: grid_kw[key] for key in keys if key in grid_kw} + kw = {key: value for key, value in grid_kw.items() + if key not in _GRID_RESOLUTION_DROPPED_KWARGS} + if not furniture: + for key in _GRID_FURNITURE_KWARGS: + kw.pop(key, None) if clustering is not None: kw.update(cluster=clustering, n_clusters=None) report, colorbars = {}, [] @@ -4958,10 +5048,9 @@ def _resolve_grid_colors(rows, grid_kw, ndims, caught_warnings, ndims=ndims, show=False, return_model=True, backend='matplotlib', _panel_shared={'colorbars': colorbars, - 'report': report}, **kw) + 'report': report, + 'resolve_only': True}, **kw) caught_warnings.extend(caught) - if isinstance(probe.get('fig'), plt.Figure): - plt.close(probe['fig']) legend = report.get('legend') groups = report.get('group_names') names = order = None @@ -4972,38 +5061,31 @@ def _resolve_grid_colors(rows, grid_kw, ndims, caught_warnings, names = {str(group): label for group, label in zip(groups, legend) if group != '_nolegend_'} - scale = probe.get('colors') - categories = (scale.get('categories') or {} - if isinstance(scale, dict) else {}) - if names and all(str(label) in categories for label in names.values()): - # the scale names its colors by legend label; the panels' hue - # holds the categories themselves - categories = {group: categories[str(label)] - for group, label in names.items()} - return {'scale': scale, - 'categories': dict(categories), + return {'scale': probe.get('colors'), + 'categories': dict(report.get('categories') or {}), 'colorbar': colorbars[0] if colorbars else None, 'legend_names': names, 'legend_labels': (list(legend) if isinstance(legend, list) else None), - 'legend_order': None if order is None else list(order)} + 'legend_order': None if order is None else list(order), + 'matrix_hue': report.get('matrix_hue'), + 'blend_groups': report.get('blend_groups')} def _panel_hue_scale_probe(lengths, grid_kw): """What the single-axes call of every dataset resolves for the grid's - `hue=` (a `_resolve_grid_colors` result, of which the scale and its - categories are read), for + `hue=` (a `_resolve_grid_colors` result, of which the scale, its + categories and a matrix hue's rows are read), for ``panel_fit='independent'``, BEFORE any panel is fit: each panel's fit is a call of its own, which must already read its `hue=` and `palette=` under the grid's scale (a ``{category: color}`` palette names the grid's categories, not one panel's). Resolved on placeholder - rows of the datasets' own lengths, from `hue=`, `palette=` and `fmt=` - alone; None when that fails -- the full resolution, run once the + rows of the datasets' own lengths, without the legend and the + colorbar; None when that fails -- the full resolution, run once the panels are fit, then reports the error.""" try: return _resolve_grid_colors( - _placeholder_rows(lengths), grid_kw, 3, [], - keys=('fmt', 'hue', 'palette', 'hue_mode', 'color_reduce')) + _placeholder_rows(lengths), grid_kw, 3, [], furniture=False) except Exception: # noqa: BLE001 - reported by the full resolution return None @@ -5031,21 +5113,40 @@ def _walk(value): return out -def _panel_apply_hue_scale(kw, resolution, shared): +def _panel_apply_hue_scale(kw, resolution, shared, rows=None): """Make one panel (kwargs `kw`, already narrowed to its dataset) draw its `hue=` under the GRID's color scale (`resolution`, a - `_resolve_grid_colors` result: the single-axes call's ``'colors'`` - and its ``{category: color}`` mapping): the hue is continuous or categorical as the - grid's is (``shared['hue_kind']``, see `plot`'s ``_panel_shared``), a - continuous hue is mapped over the grid-wide value range - (``shared['limits']``), and a categorical hue through the grid's own ``{category: color}`` - mapping, narrowed to the categories this panel has (a `palette=` - mapping may only name categories the plot draws). Returns False when - the panel has a category the scale does not know -- the grid then - cannot claim one shared mapping.""" - scale = None if resolution is None else resolution.get('scale') + `_resolve_grid_colors` result): the hue is continuous or categorical + as the grid's is (``shared['hue_kind']``, see `plot`'s + ``_panel_shared``), a continuous hue is mapped over the grid-wide + value range (``shared['limits']``), a categorical hue through the + grid's own ``{category: color}`` mapping, narrowed to the categories + this panel has (a `palette=` mapping may only name categories the plot + draws), and a matrix hue is replaced by the panel's rows (`rows`, its + ``(start, stop)`` among the grid's observations) of the matrix the + grid resolved -- RGB reduced and scaled over every panel + (``shared['hue_rgb']``), or its mixture weights. A blended coloring + drawn as quantized groups takes the grid's group colors + (``shared['blend_groups']``). Returns False when the panel has a + category the scale does not know -- the grid then cannot claim one + shared mapping.""" + if resolution is None: + return True + if resolution.get('blend_groups'): + shared['blend_groups'] = resolution['blend_groups'] + scale = resolution.get('scale') if not isinstance(scale, dict) or kw.get('hue') is None: return True + matrix = resolution.get('matrix_hue') + if matrix is not None and rows is not None: + kind, values = matrix + values = np.asarray(values) + if rows[1] <= len(values): + kw['hue'] = values[rows[0]:rows[1]] + if kind == 'rgb': + kw['hue_mode'] = 'rgb' + kw['color_reduce'] = None + shared['hue_rgb'] = True if scale.get('kind') in ('continuous', 'discrete'): # the grid's classification of a numeric hue (integers are # categorical or continuous by how many distinct values the WHOLE @@ -5056,6 +5157,7 @@ def _panel_apply_hue_scale(kw, resolution, shared): return True categories = resolution.get('categories') or {} if scale.get('kind') != 'discrete' or not categories \ + or matrix is not None \ or _looks_like_dataset_palettes(kw.get('palette')): return True try: @@ -6147,9 +6249,11 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): # palette names the GRID's categories, and a panel refused the # ones it does not hold _early = _panel_hue_scale_probe(lengths, shared) + _starts = np.cumsum([0] + lengths) for i in range(n_panels): - if not _panel_apply_hue_scale(panel_kwargs[i], _early, - panel_shared[i]): + if not _panel_apply_hue_scale( + panel_kwargs[i], _early, panel_shared[i], + rows=(int(_starts[i]), int(_starts[i + 1]))): scale_mismatch = True elif _early is not None: panel_shared[i]['quiet'] = True @@ -6208,41 +6312,54 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): # panels each draw every dataset through the same color resolution, so # they agree already. A one-panel-per-dataset grid's panels each see # one dataset, so the grid resolves ONCE what the single-axes call of - # ALL the datasets draws (`_resolve_grid_colors`: that very call, on - # the analyzed rows) and hands every panel its share: its dataset's - # color (palette position i of n), its number or name in the legend, - # the grid's `hue=` scale (continuous or categorical, one value range, - # one category -> color mapping) and the grid's names for its - # categories. The legend's order, the colorbar and the bundle's - # ``'colors'`` are that call's; so are its errors and its warnings. + # ALL the datasets resolves (`_resolve_grid_colors`: that very call's + # color resolution, in the panels' drawing mode, stopped before any + # geometry) and hands every panel its share: its dataset's color + # (palette position i of n), its number or name in the legend, the + # grid's `hue=` scale (continuous or categorical, one value range, one + # category -> color mapping, a matrix hue's rows resolved over the + # whole grid) and the grid's names for its categories. The legend's + # order, the colorbar and the bundle's ``'colors'`` are that call's; + # so are its errors and its warnings. meanings_differ = (_panel_meanings_differ(shared, per_panel_reduce, panel_fit) or scale_mismatch) - #: the grid's color resolution; None for a reducer-list grid, and where - #: every panel fits clusters of its own (no grid-wide meaning exists) + #: the grid's color resolution; None for a reducer-list grid, where + #: every panel fits clusters of its own (no grid-wide meaning exists), + #: and where there is nothing to resolve (no `hue=`, clusters, legend + #: or colorbar: `_grid_needs_color_resolution`) resolution = None + #: the color scale of the single-axes call of every dataset, which the + #: grid's bundle reports: the resolution's, or the shared fit's probe's + #: (that very call) where nothing needed resolving; None where neither + #: exists (the panels' own scales are then merged) + resolved_scale = None clustered = bool(shared.get('cluster')) \ or shared.get('n_clusters') is not None if not per_panel_reduce and not (clustered and panel_fit == 'independent'): - _rows = [_panel_frame(src[0], xf[0]) - for src, xf in zip(panel_sources, panel_xforms)] - if len({int(xf[0].shape[1]) if xf[0].ndim == 2 else 1 - for xf in panel_xforms}) > 1: - # panels of unequal width (independent fits) share no axes - _rows = _placeholder_rows([len(xf[0]) for xf in panel_xforms], - width=panel_ndims) - elif len({tuple(map(str, row.columns)) for row in _rows - if is_frame_dataset(row)}) > 1: - # panels whose DataFrames name their columns differently - # (independent fits: each panel has its own features) cannot be - # stacked by feature name; colors, legend entries and the - # colorbar do not depend on the names, so resolve them on the - # bare rows (this call refused such a grid outright) - _rows = [np.asarray(row) for row in _rows] - resolution = _resolve_grid_colors( - _rows, shared, panel_ndims, probe_warnings, - clustering=grid_clustering) - grid_scale = resolution['scale'] + if _grid_needs_color_resolution(shared): + _rows = [_panel_frame(src[0], xf[0]) + for src, xf in zip(panel_sources, panel_xforms)] + if len({int(xf[0].shape[1]) if xf[0].ndim == 2 else 1 + for xf in panel_xforms}) > 1: + # panels of unequal width (independent fits) share no axes + _rows = _placeholder_rows( + [len(xf[0]) for xf in panel_xforms], width=panel_ndims) + elif len({tuple(map(str, row.columns)) for row in _rows + if is_frame_dataset(row)}) > 1: + # panels whose DataFrames name their columns differently + # (independent fits: each panel has its own features) + # cannot be stacked by feature name; colors, legend entries + # and the colorbar do not depend on the names, so resolve + # them on the bare rows (this call refused such a grid + # outright) + _rows = [np.asarray(row) for row in _rows] + resolution = _resolve_grid_colors( + _rows, shared, panel_ndims, probe_warnings, + clustering=grid_clustering) + grid_scale = resolved_scale = resolution['scale'] + elif panel_fit == 'shared': + resolved_scale = grid_scale # one drawn trace per dataset (ndims=1 draws one line per COLUMN, # colored by column in every panel alike) one_trace = panel_ndims != 1 or all( @@ -6251,12 +6368,15 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): own_colors = (_panel_dataset_colors(shared, datasets) if one_trace else [None] * n_panels) ungrouped = shared.get('hue') is None and not clustered + _starts = np.cumsum([0] + [len(xf[0]) for xf in panel_xforms]) for i in range(n_panels): kw = panel_kwargs[i] - # the warnings about the whole call are the resolution's - panel_shared[i]['quiet'] = True if own_colors[i] is not None: kw['color'] = [own_colors[i]] + if resolution is None: + continue + # the warnings about the whole call are the resolution's + panel_shared[i]['quiet'] = True _labels = resolution['legend_labels'] if (kw.get('legend') is True and ungrouped and one_trace and kw.get('names') is None and _labels is not None @@ -6270,7 +6390,9 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): # each panel labels the ones it draws kw['legend'] = True panel_shared[i]['legend_names'] = resolution['legend_names'] - if not _panel_apply_hue_scale(kw, resolution, panel_shared[i]): + if not _panel_apply_hue_scale( + kw, resolution, panel_shared[i], + rows=(int(_starts[i]), int(_starts[i + 1]))): # a panel's categories are not the grid scale's: no # shared mapping to claim meanings_differ = True @@ -6361,7 +6483,7 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): scale_order=scale_order, dataset_mode=not per_panel_reduce, grid_colorbar=grid_colorbar, legend_order=legend_order, - grid_scale=(None if resolution is None else grid_scale)) + grid_scale=resolved_scale) _reemit_panel_warnings(probe_warnings, draw_warnings) return grid @@ -6495,8 +6617,7 @@ def _draw_grid(consolidate): else [cell['colors'] for cell in cells]) grid_colors = (_scales[0] if _scales and meanings_differ else _grid_color_scale( - _scales, - None if resolution is None else grid_scale, + _scales, resolved_scale, dataset_mode=not per_panel_reduce)) if animated: @@ -10818,15 +10939,27 @@ def plot( # asked of a continuous hue), so no panel repeats them; ``'colorbars'``, # a list this call appends its resolved colorbar to INSTEAD of drawing # it (the grid draws one for the figure, and one legend, so the panel's - # own legend is not fitted either); and ``'report'``, a dict this call - # fills with the legend it resolved (the grid's own probe call reads - # it). Internal, never a user kwarg. + # own legend is not fitted either); ``'hue_rgb'``, set when this + # panel's matrix `hue=` is the grid's RGB, already resolved for the + # whole grid (reduced and scaled over every panel's rows), which the + # panel draws as it is; and ``'blend_groups'``, the grid's + # ``{quantized color: drawn color}`` for the groups a blended (mixture) + # coloring is quantized into. The grid's own RESOLUTION call + # (`_resolve_grid_colors`) passes ``'report'``, a dict this call fills + # with what it resolved (its legend, its ``{category: color}``, the + # RGB of a matrix hue, its blend groups), and ``'resolve_only'``: the + # call then returns once its colors, legend entries and colorbar are + # resolved, BEFORE any geometry is built or drawn. Internal, never a + # user kwarg. _panel_shared = kwargs.pop('_panel_shared', None) _hue_limits = (_panel_shared or {}).get('limits') _grid_hue_kind = (_panel_shared or {}).get('hue_kind') _grid_legend_names = (_panel_shared or {}).get('legend_names') _grid_quiet = bool((_panel_shared or {}).get('quiet')) _grid_report = (_panel_shared or {}).get('report') + _grid_resolve_only = bool((_panel_shared or {}).get('resolve_only')) + _grid_hue_rgb = bool((_panel_shared or {}).get('hue_rgb')) + _grid_blend_groups = (_panel_shared or {}).get('blend_groups') _grid_furniture = (_panel_shared is not None and 'colorbars' in _panel_shared) @@ -10862,7 +10995,8 @@ def plot( '_panel_shared', '_hue_limits', '_grid_furniture', '_grid_hue_kind', '_grid_legend_names', '_grid_quiet', - '_grid_report')} + '_grid_report', '_grid_resolve_only', + '_grid_hue_rgb', '_grid_blend_groups')} _panel_call.update(kwargs) return _plot_panels(x, _panels_spec, _panel_call, _name=_panels_name) @@ -12815,6 +12949,14 @@ def _compute_forecasts(datasets): # data by category -- names= (one name per INPUT dataset) cannot apply # after that regrouping (F02-009). _hue_regrouped_counts = None + #: ``(kind, rows)`` of a flat matrix `hue=` as this call resolved it: + #: ``'rgb'`` with its rows reduced and scaled to RGB, or ``'mixture'`` + #: with its (non-negative) weight rows -- what a `panels=` grid hands + #: its panels, each its own rows; None without a matrix hue + _resolved_matrix_hue = None + #: ``{quantized color: drawn color}`` of the groups a blended coloring + #: was quantized into (`_blend_groups`), or None + _blend_group_colors = None #: True once a MARKER-only `hue=`/`cluster=` grouping ran through #: `reshape_data`, which groups GLOBALLY by category: its drawn traces #: are categories, never datasets, however the counts happen to fall @@ -13407,7 +13549,9 @@ def _compute_forecasts(datasets): # points or crossing a dataset boundary; GH #291), each run # colored by its quantized blended group color. blended = mat2colors(cluster_labels, palette=palette) - group_ids, group_colors = colors2groups(blended) + group_ids, group_colors = _blend_groups( + blended, _grid_blend_groups) + _blend_group_colors = dict(group_colors) _cat_color = {gid: group_colors[gid] for gid in dict.fromkeys(group_ids)} _cat_label = {gid: str(gid) for gid in dict.fromkeys(group_ids)} @@ -13423,7 +13567,9 @@ def _compute_forecasts(datasets): # marker animations render one trace per group: quantize the # blended colors into (near-)identical-color groups blended = mat2colors(cluster_labels, palette=palette) - group_ids, group_colors = colors2groups(blended) + group_ids, group_colors = _blend_groups( + blended, _grid_blend_groups) + _blend_group_colors = dict(group_colors) xform, labels = reshape_data(xform, group_ids, labels) _global_regrouped = True mpl_kwargs["color"] = [ @@ -13663,11 +13809,27 @@ def _compute_forecasts(datasets): # whether or not the frame has a hierarchy (they did not: measured, # color_reduce= changed a flat figure's colors and was silently # ignored under a hierarchy). - if hue_is_matrix and _matrix_hue_wants_rgb(hue_array, - color_reduce, - hue_mode): + if hue_is_matrix and _grid_hue_rgb: + # a `panels=` cell: these rows ARE the grid's RGB, reduced and + # scaled once over every panel's rows (scaling them again over + # this panel's own range drew one hue row white in one panel + # and black in the next) + hue_array = np.clip(np.asarray(hue_array, dtype=np.float64), + 0.0, 1.0) + multicolor_hue_is_rgb = True + elif hue_is_matrix and _matrix_hue_wants_rgb(hue_array, + color_reduce, + hue_mode): hue_array = _matrix_hue_to_rgb(hue_array, color_reduce) multicolor_hue_is_rgb = True + elif hue_is_matrix: + # mixture weights: a SIGNED matrix is shifted row by row + # (`mat2colors`), decided here for the whole matrix so every + # consumer -- and every panel of a grid -- blends the same rows + hue_array = _nonnegative_mixture_rows(hue_array) + if hue_is_matrix: + _resolved_matrix_hue = ( + 'rgb' if multicolor_hue_is_rgb else 'mixture', hue_array) # set when a categorical INTEGER/boolean hue needs its groups # reordered from first-appearance to sorted numeric order after @@ -13712,7 +13874,9 @@ def _compute_forecasts(datasets): # traces blended = (hue_array if multicolor_hue_is_rgb else mat2colors(hue_array, palette=palette)) - group_ids, group_colors = colors2groups(blended) + group_ids, group_colors = _blend_groups( + blended, _grid_blend_groups) + _blend_group_colors = dict(group_colors) mpl_kwargs["color"] = [ group_colors[gid] for gid in sorted(set(group_ids), key=group_ids.index) @@ -14447,6 +14611,57 @@ def _compute_forecasts(datasets): and not isinstance(palette, collections.abc.Mapping) and not _looks_like_dataset_palettes(palette)) + if _grid_resolve_only: + # a `panels=` grid's color resolution (`_resolve_grid_colors`): + # everything this call's colors mean is resolved by now -- the + # scale, the legend's entries, the colorbar -- and nothing of it + # depends on the geometry, so the call stops HERE, before the + # lines are interpolated and anything is drawn (1.2.0 review, + # round 3: the resolution used to draw a second full figure) + if _color_scales_from_cycle: + # the cycle colors the datasets take on a fresh axes, as both + # backends assign them below (a fmt= color letter takes no + # slot) + _fmts = _panel_draw_fmts(fmt, len(xform)) or [] + _cycle_iter = iter(_palette_continuation(palette, len(xform))) + _drawn_colors = [] + for _i in range(len(xform)): + _letter = _fmt_color_letter( + _fmts[_i] if _i < len(_fmts) else None) + _drawn_colors.append(_letter if _letter is not None + else next(_cycle_iter, None)) + if None not in _drawn_colors: + _sync_color_scales(_drawn_colors, colors_info, + colorbar_info) + if colorbar_info is not None and _grid_furniture: + _panel_shared['colorbars'].append( + dict(colorbar_info, font=_artist_font)) + if (multicolor_hue is not None and not multicolor_hue_is_rgb + and not _grid_quiet): + # the one warning the drawing itself issues about the colors + # (`_multicolor_line_colors`): said here, for the whole grid + _warn_non_finite_hue(multicolor_hue) + if _grid_report is not None: + #: the scale's ``{category: color}``, keyed by the CATEGORY + #: (the scale itself is keyed by legend label, and a `legend=` + #: list may give two categories one label) + _by_category = colors_info + if (_legend_group_names is not None + and isinstance(legend, (list, tuple)) + and len(_legend_group_names) == len(legend)): + _by_category = _build_colors_info( + hue, multicolor_hue, cluster, n_clusters, xform, + mpl_kwargs, list(_legend_group_names), palette, + hue_group_labels=hue_group_labels, + hierarchy_labels=_mi_colorbar_labels, + legend_entries=_final_legend_entries, + limits=_hue_limits) + _grid_report.update( + categories=dict(_by_category.get('categories') or {}), + matrix_hue=_resolved_matrix_hue, + blend_groups=_blend_group_colors) + return {'colors': colors_info} + # interpolate if its a line plot. animate='morph' treats every dataset # as a POINT CLOUD (Hungarian-matched to its neighbors in `morph.py`), # never as a time-ordered trajectory -- interpolating it here would @@ -18153,6 +18368,24 @@ def _contains_string(el): return False +def _warn_non_finite_hue(hue_values): + """Warn, once, how many OBSERVATIONS of a per-point `hue=` (1-D values + or one matrix row each) are non-finite: they are drawn gray and left + out of the color mapping. Nothing is said when every one is finite.""" + values = np.asarray(hue_values, dtype=np.float64) + if values.ndim == 1: + values = values.reshape(-1, 1) + n_bad = int(np.count_nonzero(~np.isfinite(values).all(axis=1))) + if n_bad: + from .colors import NAN_COLOR + warnings.warn( + f"{n_bad} observation(s) have non-finite (NaN/inf) " + f"hue/color values; they are drawn in a neutral gray " + f"{NAN_COLOR} and excluded from the color mapping (the " + "remaining observations keep their full color range).", + UserWarning, stacklevel=external_stacklevel()) + + def _multicolor_line_colors(hue_src, orig_lengths, xform, palette, is_rgb=False, warn_non_finite=True, limits=None): """Per-point RGB colors for multicolored lines. @@ -18223,15 +18456,7 @@ def _multicolor_line_colors(hue_src, orig_lengths, xform, palette, is_rgb=False, stacked.ravel() if stacked.shape[1] == 1 else stacked, palette=palette) if warn_non_finite: - _n_bad = int(np.count_nonzero(~np.isfinite(hue_src).all(axis=1))) - if _n_bad: - from .colors import NAN_COLOR - warnings.warn( - f"{_n_bad} observation(s) have non-finite (NaN/inf) " - f"hue/color values; they are drawn in a neutral gray " - f"{NAN_COLOR} and excluded from the color mapping (the " - "remaining observations keep their full color range).", - UserWarning, stacklevel=external_stacklevel()) + _warn_non_finite_hue(hue_src) out, start = [], 0 for xi in xform: diff --git a/tests/test_panel_color_invariant.py b/tests/test_panel_color_invariant.py new file mode 100644 index 000000000..f077a68a2 --- /dev/null +++ b/tests/test_panel_color_invariant.py @@ -0,0 +1,315 @@ +"""The `panels=` color invariant (1.2.0 review round 3): every artist a +one-panel-per-dataset grid draws for dataset i has the color the equivalent +single-axes call of ALL the datasets gives that dataset's rows. + +Each case draws both real figures and reads the real artists back. The +first data column is the row's global index, so every drawn vertex can be +traced to its row whatever regrouping (`hue=` categories, clusters, runs) +either call applied: hypertools' display rescale is affine per axis, so +the drawn x of a row is an affine function of its index in either figure. +""" +import math +import warnings + +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +import pytest +from matplotlib.collections import LineCollection, PathCollection +from matplotlib.colors import to_rgba, to_rgba_array + +import hypertools as hyp +from hypertools.plot.plot import SHARED_COLORBAR_GID + +ROWS = 12 +N_DATASETS = 3 +TOTAL = ROWS * N_DATASETS + + +@pytest.fixture(autouse=True) +def _close_figures(): + """Leave no figure behind.""" + yield + plt.close('all') + + +def _datasets(width=2): + """Three datasets whose first column is the global row index and whose + other columns separate the rows into clusterable blocks.""" + rng = np.random.default_rng(7) + out = [] + for i in range(N_DATASETS): + index = np.arange(i * ROWS, (i + 1) * ROWS, dtype=float) + columns = [index] + for k in range(width - 1): + columns.append(np.sin(index / 3.0 + k) + + 0.05 * rng.normal(size=ROWS)) + out.append(np.column_stack(columns)) + return out + + +def _x_of(artist): + """The drawn x coordinates of a line or scatter artist (2-D or 3-D).""" + if hasattr(artist, 'get_data_3d'): + return np.asarray(artist.get_data_3d()[0], dtype=float) + if hasattr(artist, '_offsets3d'): + return np.asarray(artist._offsets3d[0], dtype=float) + if isinstance(artist, PathCollection): + return np.asarray(artist.get_offsets(), dtype=float)[:, 0] + return np.asarray(artist.get_xdata(), dtype=float) + + +def _segments_of(collection): + """A line collection's segments as ``(x0, x1)`` pairs (2-D or 3-D).""" + segments = getattr(collection, '_segments3d', None) + if segments is None: + segments = collection.get_segments() + return [(float(np.asarray(seg)[0][0]), float(np.asarray(seg)[-1][0])) + for seg in segments if len(seg) >= 2] + + +def _marks(ax): + """Every colored mark `ax` draws, as ``(kind, x0, x1, rgb)``: a + ``'marker'`` at ``x0`` (``x1`` is None) or a line ``'segment'`` from + ``x0`` to ``x1``.""" + marks = [] + for line in ax.lines: + if not line.get_visible(): + continue + xs = _x_of(line) + if xs.size == 0: + continue + if line.get_linestyle() not in ('None', '', ' ', None) \ + and xs.size >= 2: + rgb = to_rgba(line.get_color())[:3] + marks.extend(('segment', float(a), float(b), rgb) + for a, b in zip(xs[:-1], xs[1:])) + if line.get_marker() not in ('None', '', ' ', None): + rgb = to_rgba(line.get_markerfacecolor())[:3] + marks.extend(('marker', float(a), None, rgb) for a in xs) + for coll in ax.collections: + if not coll.get_visible(): + continue + if isinstance(coll, LineCollection): + segments = _segments_of(coll) + if not segments: + continue + colors = to_rgba_array(coll.get_colors()) + if len(colors) == 1 and len( + {round(abs(x), 9) for seg in segments for x in seg}) == 1: + # a face of the 3-D cube frame (a wireframe whose every + # vertex sits on the cube's +/- half-width), not data + continue + if len(colors) == 1: + colors = np.repeat(colors, len(segments), axis=0) + marks.extend(('segment', a, b, tuple(c[:3])) + for (a, b), c in zip(segments, colors)) + elif isinstance(coll, PathCollection): + xs = _x_of(coll) + if xs.size == 0: + continue + # (a 3-D scatter's `get_facecolor()` is depth-sorted to the + # current view; the colors it was given are `_facecolors`) + colors = to_rgba_array(coll._facecolors + if hasattr(coll, '_offsets3d') + else coll.get_facecolor()) + if len(colors) == 1: + colors = np.repeat(colors, xs.size, axis=0) + marks.extend(('marker', float(a), None, tuple(c[:3])) + for a, c in zip(xs, colors)) + return marks + + +def _row_colors(ax, first_row, last_row): + """``{(kind, row): sorted colors}`` for the rows `ax` draws, which run + from `first_row` to `last_row` (global indices): a marker belongs to + the row it sits on, a line segment to every row it starts at or + passes.""" + marks = _marks(ax) + assert marks, 'the axes draws nothing' + xs = [m[1] for m in marks] + [m[2] for m in marks if m[2] is not None] + lo, hi = min(xs), max(xs) + assert hi > lo + scale = (last_row - first_row) / (hi - lo) + eps = 1e-6 + out = {} + for kind, x0, x1, rgb in marks: + a = first_row + (x0 - lo) * scale + color = tuple(round(float(v), 3) for v in rgb) + if kind == 'marker': + if abs(a - round(a)) < 1e-4: + out.setdefault((kind, int(round(a))), set()).add(color) + continue + b = first_row + (x1 - lo) * scale + if b <= a: + continue + for row in range(math.ceil(a - eps), math.ceil(b - eps)): + out.setdefault((kind, row), set()).add(color) + return {key: sorted(value) for key, value in out.items()} + + +def _draw(data, kwargs): + """`hyp.plot` of `data`, quietly; an animation is advanced to its last + frame (every row revealed) and its figure returned.""" + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + out = hyp.plot(data, show=False, **kwargs) + if hasattr(out, 'draw_frame'): + out.draw_frame(out.n_frames - 1) + return out.figure + return out + + +def _mixed_categories(): + """Categories spread unevenly over the panels: the first panel holds + one, the others two each, never the same pair.""" + return (['a'] * ROWS + ['a'] * 5 + ['b'] * (ROWS - 5) + + ['c'] * 7 + ['b'] * (ROWS - 7)) + + +def _rgb_matrix(): + """An RGB hue whose value range differs between the panels.""" + ramp = np.linspace(0.0, 2.0, TOTAL) + return np.column_stack([ramp, ramp[::-1] ** 2, np.cos(ramp)]) + + +def _wide_matrix(): + """A five-column hue matrix (reduced to RGB).""" + rng = np.random.default_rng(3) + return rng.normal(size=(TOTAL, 5)).cumsum(axis=0) + + +def _mixture(signed=False): + """Mixture weights over three components; `signed` puts negative + entries in the last panel's rows only.""" + rng = np.random.default_rng(5) + weights = rng.dirichlet([1.0, 1.0, 1.0], size=TOTAL) + if signed: + weights[-ROWS:] -= 0.4 + return weights + + +def _multiindex_frames(width=2): + """The datasets as row-MultiIndex frames (flattened in a list).""" + index = pd.MultiIndex.from_product([['u', 'v'], range(ROWS // 2)]) + return [pd.DataFrame(d, index=index) for d in _datasets(width)] + + +#: ``id -> (kwargs, data factory or None)``; every case is drawn with each +#: of `FMTS` unless it names its own `fmt=` +CASES = { + 'plain': {}, + 'palette-name': {'palette': 'viridis'}, + 'palette-list': {'palette': ['#111111', '#aa3300', '#0055ff']}, + 'color-list': {'color': ['k', 'tab:orange', 'teal']}, + 'color-tuple': {'color': (0.2, 0.4, 0.6)}, + 'fmt-letters': {'fmt': ['r-', '-', 'g-']}, + 'legend': {'legend': True}, + 'names': {'names': ['one', 'two', 'three']}, + 'hue-continuous': {'hue': np.linspace(-1.0, 4.0, TOTAL) ** 2}, + 'hue-continuous-colorbar': {'hue': np.linspace(0.0, 1.0, TOTAL), + 'colorbar': True, 'palette': 'magma'}, + 'hue-continuous-nan': {'hue': np.r_[np.nan, np.linspace(0, 1, + TOTAL - 1)]}, + 'hue-categorical': {'hue': _mixed_categories()}, + 'hue-categorical-legend': {'hue': _mixed_categories(), 'legend': True, + 'colorbar': True}, + 'hue-categorical-palette-map': { + 'hue': _mixed_categories(), + 'palette': {'a': 'red', 'b': 'blue', 'c': '#00aa00'}}, + 'hue-categorical-duplicate-legend': { + 'hue': _mixed_categories(), + 'palette': {'a': 'red', 'b': 'blue', 'c': 'green'}, + 'legend': ['same', 'same', 'other'], 'colorbar': True}, + 'hue-categorical-renamed': { + 'hue': _mixed_categories(), 'legend': ['x', 'y', 'z']}, + 'hue-partial-labels': { + 'hue': [None if i % 5 == 0 else label + for i, label in enumerate(_mixed_categories())]}, + 'hue-integers': {'hue': np.repeat([3, 1, 2, 1, 3, 2], TOTAL // 6)}, + 'hue-many-integers': {'hue': np.arange(TOTAL)}, + 'hue-per-dataset': {'hue': ['p', 'q', 'p']}, + 'hue-nested': {'hue': [['a'] * ROWS, ['b'] * ROWS, + ['a'] * 6 + ['c'] * (ROWS - 6)]}, + 'hue-rgb': {'hue': _rgb_matrix(), 'hue_mode': 'rgb'}, + 'hue-wide-matrix': {'hue': _wide_matrix()}, + 'hue-wide-matrix-pca': {'hue': _wide_matrix(), 'color_reduce': 'PCA'}, + 'hue-mixture': {'hue': _mixture(), 'palette': ['r', 'g', 'b']}, + 'hue-mixture-signed': {'hue': _mixture(signed=True)}, + 'hue-mixture-legend': {'hue': _mixture(), 'legend': True}, + 'cluster-kmeans': {'cluster': 'KMeans', 'n_clusters': 4, + 'random_state': 0}, + 'cluster-kmeans-legend': {'n_clusters': 3, 'random_state': 1, + 'legend': ['k1', 'k2', 'k3'], + 'colorbar': True}, + 'cluster-mixture': {'cluster': 'GaussianMixture', 'n_clusters': 3, + 'random_state': 0}, + 'multiindex-frames': ({'legend': True, 'colorbar': True}, + _multiindex_frames), + 'font': {'hue': np.linspace(0.0, 1.0, TOTAL), 'colorbar': True, + 'font': 'DejaVu Sans Mono'}, +} + +FMTS = ('-', 'o', 'o-') +MODES = { + 'static': {}, + 'static-raw': {'antialias': False}, + 'spin': {'animate': 'spin', 'duration': 1, 'frame_rate': 4, + '_width': 3}, + 'reveal': {'animate': True, 'duration': 1, 'frame_rate': 4, + 'tail_duration': 1}, + 'independent': {'panel_fit': 'independent'}, + '3d': {'_width': 3}, +} + + +def _grid_cases(): + """Every (case, fmt, mode) drawn by `test_panel_colors_are_the_single` + `_axes_call_s`: all cases statically with every fmt; the animated, + independent-fit and 3-D modes with lines and with markers.""" + params = [] + for name, spec in CASES.items(): + kwargs, factory = spec if isinstance(spec, tuple) else (spec, None) + fmts = (None,) if 'fmt' in kwargs else FMTS + for mode in MODES: + for fmt in fmts: + if mode != 'static' and fmt == 'o-': + continue + if mode == 'independent' and ('cluster' in kwargs + or 'n_clusters' in kwargs): + # every panel then fits clusters of its own: there is + # no single-axes call the grid is equivalent to + continue + params.append(pytest.param( + kwargs, factory, fmt, mode, + id=f'{name}/{fmt or "own"}/{mode}')) + return params + + +@pytest.mark.parametrize('kwargs,factory,fmt,mode', _grid_cases()) +def test_panel_colors_are_the_single_axes_calls(kwargs, factory, fmt, mode): + mode_kwargs = dict(MODES[mode]) + width = mode_kwargs.pop('_width', 2) + data = (factory or _datasets)(width) + call = dict(kwargs, reduce=None, ndims=width, **mode_kwargs) + if fmt is not None: + call['fmt'] = fmt + single_kwargs = {k: v for k, v in call.items() if k != 'panel_fit'} + single = _draw(data, single_kwargs) + grid = _draw(data, dict(call, panels=True)) + + # (the data axes come first; a colorbar's axes follow them) + want = _row_colors(single.axes[0], 0, TOTAL - 1) + panels = grid.axes[:N_DATASETS] + assert all(ax.get_gid() != SHARED_COLORBAR_GID for ax in panels) + for i, ax in enumerate(panels): + first, last = i * ROWS, (i + 1) * ROWS - 1 + got = _row_colors(ax, first, last) + expected = {key: value for key, value in want.items() + if first <= key[1] <= last} + assert expected, f'the single-axes call draws nothing of dataset {i}' + assert got == expected, ( + f'panel {i}: ' + '; '.join( + f'{key}: grid {got.get(key)} != single {expected.get(key)}' + for key in sorted(set(got) | set(expected)) + if got.get(key) != expected.get(key))[:600]) diff --git a/tests/test_panels_review_round3.py b/tests/test_panels_review_round3.py new file mode 100644 index 000000000..c5cd48edc --- /dev/null +++ b/tests/test_panels_review_round3.py @@ -0,0 +1,294 @@ +"""1.2.0 review, round 3: a `panels=` grid's color resolution runs in the +panels' own drawing mode and stops before any geometry, categories are +identified by themselves, and a matrix `hue=` is resolved once for the grid. + +Every test makes the real call and reads the real figure back; call counts +are taken with `sys.setprofile` on the real functions (nothing is replaced). +The broad "every panel artist has the single-axes call's color" check is +`tests/test_panel_color_invariant.py`. +""" +import sys +import warnings + +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +import pytest +from matplotlib.colors import to_rgb + +import hypertools as hyp +from hypertools.plot import matplotlib_backend, plotly_backend +from hypertools.plot import plot as plot_module +from hypertools.plot.plot import SHARED_COLORBAR_GID, SHARED_LEGEND_GID + +X = np.random.default_rng(0).normal(size=(20, 2)).cumsum(0) +ANIM = dict(animate=True, duration=1, frame_rate=4) + + +@pytest.fixture(autouse=True) +def _close_figures(): + """Leave no figure behind.""" + yield + plt.close('all') + + +def _quiet(*args, **kwargs): + """`hyp.plot(..., show=False)` with its warnings ignored.""" + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + return hyp.plot(*args, show=False, **kwargs) + + +def _shared_colorbar(fig): + """The grid's one colorbar axes.""" + found = [ax for ax in fig.axes if ax.get_gid() == SHARED_COLORBAR_GID] + assert len(found) == 1 + return found[0] + + +def _swatches(cax): + """The RGB swatches of a discrete colorbar axes, in drawn order.""" + colors = [] + for coll in cax.collections: + array = coll.get_array() + if array is None or not len(array): + continue + rgba = coll.cmap(coll.norm(np.asarray(array).ravel())) + colors.extend(tuple(round(float(v), 3) for v in c[:3]) + for c in rgba) + return colors + + +class _Calls: + """Count the real calls of the given functions made inside a ``with`` + block, with `sys.setprofile` -- the functions themselves run + untouched.""" + + def __init__(self, **functions): + self._codes = {name: fn.__code__ for name, fn in functions.items()} + self.count = dict.fromkeys(functions, 0) + + def _profile(self, frame, event, arg): + """Tally a ``call`` event of one of the watched functions.""" + if event == 'call': + for name, code in self._codes.items(): + if frame.f_code is code: + self.count[name] += 1 + + def __enter__(self): + self._previous = sys.getprofile() + sys.setprofile(self._profile) + return self + + def __exit__(self, *exc): + sys.setprofile(self._previous) + return False + + +# -------------------------------------------------------------------------- +# Codex 1: the resolution runs in the panels' drawing mode +# -------------------------------------------------------------------------- + +def test_animated_mixture_clusters_take_a_colorbar(): + """An animated mixture clustering is quantized into groups, which a + discrete colorbar can show; the static one is a continuous blend, + which it cannot. The grid resolved its colors statically whatever + the panels drew, and refused the animated grid's colorbar.""" + kwargs = dict(reduce=None, ndims=2, cluster='GaussianMixture', + n_clusters=2, random_state=0, colorbar=True) + anim = _quiet([X, X + 3], 'o', panels=True, **kwargs, **ANIM) + single = _quiet([X, X + 3], 'o', **kwargs, **ANIM) + grid_swatches = _swatches(_shared_colorbar(anim.figure)) + assert grid_swatches + # the one colorbar is the single-axes call's + assert grid_swatches == _swatches(single.figure.axes[-1]) + # ...and every panel draws its groups in those colors + anim.draw_frame(anim.n_frames - 1) + drawn = {tuple(np.round(to_rgb(line.get_color()), 3)) + for ax in anim.figure.axes[:2] for line in ax.lines + if len(line.get_xdata())} + assert drawn and drawn <= set(grid_swatches) + + with pytest.raises(ValueError, match='colorbar is not supported'): + _quiet([X, X + 3], 'o', panels=True, **kwargs) + + +# -------------------------------------------------------------------------- +# Codex 2: a category is identified by itself, never by its legend label +# -------------------------------------------------------------------------- + +@pytest.mark.parametrize('backend', ['matplotlib', 'plotly']) +def test_two_categories_with_one_legend_name_keep_their_colors(backend): + fig = _quiet([X, X + 3], 'o', panels=True, reduce=None, ndims=2, + hue=[['a'] * 20, ['b'] * 20], + palette={'a': 'red', 'b': 'blue'}, + legend=['same', 'same'], colorbar=True, backend=backend) + if backend == 'plotly': + drawn = [trace.marker.color for trace in fig.data + if trace.name == 'same'] + assert drawn == ['rgba(255,0,0,1.0)', 'rgba(0,0,255,1.0)'] + return + drawn = [to_rgb(ax.lines[0].get_color()) for ax in fig.axes[:2]] + assert drawn == [to_rgb('red'), to_rgb('blue')] + assert _swatches(_shared_colorbar(fig)) == [(1.0, 0.0, 0.0), + (0.0, 0.0, 1.0)] + # one name for two colors cannot be one shared entry: each panel + # keeps its own legend, in its own color + assert not [lg for lg in fig.legends + if lg.get_gid() == SHARED_LEGEND_GID] + for ax, color in zip(fig.axes[:2], ('red', 'blue')): + handle, = ax.get_legend().legend_handles + assert to_rgb(handle.get_color()) == to_rgb(color) + assert [t.get_text() for t in ax.get_legend().get_texts()] \ + == ['same'] + + +# -------------------------------------------------------------------------- +# Codex 4: MultiIndex frames in a list are datasets like any other +# -------------------------------------------------------------------------- + +@pytest.mark.parametrize('backend', ['matplotlib', 'plotly']) +def test_row_multiindex_frames_keep_their_dataset_colors(backend): + frame = pd.DataFrame( + X, index=pd.MultiIndex.from_product([['a', 'b'], range(10)])) + kwargs = dict(reduce=None, ndims=2, legend=True, colorbar=True, + backend=backend) + grid = _quiet([frame, frame + 3], 'o', panels=True, **kwargs) + single = _quiet([frame, frame + 3], 'o', **kwargs) + if backend == 'plotly': + want = [t.marker.color for t in single.data if t.name in ('1', '2')] + got = [t.marker.color for t in grid.data if t.name in ('1', '2')] + assert len(set(want)) == 2 and got == want + return + want = [to_rgb(line.get_color()) for line in single.axes[0].lines] + got = [to_rgb(ax.lines[0].get_color()) for ax in grid.axes[:2]] + assert len(set(want)) == 2 and got == want + assert _swatches(_shared_colorbar(grid)) \ + == [tuple(round(float(v), 3) for v in c) for c in want] + + +# -------------------------------------------------------------------------- +# Codex 5: a matrix hue is resolved once for the grid +# -------------------------------------------------------------------------- + +@pytest.mark.parametrize('backend', ['matplotlib', 'plotly']) +def test_one_rgb_hue_row_is_one_color_in_every_panel(backend): + """Rows 19 and 20 of the hue are both ``[1, 1, 1]``; the grid's range + is 0..2, so both are mid gray, as the single-axes call draws them -- + not white in the first panel and black in the second.""" + hue = np.repeat(np.r_[np.linspace(0, 1, 20), + np.linspace(1, 2, 20)][:, None], 3, axis=1) + fig = _quiet([X, X + 3], 'o', panels=True, reduce=None, ndims=2, + hue=hue, hue_mode='rgb', backend=backend) + if backend == 'plotly': + first, second = [t.marker.color for t in fig.data[:2]] + assert first[0] == 'rgb(0,0,0)' and second[-1] == 'rgb(255,255,255)' + assert first[-1] == second[0] == 'rgb(128,128,128)' + return + first, second = [ax.collections[0].get_facecolor()[:, :3] + for ax in fig.axes[:2]] + np.testing.assert_allclose(first[0], 0.0) + np.testing.assert_allclose(second[-1], 1.0) + np.testing.assert_allclose(first[-1], 0.5) + np.testing.assert_allclose(second[0], 0.5) + + +def test_a_wide_matrix_hue_is_reduced_once_for_the_grid(): + """More than three columns are reduced to RGB by ONE fit over every + panel's rows; each panel refitting its own gave unrelated colors.""" + rng = np.random.default_rng(3) + hue = rng.normal(size=(40, 6)).cumsum(axis=0) + kwargs = dict(reduce=None, ndims=2, hue=hue) + grid = _quiet([X, X + 3], 'o', panels=True, **kwargs) + single = _quiet([X, X + 3], 'o', **kwargs) + want = [c.get_facecolor()[:, :3] for c in single.axes[0].collections] + got = [ax.collections[0].get_facecolor()[:, :3] for ax in grid.axes[:2]] + assert len(want) == 2 + for panel, reference in zip(got, want): + np.testing.assert_allclose(panel, reference, atol=1e-9) + + +def test_signed_mixture_weights_blend_alike_in_every_panel(): + """`mat2colors` shifts every row of a matrix that holds ANY negative + entry; a panel whose own rows hold none must still be shifted when the + grid's matrix is signed.""" + rng = np.random.default_rng(5) + hue = rng.dirichlet([1.0, 1.0, 1.0], size=40) + hue[20:] -= 0.4 + kwargs = dict(reduce=None, ndims=2, hue=hue) + grid = _quiet([X, X + 3], 'o', panels=True, **kwargs) + single = _quiet([X, X + 3], 'o', **kwargs) + want = [c.get_facecolor()[:, :3] for c in single.axes[0].collections] + got = [ax.collections[0].get_facecolor()[:, :3] for ax in grid.axes[:2]] + for panel, reference in zip(got, want): + np.testing.assert_allclose(panel, reference, atol=1e-9) + + +# -------------------------------------------------------------------------- +# Codex 7: font= reaches the grid's one colorbar +# -------------------------------------------------------------------------- + +def test_the_shared_colorbar_uses_the_requested_font(): + fig = _quiet([X, X + 3], 'o', panels=True, reduce=None, ndims=2, + hue=np.linspace(0, 1, 40), + colorbar={'label': 'value'}, font='DejaVu Sans Mono') + cax = _shared_colorbar(fig) + fig.canvas.draw() + texts = [t for t in cax.get_yticklabels() if t.get_text()] + texts.append(cax.yaxis.label) + assert len(texts) > 1 + for text in texts: + assert text.get_fontname() == 'DejaVu Sans Mono', text.get_text() + + +# -------------------------------------------------------------------------- +# Codex 8: resolving the colors draws nothing +# -------------------------------------------------------------------------- + +def _count_calls(data, **kwargs): + """How often `plot()` and the two backends' draw entry points run for + one grid call: ``(plot calls, draw calls)``.""" + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + with _Calls(plot=plot_module.plot, + mpl=matplotlib_backend._draw, + plotly=plotly_backend.plotly_draw) as calls: + hyp.plot(data, show=False, panels=True, **kwargs) + return (calls.count['plot'], + calls.count['mpl'] + calls.count['plotly']) + + +@pytest.mark.parametrize('backend', ['matplotlib', 'plotly']) +def test_color_resolution_never_draws(backend): + """A shared-fit grid of n datasets makes the call itself, one probe + (the fit) and n panel calls; an independent-fit grid one probe per + panel. With nothing to resolve -- no `hue=`, clusters, legend or + colorbar -- that is ALL: no call is made for the colors. With + something to resolve, the resolution is one more `plot()` call (two + for independent fits, one of them before the fits) and NOT ONE more + draw: it stops before any geometry.""" + data = [X, X + 3, X - 3] + n = len(data) + base = dict(reduce=None, ndims=2, backend=backend) + hue = dict(hue=np.linspace(0, 1, 60), legend=False, colorbar=True) + + assert _count_calls(data, **base) == (2 + n, 1 + n) + assert _count_calls(data, **base, **hue) == (3 + n, 1 + n) + assert _count_calls(data, **base, legend=True) == (3 + n, 1 + n) + + independent = dict(base, panel_fit='independent') + assert _count_calls(data, **independent) == (1 + 2 * n, 2 * n) + assert _count_calls(data, **independent, **hue) \ + == (3 + 2 * n, 2 * n) + + +def test_color_resolution_creates_no_figure(): + """Only the probe's figure and the grid's are ever created.""" + data = [X, X + 3] + before = len(plt.get_fignums()) + with _Calls(new=plt.figure) as calls: + fig = _quiet(data, panels=True, reduce=None, ndims=2, + hue=np.linspace(0, 1, 40), colorbar=True) + assert calls.count['new'] <= 2 + assert len(plt.get_fignums()) == before + assert _shared_colorbar(fig) is not None From ba7f9ddccd56d2b176fc79aaa89d263bd5e1112f Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 09:45:12 -0500 Subject: [PATCH 38/58] fix: an RGB(A) tuple is one color under colorbar= when it is as long as the dataset count `color=(0.2, 0.4, 0.6)` with three datasets (or an RGBA tuple with four) is one color, as the drawing reads it; the colorbar read it as one entry per dataset, resolved ONE color for three labels and failed with matplotlib's "number of FixedLocator locations (1) ... does not match the number of labels (3)". The single-color check now comes before the per-group list in `_build_colorbar_info`. Single-axes plots and panel grids alike (also in 1.1.0). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/plot/plot.py | 22 ++++++++++++-------- tests/test_panels_review_round3.py | 32 +++++++++++++++++++++++++++++- 2 files changed, 45 insertions(+), 9 deletions(-) diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index af7c45a5d..d0792d77c 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -17168,8 +17168,18 @@ def _build_colorbar_info(colorbar, hue, multicolor_hue, cluster, n_clusters, labels = [i + 1 for i in range(n_groups)] explicit_colors = mpl_kwargs.get('color') + # ONE explicit color for every ungrouped dataset (``color='red'``, an + # RGB(A) tuple): recognized BEFORE the per-group list below, because a + # 3- or 4-number tuple is one color even when there happen to be three + # or four datasets (`_is_single_color`, as the drawing reads it) -- + # read as a list it resolved to one color for three labels, and the + # colorbar failed on the tick/label count + _one_color = (explicit_colors is not None and hue is None + and cluster is None and n_clusters is None + and (isinstance(explicit_colors, str) + or _is_single_color(explicit_colors))) if (isinstance(explicit_colors, (list, tuple)) - and len(explicit_colors) == n_groups): + and len(explicit_colors) == n_groups and not _one_color): # the mixture-blend paths (cluster= or matrix hue, # animated) set an EXPLICIT per-group color list -- reuse it # verbatim so the colorbar swatches exactly match the drawn lines. @@ -17181,13 +17191,9 @@ def _build_colorbar_info(colorbar, hue, multicolor_hue, cluster, n_clusters, # always-on color-scale resolution `bundle['colors']` added there). from matplotlib.colors import to_rgba_array colors = to_rgba_array(explicit_colors)[:, :3] - elif (explicit_colors is not None and hue is None and cluster is None - and n_clusters is None - and (isinstance(explicit_colors, str) - or _is_single_color(explicit_colors))): - # ONE explicit color for every ungrouped dataset - # (``color='red'``): the swatches are that color, the color the - # datasets are drawn in -- not the palette's, which nothing drew + elif _one_color: + # the swatches are that color, the color the datasets are drawn in + # -- not the palette's, which nothing drew from matplotlib.colors import to_rgba_array colors = np.tile(to_rgba_array([explicit_colors])[:, :3], (n_groups, 1)) diff --git a/tests/test_panels_review_round3.py b/tests/test_panels_review_round3.py index c5cd48edc..4d1362d4f 100644 --- a/tests/test_panels_review_round3.py +++ b/tests/test_panels_review_round3.py @@ -1,6 +1,9 @@ """1.2.0 review, round 3: a `panels=` grid's color resolution runs in the panels' own drawing mode and stops before any geometry, categories are -identified by themselves, and a matrix `hue=` is resolved once for the grid. +identified by themselves, a matrix `hue=` is resolved once for the grid -- +plus the single-axes defects found on the way (an RGB tuple under +`colorbar=`, a left/right animated title, a per-frame caption's extra +`on_frame=` call). Every test makes the real call and reads the real figure back; call counts are taken with `sys.setprofile` on the real functions (nothing is replaced). @@ -292,3 +295,30 @@ def test_color_resolution_creates_no_figure(): assert calls.count['new'] <= 2 assert len(plt.get_fignums()) == before assert _shared_colorbar(fig) is not None + + +# -------------------------------------------------------------------------- +# Codex 3 (single axes): an RGB(A) tuple is ONE color under colorbar= +# -------------------------------------------------------------------------- + +@pytest.mark.parametrize('color', [(0.2, 0.4, 0.6), (0.2, 0.4, 0.6, 1.0)], + ids=['rgb-3-datasets', 'rgba-4-datasets']) +@pytest.mark.parametrize('panels', [False, True], ids=['single', 'grid']) +def test_a_color_tuple_as_long_as_the_dataset_count_is_one_color( + color, panels): + """Three datasets and a three-number tuple: the tuple is one RGB color + (as the drawing reads it), not one entry per dataset. The colorbar + resolved ONE color for three labels and failed on the tick count.""" + data = [X + 3 * i for i in range(len(color))] + kwargs = dict(panels=True) if panels else {} + fig = _quiet(data, reduce=None, ndims=2, color=color, colorbar=True, + backend='matplotlib', **kwargs) + cax = _shared_colorbar(fig) if panels else fig.axes[-1] + assert _swatches(cax) == [tuple(color[:3])] * len(data) + fig.canvas.draw() + assert [t.get_text() for t in cax.get_yticklabels()] \ + == [str(i + 1) for i in range(len(data))] + lines = [line for ax in fig.axes if ax is not cax for line in ax.lines] + assert len(lines) == len(data) + assert all(to_rgb(line.get_color()) == tuple(color[:3]) + for line in lines) From bca7c05dae1be05dcbe784ac9965d957a61ae149 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 09:45:12 -0500 Subject: [PATCH 39/58] fix: room for an animated 2-D title set at loc='left' or 'right' matplotlib keeps three titles per axes; `ax.get_title()` and `ax.title` are the center one. With `title_kwargs={'loc': 'left'}` the room for a tall animated title was read and measured on the (empty) center title, so nothing was reserved and the title left the canvas. The title artist that `loc` selects is now the one read, measured and restored (`_title_artist`). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/plot/plot.py | 22 ++++++++++++++++++++-- tests/test_panels_review_round3.py | 27 ++++++++++++++++++++++++++- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index d0792d77c..b39e10b9d 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -16618,7 +16618,9 @@ def _sampled_dynamic_titles(): and xform[0].shape[1] < 3 and (title is not None or _segment_titles is not None or _dynamic_title is not None)): - _shown_title = ax.get_title() + # (the title `title_kwargs`' ``loc`` selects: matplotlib + # keeps a center, a left and a right one) + _shown_title = _title_artist(ax, _title_kwargs).get_text() if _dynamic_title is not None: _title_candidates = _sampled_dynamic_titles() elif _segment_titles is not None: @@ -17728,6 +17730,18 @@ def _tallest_title(texts): return best +def _title_artist(ax, title_kwargs=None): + """The ``Text`` that `ax.set_title` writes with `title_kwargs`: + matplotlib keeps three titles per axes -- center, left and right -- + and ``loc`` (default: ``rcParams['axes.titlelocation']``) selects + one. Reading, measuring or restoring "the title" has to use this one; + `ax.title` and `ax.get_title()` are the CENTER title only.""" + loc = (title_kwargs or {}).get('loc') \ + or plt.rcParams['axes.titlelocation'] + return {'left': ax._left_title, + 'right': ax._right_title}.get(str(loc).lower(), ax.title) + + def _reserve_animated_2d_title_room(fig, ax, tallest, shown, font=None, title_kwargs=None, pad_in=0.08): """Give an animated 2-D plot's title the room its TALLEST text needs. @@ -17747,7 +17761,11 @@ def _reserve_animated_2d_title_room(fig, ax, tallest, shown, font=None, if not tallest: return _apply_title(ax, tallest, font=font, title_kwargs=title_kwargs) - top = ax.title.get_window_extent(_measurement_renderer(fig)).y1 + # the artist `title_kwargs`' ``loc`` wrote to: with ``loc='left'`` the + # center title is empty, so measuring it reserved nothing and a tall + # left/right title stayed clipped + top = _title_artist(ax, title_kwargs).get_window_extent( + _measurement_renderer(fig)).y1 over_in = (top - fig.bbox.height) / fig.dpi if np.isfinite(over_in) and over_in > 0: _grow_figure(fig, top=over_in + pad_in) diff --git a/tests/test_panels_review_round3.py b/tests/test_panels_review_round3.py index 4d1362d4f..dca226d2d 100644 --- a/tests/test_panels_review_round3.py +++ b/tests/test_panels_review_round3.py @@ -22,7 +22,8 @@ import hypertools as hyp from hypertools.plot import matplotlib_backend, plotly_backend from hypertools.plot import plot as plot_module -from hypertools.plot.plot import SHARED_COLORBAR_GID, SHARED_LEGEND_GID +from hypertools.plot.plot import (SHARED_COLORBAR_GID, SHARED_LEGEND_GID, + _title_artist) X = np.random.default_rng(0).normal(size=(20, 2)).cumsum(0) ANIM = dict(animate=True, duration=1, frame_rate=4) @@ -322,3 +323,27 @@ def test_a_color_tuple_as_long_as_the_dataset_count_is_one_color( assert len(lines) == len(data) assert all(to_rgb(line.get_color()) == tuple(color[:3]) for line in lines) + + +# -------------------------------------------------------------------------- +# Codex 6 (single axes): room for a tall left/right animated title +# -------------------------------------------------------------------------- + +@pytest.mark.parametrize('loc', ['left', 'right', 'center']) +@pytest.mark.parametrize('ndims', [2, 3]) +def test_a_tall_animated_title_at_any_loc_is_inside_the_canvas(loc, ndims): + rng = np.random.default_rng(0) + data = rng.normal(size=(20, ndims)).cumsum(0) + title = '\n'.join(['Tall title'] * 12) + anim = _quiet(data, reduce=None, ndims=ndims, title=title, + title_kwargs={'loc': loc}, **ANIM) + fig = anim.figure + anim.draw_frame(0) + fig.canvas.draw() + artist = _title_artist(fig.axes[0], {'loc': loc}) + assert artist.get_text() == title + box = artist.get_window_extent() + assert box.height > 150 + assert box.y0 >= 0 and box.y1 <= fig.bbox.height + 0.5, ( + f'the title spans y={box.y0:.0f}..{box.y1:.0f} px on a ' + f'{fig.bbox.height:.0f} px canvas') From 56c82d34115c54d846d89ced2dae447cd17e35b3 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 09:45:12 -0500 Subject: [PATCH 40/58] fix: a per-frame caption no longer adds an on_frame= call for frame 0 on a save Every frame's caption is wrapped to the figure's width, and the wrap measured its text on a renderer taken from a real draw of the figure on a NEW canvas. During a save that replaced the canvas matplotlib had marked as saving, so the next frame's draw started the animation, which drew frame 0 again: `on_frame=` saw frame 0 three times with a callable `caption=` and `save_path=`, single plot or grid. The text is now measured on a bare renderer (`_text_metrics_renderer`): nothing is drawn and the figure keeps its canvas, which also saves one full figure draw per frame. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/plot/plot.py | 29 ++++++++++++++++++++++-- tests/test_panels_review_round3.py | 36 ++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index b39e10b9d..8765480d1 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -4603,10 +4603,35 @@ def _static_axes_artists(ax): return tuple(ax.lines) + tuple(ax.collections) +def _text_metrics_renderer(artist): + """A renderer that measures the text `artist` (a figure-level + ``Text``) WITHOUT drawing its figure and without touching the figure's + canvas: a bare Agg renderer of the figure's pixel size, kept on the + artist while that size stands. + + A per-frame caption is wrapped on every frame of an animation, a save + included. Measuring it through `_measurement_renderer` drew the whole + figure once more per frame and, worse, REPLACED the figure's canvas in + the middle of the save: matplotlib's guard against starting the + animation during a save (``canvas._is_saving``) sits on the canvas the + save began with, so the next frame's draw on the new canvas started + the animation, which drew frame 0 again and called every `on_frame=` + callback a third time for it (1.2.0 review, round 3).""" + from matplotlib.backends.backend_agg import RendererAgg + fig = artist.figure + width, height = fig.get_size_inches() * fig.dpi + key = (int(round(width)), int(round(height)), float(fig.dpi)) + cached = getattr(artist, '_hyp_metrics_renderer', None) + if cached is None or cached[0] != key: + cached = (key, RendererAgg(max(key[0], 1), max(key[1], 1), key[2])) + artist._hyp_metrics_renderer = cached + return cached[1] + + def _wrap_caption(artist, text): """`text` broken into lines no wider than the caption's figure (less `_CAPTION_SIDE_PAD_IN` on each side), measured in the caption's own - font on the figure's renderer. + font (`_text_metrics_renderer`: nothing is drawn). Lines break at spaces; a single word wider than the figure is broken between characters. The caller's own ``'\n'`` line breaks are kept. A @@ -4614,7 +4639,7 @@ def _wrap_caption(artist, text): split a formula. """ fig = artist.figure - renderer = _measurement_renderer(fig) + renderer = _text_metrics_renderer(artist) room_px = (fig.get_size_inches()[0] - 2 * _CAPTION_SIDE_PAD_IN) * fig.dpi shown, visible = artist.get_text(), artist.get_visible() # (an invisible Text reports no extent) diff --git a/tests/test_panels_review_round3.py b/tests/test_panels_review_round3.py index dca226d2d..46a3cf527 100644 --- a/tests/test_panels_review_round3.py +++ b/tests/test_panels_review_round3.py @@ -347,3 +347,39 @@ def test_a_tall_animated_title_at_any_loc_is_inside_the_canvas(loc, ndims): assert box.y0 >= 0 and box.y1 <= fig.bbox.height + 0.5, ( f'the title spans y={box.y0:.0f}..{box.y1:.0f} px on a ' f'{fig.bbox.height:.0f} px canvas') + + +# -------------------------------------------------------------------------- +# Q1: a per-frame caption adds no on_frame= call +# -------------------------------------------------------------------------- + +@pytest.mark.parametrize('grid', [{}, dict(panels=(1, 2))], + ids=['single', 'grid']) +@pytest.mark.parametrize('caption', [None, 'fixed', + lambda ctx: f'frame {ctx.frame}'], + ids=['no-caption', 'fixed', 'per-frame']) +def test_a_caption_does_not_change_how_often_on_frame_is_called( + tmp_path, grid, caption): + """A save calls `on_frame=` for frame 0 twice (docs/animation.rst): + ``n_frames + 1`` calls, with or without a caption, fixed or per frame. + Wrapping a per-frame caption used to replace the figure's canvas in + the middle of the save, which made matplotlib start the animation and + draw frame 0 a third time. Building the animation calls it for no + frame at all.""" + data = [X, X + 3] + seen = [] + anim = _quiet(data, reduce=None, ndims=2, caption=caption, + on_frame=lambda ctx: seen.append(ctx.frame), + **ANIM, **grid) + assert seen == [] + canvas = anim.figure.canvas + anim.save(str(tmp_path / 'later.gif')) + assert seen == [0] + list(range(anim.n_frames)) + # (the save drew on the canvas it started with) + assert anim.figure.canvas is canvas + + seen.clear() + saved = _quiet(data, reduce=None, ndims=2, caption=caption, + on_frame=lambda ctx: seen.append(ctx.frame), + save_path=str(tmp_path / 'direct.mp4'), **ANIM, **grid) + assert seen == [0] + list(range(saved.n_frames)) From 936ce71946632b4050571c75c02454e9a66803cc Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 09:50:04 -0500 Subject: [PATCH 41/58] fix: predict= in a panel grid: one plotly legend, one warning per call, the single-axes forecast_hue= error - plotly: every panel's `truth=` trace lists itself in its dataset's color, so a grid's "truth" entries looked different and the legend merge gave up, leaving "1, Kalman, truth" beside every panel. A drawn overlay trace is now merged like a forecast key: it keeps its color and one neutral data-free key takes the entry (`_neutral_legend_key`); overlay keys are ranked after every data entry. - A warning every panel call repeats word for word is re-issued once (`_reemit_panel_warnings`): `forecast_n_clusters=` without `forecast_cluster=`, "forecast_cluster= needs at least two forecasts". - The forecast-cost notice of an animated grid is issued once, with the grid's total fits and seconds: the panels' schedules report to one record (`forecast.grid_cost_report`, `ForecastSchedule(cost_report=)`), and the first schedule able to project its own cost projects the grid's. - A per-observation `forecast_hue=` (a list of arrays) raised "TypeError: unhashable type" from the grid's label slicing; it now raises the single-axes ValueError (`forecast.require_scalar_forecast_hue`). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/plot/forecast.py | 90 ++++++++++-- hypertools/plot/plot.py | 37 +++-- hypertools/plot/plotly_backend.py | 87 ++++++++++-- tests/test_panels_forecast_review_round3.py | 149 ++++++++++++++++++++ 4 files changed, 326 insertions(+), 37 deletions(-) create mode 100644 tests/test_panels_forecast_review_round3.py diff --git a/hypertools/plot/forecast.py b/hypertools/plot/forecast.py index ef8b9a3ce..2fff3e1f6 100644 --- a/hypertools/plot/forecast.py +++ b/hypertools/plot/forecast.py @@ -537,6 +537,30 @@ def project_schedule_cost(timings, remaining_rows): return projected, per_row, setup, (short, long) +def require_scalar_forecast_hue(labels): + """Raise the `forecast_hue=` error for a per-observation value: any + entry of `labels` that is itself a sequence. Shared by the single-axes + call and the `panels=` grid, which reads the labels before any panel + is drawn.""" + if any(isinstance(v, (list, tuple, np.ndarray)) for v in labels): + raise ValueError( + "forecast_hue= takes one SCALAR value per dataset (a " + "forecast is a single trace, so there is no per-observation " + "hue to take); got a sequence as one of its values. Pass " + "hue= to color the observed data per observation.") + + +def grid_cost_report(n_panels): + """The record a `panels=` grid's forecast schedules share so the grid + is warned about its forecast cost ONCE, with its total + (`ForecastSchedule`'s ``cost_report=``): how many `panels` and + `schedules` (one per panel and model; `plot()` sets it) there are, + how many are `done`, the seconds `spent` and `fits` counted so far, + and whether the grid was `warned`.""" + return {'panels': int(n_panels), 'schedules': int(n_panels), 'done': 0, + 'spent': 0.0, 'fits': 0, 'warned': False} + + class ForecastSchedule: """Every forecast an animation will ever draw, computed before drawing. @@ -554,7 +578,8 @@ class ForecastSchedule: def __init__(self, histories, counts=None, model=None, t=None, rows=None, min_history=DEFAULT_MIN_HISTORY, transform=None, slow_warning_seconds=DEFAULT_SLOW_WARNING_SECONDS, - forecast_function=None, heads=None, head_positions=None): + forecast_function=None, heads=None, head_positions=None, + cost_report=None): if (counts is None) == (rows is None): raise ValueError( "pass exactly one of counts= (a revealed ROW COUNT per " @@ -616,6 +641,14 @@ def __init__(self, histories, counts=None, model=None, t=None, rows=None, completed_fits = set() warned = slow_warning_seconds is None + # one of a `panels=` grid's schedules (`cost_report`, see + # `grid_cost_report`): the grid is warned about ONCE, with its + # total, by the first schedule that can project it + if cost_report is not None: + if cost_report['done'] >= cost_report['schedules']: + # (the grid is drawing its panels a second time) + cost_report.update(done=0, spent=0.0, fits=0) + warned = warned or cost_report['warned'] # Seconds keyed by revealed-history LENGTH, for fits that really # ran. A mapping rather than a list of samples, because the slope # needs two DIFFERENT lengths -- see the sampling comment below. @@ -677,7 +710,34 @@ def __init__(self, histories, counts=None, model=None, t=None, rows=None, 'spent': spent, 'remaining': projected, 'total': total, 'timed_fits': timed, } - if total > slow_warning_seconds: + if cost_report is not None: + # this schedule's cost stands for each one still to + # come: the grid's panels are drawn one after another + left = cost_report['schedules'] - cost_report['done'] + grid_total = cost_report['spent'] + total * left + grid_fits = cost_report['fits'] + fit_count * left + if grid_total > slow_warning_seconds: + cost_report['warned'] = True + warnings.warn( + f"predict= over this grid's animation needs " + f"about {grid_fits} forecast fits in all " + f"({cost_report['panels']} panels; one fit per " + f"distinct revealed history length in each), " + f"projected at roughly {grid_total:.1f} s in " + f"total before the first frame can be drawn. " + f"That projection is extrapolated from fits " + f"timed at two history lengths ({lengths[0]} " + f"and {lengths[1]} rows) in one panel, taking " + f"every panel still to come to cost what that " + f"one does, so treat it as an order of " + f"magnitude rather than a countdown. Every fit " + f"is kept: sampling the reveal instead would " + f"change what is plotted. To speed it up, " + f"shorten the series or lower " + f"frame_rate/duration; to silence this notice, " + f"pass slow_warning_seconds=None.", + stacklevel=3) + elif total > slow_warning_seconds: warnings.warn( f"predict= over this animation needs {fit_count} " f"forecast fits (one per distinct revealed history " @@ -695,13 +755,17 @@ def __init__(self, histories, counts=None, model=None, t=None, rows=None, f"slow_warning_seconds=None.", stacklevel=3) warned = True + if cost_report is not None: + cost_report['done'] += 1 + cost_report['spent'] += spent + cost_report['fits'] += fit_count # -- construction ------------------------------------------------------ @classmethod def for_parallel(cls, histories, grid_lengths, model, t, n_frames, min_history=DEFAULT_MIN_HISTORY, slow_warning_seconds=DEFAULT_SLOW_WARNING_SECONDS, - forecast_function=None, grids=None): + forecast_function=None, grids=None, cost_report=None): """Schedule for a parallel/`'window'` animation. Every dataset advances together, so each one's revealed row count @@ -728,13 +792,14 @@ def for_parallel(cls, histories, grid_lengths, model, t, n_frames, min_history=min_history, slow_warning_seconds=slow_warning_seconds, forecast_function=forecast_function, - heads=heads or None, head_positions=positions or None) + heads=heads or None, head_positions=positions or None, + cost_report=cost_report) @classmethod def for_serial(cls, histories, grid_lengths, model, t, n_frames, min_history=DEFAULT_MIN_HISTORY, slow_warning_seconds=DEFAULT_SLOW_WARNING_SECONDS, - forecast_function=None, grids=None): + forecast_function=None, grids=None, cost_report=None): """Serial reveals one dataset at a time, so its schedule comes from the backend's own `serial_reveal_counts` (animation-core Task 7), mapped from frame-grid rows onto raw rows dataset by dataset. The @@ -767,13 +832,14 @@ def for_serial(cls, histories, grid_lengths, model, t, n_frames, min_history=min_history, slow_warning_seconds=slow_warning_seconds, forecast_function=forecast_function, - heads=heads or None, head_positions=positions or None) + heads=heads or None, head_positions=positions or None, + cost_report=cost_report) @classmethod def for_regrouped(cls, histories, reveal, model, t, n_frames, min_history=DEFAULT_MIN_HISTORY, slow_warning_seconds=DEFAULT_SLOW_WARNING_SECONDS, - forecast_function=None, grids=None): + forecast_function=None, grids=None, cost_report=None): """Schedule for an animation whose data `hue=`/`cluster=` regrouped. The revealed rows come from a `DatasetRevealSchedule` rather than from @@ -808,7 +874,8 @@ def for_regrouped(cls, histories, reveal, model, t, n_frames, min_history=min_history, slow_warning_seconds=slow_warning_seconds, forecast_function=forecast_function, - heads=heads or None, head_positions=positions or None) + heads=heads or None, head_positions=positions or None, + cost_report=cost_report) # -- lookups ----------------------------------------------------------- def revealed_rows(self, dataset, frame): @@ -1474,12 +1541,7 @@ def resolve_forecast_overrides(n_datasets, forecasts=None, *, hue=None, # list of ARRAYS, and grouping by `==` on those raises numpy's # "truth value of an array is ambiguous" from deep inside the color # code. Say what was actually wrong instead. - if any(isinstance(v, (list, tuple, np.ndarray)) for v in labels): - raise ValueError( - "forecast_hue= takes one SCALAR value per dataset (a " - "forecast is a single trace, so there is no per-observation " - "hue to take); got a sequence as one of its values. Pass " - "hue= to color the observed data per observation.") + require_scalar_forecast_hue(labels) if len(labels) != n_datasets: raise ValueError( f"forecast_hue= must have exactly one value per FORECAST (a " diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index 8765480d1..8351d7541 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -3768,7 +3768,9 @@ def _panel_forecast_labels(hue, n_datasets, n_models): n_datasets + d`` is model ``k``'s forecast of dataset ``d``): a per-DATASET list is broadcast over every model's forecast of that dataset, a model-major list is taken as is. None for any other shape - (`plot()` reports it) and for a bare string (`plot()` rejects it).""" + (`plot()` reports it) and for a bare string (`plot()` rejects it); a + list of per-observation sequences raises `plot()`'s own ValueError + (`forecast.require_scalar_forecast_hue`).""" if hue is None or isinstance(hue, (str, bytes)): return None if is_series_like(hue): @@ -3778,6 +3780,10 @@ def _panel_forecast_labels(hue, n_datasets, n_models): if not isinstance(hue, (list, tuple, np.ndarray)): return None labels = list(hue) + # a per-observation value is refused as the single-axes call refuses + # it, not by a TypeError from hashing an array further on + from .forecast import require_scalar_forecast_hue + require_scalar_forecast_hue(labels) if len(labels) == n_datasets: return [labels[d] for _ in range(n_models) for d in range(n_datasets)] if len(labels) == n_datasets * n_models: @@ -4826,19 +4832,21 @@ def _panel_cluster_model(kw): def _reemit_panel_warnings(probe_caught, draw_caught): """Re-issue the warnings a panel grid's calls raised, each from its - original location: every draw-time warning (the panel calls warn from - the user's own kwargs, one per panel, as they always have), preceded - by the fit-time ones only the probes saw -- each of those ONCE, and - not at all when a panel call repeated it (round 7: the panels are - drawn through ``transform=``, so a reducer's own warning would - otherwise be lost with the probe's figure).""" + original location and each ONCE per grid call: the draw-time warnings + (the panel calls warn from the user's own kwargs; a warning every + panel repeats word for word is about the call, not about a panel), + preceded by the fit-time ones only the probes saw -- not at all when + a panel call repeated one (round 7: the panels are drawn through + ``transform=``, so a reducer's own warning would otherwise be lost + with the probe's figure). Warnings that differ in any word (a + dataset's name, a count) are all kept.""" seen = {(w.category, str(w.message)) for w in draw_caught} to_emit = [w for w in probe_caught if (w.category, str(w.message)) not in seen] emitted = set() for w in list(to_emit) + list(draw_caught): key = (w.category, str(w.message), w.filename, w.lineno) - if w in to_emit and key in emitted: + if key in emitted: continue emitted.add(key) registry = None @@ -6221,6 +6229,13 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): #: per panel, what `plot()` reads as ``_panel_shared``: the panel's #: share of the grid's color resolution (`_resolve_grid_colors`) panel_shared = [{} for _ in range(n_panels)] + if shared.get('predict') is not None: + # the panels' forecast schedules report to ONE record, so the + # forecast-cost warning is issued once, with the grid's total + from .forecast import grid_cost_report + _forecast_cost = grid_cost_report(n_panels) + for _shared in panel_shared: + _shared['forecast_cost'] = _forecast_cost #: whether a panel's categories turned out not to be the grid scale's #: (the grid then cannot claim one shared mapping) scale_mismatch = False @@ -15140,6 +15155,7 @@ def _build_schedule(model_spec): return ForecastSchedule.for_regrouped( analyze_histories, _reveal, model=model_spec, t=t, n_frames=_n_frames, slow_warning_seconds=_slow_secs, + cost_report=_cost_report, # one array per RUN here (hue=/cluster= regrouped the # data), which is exactly what the reveal indexes grids=xform, @@ -15147,6 +15163,7 @@ def _build_schedule(model_spec): return _builder( analyze_histories, _grid_lengths, model=model_spec, t=t, n_frames=_n_frames, slow_warning_seconds=_slow_secs, + cost_report=_cost_report, # the animation grid ITSELF, so each frame's forecast starts # at the vertex that frame actually draws last rather than at # the last raw observation behind it (maintainer report, @@ -15155,6 +15172,10 @@ def _build_schedule(model_spec): grids=xform, **_time_kwargs) + _cost_report = (_panel_shared or {}).get('forecast_cost') + if _cost_report is not None and _predict_names is not None: + _cost_report['schedules'] = ( + _cost_report['panels'] * len(_predict_names)) if _predict_names is None: forecast_schedule = _build_schedule(predict) else: diff --git a/hypertools/plot/plotly_backend.py b/hypertools/plot/plotly_backend.py index f7e85ffe8..8c47be55c 100644 --- a/hypertools/plot/plotly_backend.py +++ b/hypertools/plot/plotly_backend.py @@ -3278,11 +3278,14 @@ def merge_panel_legends(panels, order=None): ONCE between them -- the plotly twin of `hypertools.plot.plot._merge_panel_legends`, under the same rule: two entries with the same name and the same look are one (the later - traces keep their name but leave the legend); a forecast/truth key - (``meta['hyp_legend_entry']``) that differs between panels only in - color becomes one key in the neutral `FORECAST_LEGEND_COLOR`; any - other name that looks different in two panels raises - `PanelFurnitureConflict`. Same-named traces share a ``legendgroup``, + traces keep their name but leave the legend); a forecast/truth entry + -- a data-free key (``meta['hyp_legend_entry']``) or a drawn overlay + trace that lists itself (``meta['hyp_forecast_role']``: a panel's one + `truth=` trace) -- that differs between panels only in color becomes + one key in the neutral `FORECAST_LEGEND_COLOR` (a drawn trace keeps + its own color and hands the entry to a data-free key, + `_neutral_legend_key`); any other name that looks different in two + panels raises `PanelFurnitureConflict`. Same-named traces share a ``legendgroup``, so clicking the one entry toggles them in every panel, and the forecast/truth keys are ranked after the data entries. The data entries are listed in `order` -- their names in the order the @@ -3295,14 +3298,20 @@ def merge_panel_legends(panels, order=None): if not trace.showlegend: continue name = str(trace.name) - overlay = bool((trace.meta or {}).get('hyp_legend_entry')) \ - if isinstance(trace.meta, dict) else False + meta = trace.meta if isinstance(trace.meta, dict) else {} + overlay = bool(meta.get('hyp_legend_entry') + or meta.get('hyp_forecast_role')) look = _legend_trace_look(trace) shape = _legend_trace_look(trace, color=False) if trace.legendgroup is None: trace.legendgroup = f'hyp-shared-{name}' - if overlay and trace.legendrank is None: - trace.legendrank = 2000 + if overlay and (trace.legendrank is None + or trace.legendrank < 2000): + # after every data entry (ranked from 1000 below), in the + # order the panel's own legend lists its overlay keys (a + # truth key's 1001 follows the forecast keys' default) + trace.legendrank = 2000 + max( + 0, int(trace.legendrank or 1000) - 1000) same = kept.setdefault(name, []) match = [e for e in same if e['look'] == look] if match: @@ -3313,18 +3322,28 @@ def merge_panel_legends(panels, order=None): and e['shape'] == shape] if neutral: first = neutral[0]['trace'] - alpha = _color_alpha(first.line.color) - first.line.color = _to_plotly_color(FORECAST_LEGEND_COLOR, - alpha) - if first.marker is not None and first.marker.color is not None: - first.marker.color = first.line.color + first_meta = first.meta if isinstance(first.meta, dict) \ + else {} + if not first_meta.get('hyp_legend_entry'): + # a DRAWN overlay trace listed itself (one panel's + # truth): it keeps its color, and a data-free key + # takes the entry over for every panel + first = _neutral_legend_key(neutral[0]['panel'], first) + neutral[0]['trace'] = first + else: + alpha = _color_alpha(first.line.color) + first.line.color = _to_plotly_color( + FORECAST_LEGEND_COLOR, alpha) + if first.marker is not None \ + and first.marker.color is not None: + first.marker.color = first.line.color trace.showlegend = False trace.legendgroup = first.legendgroup continue if same: raise PanelFurnitureConflict(name) same.append({'look': look, 'shape': shape, 'overlay': overlay, - 'trace': trace}) + 'trace': trace, 'panel': panel}) data = [entry for same in kept.values() for entry in same if not entry['overlay']] names = [str(entry['trace'].name) for entry in data] @@ -3337,6 +3356,44 @@ def merge_panel_legends(panels, order=None): return bool(kept) +def _neutral_legend_key(panel, trace): + """Hand the legend entry of the drawn overlay `trace` (in the panel + figure `panel`) to a data-free key in the neutral + `FORECAST_LEGEND_COLOR`, and return that key: the same mode, line + style and marker, the trace's name, legend group and rank. The trace + itself stays as drawn and leaves the legend. For an entry that stands + for several panels' overlays of different colors (one `truth=` per + panel, each in its dataset's color), as the single-axes legend keys + them.""" + import plotly.graph_objects as go + from .forecast import FORECAST_LEGEND_COLOR + gray = _to_plotly_color(FORECAST_LEGEND_COLOR, + _color_alpha(trace.line.color)) + line = dict(trace.line.to_plotly_json(), color=gray) + key = dict(mode=trace.mode or 'lines', name=trace.name, + showlegend=True, hoverinfo='skip', line=line, + legendgroup=trace.legendgroup, legendrank=trace.legendrank, + legend=trace.legend, + meta=dict(hyp_legend_entry=str(trace.name))) + marker = (trace.marker.to_plotly_json() + if getattr(trace, 'marker', None) is not None else {}) + if 'markers' in (trace.mode or '') and marker: + size = marker.get('size') + if size is not None and np.ndim(size) > 0: + # (one size per vertex, where only the observations are + # marked: the key shows the marked size) + marker['size'] = float(np.max(np.asarray(size, dtype=float))) + key['marker'] = dict(marker, color=gray) + if isinstance(trace, go.Scatter3d): + panel.add_trace(go.Scatter3d(x=[None], y=[None], z=[None], **key)) + else: + panel.add_trace(go.Scatter(x=[None], y=[None], + xaxis=trace.xaxis, yaxis=trace.yaxis, + **key)) + trace.showlegend = False + return panel.data[-1] + + def _color_alpha(color): """The alpha of a plotly ``rgba(...)`` color string (1.0 for any other form).""" diff --git a/tests/test_panels_forecast_review_round3.py b/tests/test_panels_forecast_review_round3.py new file mode 100644 index 000000000..2967c4900 --- /dev/null +++ b/tests/test_panels_forecast_review_round3.py @@ -0,0 +1,149 @@ +"""1.2.0 review, round 3: `predict=` in a `panels=` grid -- one shared +plotly legend, one warning per grid call (the forecast-cost notice with +the grid's total), and the single-axes error for a per-observation +`forecast_hue=`. + +Real calls only; the figures and the warnings are read back as issued. +""" +import re +import warnings + +import matplotlib.pyplot as plt +import numpy as np +import pytest + +import hypertools as hyp + +N_PANELS = 4 +TRAIN = [np.random.default_rng(i).normal(size=(40, 3)).cumsum(0) + for i in range(N_PANELS)] +TRUTH = [np.random.default_rng(10 + i).normal(size=(10, 3)).cumsum(0) + + train[-1] for i, train in enumerate(TRAIN)] + + +@pytest.fixture(autouse=True) +def _close_figures(): + """Leave no figure behind.""" + yield + plt.close('all') + + +def _caught(*args, **kwargs): + """`hyp.plot(..., show=False)`: ``(result, [warning messages])``.""" + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + result = hyp.plot(*args, show=False, **kwargs) + return result, [str(w.message) for w in caught] + + +# -------------------------------------------------------------------------- +# Q2: the plotly grid lists forecast and truth entries once +# -------------------------------------------------------------------------- + +@pytest.mark.parametrize('ndims', [2, 3]) +def test_a_plotly_predict_grid_has_one_legend(ndims): + """Each panel's `truth=` trace lists itself, in its dataset's color; + four of them under one name were a "conflict" that sent the grid back + to a legend beside every panel (12 entries). They are one neutral + key, as in the matplotlib grid and the single-axes call.""" + train = [x[:, :ndims] for x in TRAIN] + truth = [x[:, :ndims] for x in TRUTH] + kwargs = dict(panels=(1, N_PANELS), predict='Kalman', t=10, truth=truth, + legend=True, reduce=None, ndims=ndims) + fig, _ = _caught(train, backend='plotly', **kwargs) + listed = [trace for trace in fig.data if trace.showlegend] + assert sorted(((t.legendrank, t.name) for t in listed)) == [ + (1000, '1'), (1001, '2'), (1002, '3'), (1003, '4'), + (2000, 'Kalman'), (2001, 'truth')] + # one legend for the figure + assert {t.legend for t in listed} == {'legend'} + assert [k for k in fig.layout if k.startswith('legend')] == ['legend'] + # the truth key is neutral; every drawn truth keeps its dataset's color + key, = [t for t in listed if t.name == 'truth'] + drawn = [t for t in fig.data + if (t.meta or {}).get('hyp_forecast_role') == 'truth'] + data = [t for t in listed if t.name in '1234'] + assert len(drawn) == N_PANELS and not any(t.showlegend for t in drawn) + assert [t.line.color for t in drawn] == [t.line.color for t in data] + assert key.line.color == key.marker.color == 'rgba(85,85,85,1.0)' + assert key.mode == drawn[0].mode + assert all(t.legendgroup == key.legendgroup for t in drawn) + + # the matplotlib grid lists the same six + mpl, _ = _caught(train, backend='matplotlib', **kwargs) + legend, = mpl.legends + assert [t.get_text() for t in legend.get_texts()] \ + == ['1', '2', '3', '4', 'Kalman', 'truth'] + + +# -------------------------------------------------------------------------- +# Q3: one warning per grid call +# -------------------------------------------------------------------------- + +@pytest.mark.parametrize('backend', ['matplotlib', 'plotly']) +@pytest.mark.parametrize('kwargs, message', [ + (dict(forecast_n_clusters=2), 'forecast_n_clusters= has no effect'), + (dict(forecast_cluster='KMeans'), + 'forecast_cluster= needs at least two forecasts'), +], ids=['n_clusters', 'cluster']) +def test_a_forecast_argument_warning_is_issued_once_per_grid( + backend, kwargs, message): + _, messages = _caught(TRAIN, panels=(1, N_PANELS), predict='Kalman', + t=10, backend=backend, **kwargs) + assert len([m for m in messages if message in m]) == 1, messages + + +def _fits(messages, pattern): + """The fit count of the one forecast-cost warning in `messages`.""" + found = [re.search(pattern, m) for m in messages] + found = [m for m in found if m] + assert len(found) == 1, messages + return int(found[0].group(1)), found[0].string + + +@pytest.mark.parametrize('predict, n_models', [ + ('Kalman', 1), (['Kalman', 'AutoRegressor'], 2)], + ids=['one-model', 'two-models']) +def test_the_forecast_cost_warning_is_one_with_the_grids_total( + predict, n_models): + """A threshold of 0 s makes every schedule's projection warn. Each + dataset alone warns with its own fit count; the grid of the four + warns ONCE, with their sum.""" + anim = dict(animate=True, duration=1, frame_rate=5, predict=predict, + t=5, slow_warning_seconds=0) + alone = 0 + for train in TRAIN: + _, messages = _caught(train, **anim) + cost = [m for m in messages if 'forecast fits' in m] + assert len(cost) == n_models + alone += sum(int(re.search(r'needs (\d+) forecast fits', m).group(1)) + for m in cost) + + grid, messages = _caught(TRAIN, panels=(1, N_PANELS), **anim) + total, text = _fits(messages, r'needs about (\d+) forecast fits in all') + assert total == alone + assert f'({N_PANELS} panels;' in text + seconds = float(re.search(r'roughly ([\d.]+) s in total', text).group(1)) + assert seconds > 0 + + # silenced like the single-axes notice + _, messages = _caught(TRAIN, panels=(1, N_PANELS), + **dict(anim, slow_warning_seconds=None)) + assert not [m for m in messages if 'forecast fits' in m] + + +# -------------------------------------------------------------------------- +# Q4: a per-observation forecast_hue= gets the single-axes error +# -------------------------------------------------------------------------- + +@pytest.mark.parametrize('hue', [ + [np.linspace(0, 1, 10)] * N_PANELS, + [[0.0, 1.0]] * N_PANELS, + [(1, 2)] * N_PANELS], ids=['arrays', 'lists', 'tuples']) +@pytest.mark.parametrize('grid', [{}, dict(panels=(1, N_PANELS))], + ids=['single', 'grid']) +def test_a_per_observation_forecast_hue_is_refused_clearly(hue, grid): + with pytest.raises(ValueError, + match='takes one SCALAR value per dataset'): + hyp.plot(TRAIN, predict='Kalman', t=10, forecast_hue=hue, + show=False, **grid) From 4fa5742265c97fddf6ff5bdb518cb49935162dcd Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 09:51:25 -0500 Subject: [PATCH 42/58] fix: an animate='morph' legend shows its keys The morphing datasets' own artists are hidden for the whole animation (the one traveling cloud is all that is drawn), and matplotlib copies an artist's visibility onto its legend key: the legend was labels with no glyphs, on single axes and in a panel grid (also in 1.1.0). Every legend hypertools builds now shows its keys (`show_legend_keys`): the dataset's marker in its color. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/plot/matplotlib_backend.py | 24 +++++++- hypertools/plot/plot.py | 8 +-- tests/test_morph_legend_keys.py | 79 +++++++++++++++++++++++++++ 3 files changed, 104 insertions(+), 7 deletions(-) create mode 100644 tests/test_morph_legend_keys.py diff --git a/hypertools/plot/matplotlib_backend.py b/hypertools/plot/matplotlib_backend.py index 1ad66613d..aa650f0a5 100644 --- a/hypertools/plot/matplotlib_backend.py +++ b/hypertools/plot/matplotlib_backend.py @@ -416,6 +416,23 @@ def legend_call_kwargs(is_3d=False, zlabel=None, font=None, return call +def show_legend_keys(legend): + """Make every key of `legend` visible, and return the legend. + + matplotlib builds a legend key as a copy of the artist it stands for, + visibility included. An ``animate='morph'`` animation HIDES each + morphing dataset's own artist for good -- the one traveling cloud is + all that is drawn -- so every key of its legend was an invisible copy: + labels with nothing beside them (1.2.0 review, round 3; also in + 1.1.0). A listed entry always shows its key: the dataset's marker in + its color.""" + if legend is not None: + for handle in legend.legend_handles: + if handle is not None and not handle.get_visible(): + handle.set_visible(True) + return legend + + def _recolor_legend_handles(legend, colors): """Apply `legend_colors=`'s plain color list to an already-built legend, in entry order (GH #285).""" @@ -3503,8 +3520,9 @@ def _trail_kwargs(kw): # explicit entries (matrix/mixture hue palette swatches, or # `legend_colors=[(label, color), ...]`): proxy handles, since # no drawn artist carries these labels. - ax.legend(handles=_legend_proxy_handles(legend_entries, fmt), - **_legend_call) + show_legend_keys(ax.legend( + handles=_legend_proxy_handles(legend_entries, fmt), + **_legend_call)) else: if legend_order: _handles, _labels = ax.get_legend_handles_labels() @@ -3518,7 +3536,7 @@ def _trail_kwargs(kw): _legend_call = dict( _legend_call, handles=[_handles[j] for j in _perm], labels=[_labels[j] for j in _perm]) - _legend_artist = ax.legend(**_legend_call) + _legend_artist = show_legend_keys(ax.legend(**_legend_call)) if legend_colors is not None: _recolor_legend_handles(_legend_artist, legend_colors) diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index 8351d7541..b4499f732 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -35,7 +35,7 @@ _looks_like_dataset_palettes) from ..reduce.reduce import reduce as reducer from ..tools.format_data import format_data -from .matplotlib_backend import _draw, _apply_title +from .matplotlib_backend import _draw, _apply_title, show_legend_keys from .backend import manage_backend from .plotly_backend import resolve_backend from .animation_context import FrameContext, FrameHooks @@ -908,7 +908,7 @@ def _add_overlay_legend_entries(ax, forecast_artists=None, truth_artists=None, marker=first.get_marker(), markersize=first.get_markersize(), markevery=None, label=truth_label)) labels.append(truth_label) - ax.legend(handles, labels, **legend_call) + show_legend_keys(ax.legend(handles, labels, **legend_call)) def _recolor_overlay_legend(ax, colors, close_fig=None): @@ -5559,7 +5559,7 @@ def _add_shared_furniture(fig, panel_axes, legend_spec, colorbar_info, _call = dict(call) if not fixed_columns and columns > 1: _call['ncols'] = columns - legend = fig.legend(handles, labels, **_call) + legend = show_legend_keys(fig.legend(handles, labels, **_call)) box = legend.get_window_extent(_measurement_renderer(fig)) size_in = (box.width / fig.dpi, box.height / fig.dpi) if side is None or side == 'over' or fixed_columns: @@ -5741,7 +5741,7 @@ def _wrap_shared_legend(fig, handles, labels, call, limit_in): wrapped = [label if label.count('$') >= 2 else (textwrap.fill(label, width=chars) or label) for label in labels] - legend = fig.legend(handles, wrapped, **call) + legend = show_legend_keys(fig.legend(handles, wrapped, **call)) box = legend.get_window_extent(_measurement_renderer(fig)) size_in = (box.width / fig.dpi, box.height / fig.dpi) if size_in[0] <= limit_in or chars <= _SHARED_LEGEND_MIN_WRAP: diff --git a/tests/test_morph_legend_keys.py b/tests/test_morph_legend_keys.py new file mode 100644 index 000000000..7e9c172ec --- /dev/null +++ b/tests/test_morph_legend_keys.py @@ -0,0 +1,79 @@ +"""An ``animate='morph'`` legend shows its keys (1.2.0 review, round 3; +also wrong in 1.1.0): the morphing datasets' own artists are hidden for +the whole animation, and matplotlib copied that onto the legend keys, so +the legend was a column of labels with nothing beside them. + +Real animations; the keys are read from the real legend and looked for in +the rendered pixels. +""" +import warnings + +import matplotlib.pyplot as plt +import numpy as np +import pytest +from matplotlib.colors import to_rgb + +import hypertools as hyp + +DATA = [np.random.default_rng(i).normal(size=(60, 5)) + i for i in range(3)] + +CASES = { + 'single-3d': {}, + 'single-2d': dict(ndims=2), + 'grid': dict(panels=(1, 3), + reduce=['PCA', 'FastICA', 'IncrementalPCA']), +} + + +@pytest.fixture(autouse=True) +def _close_figures(): + """Leave no figure behind.""" + yield + plt.close('all') + + +def _legend(fig): + """The figure's one legend (figure-level for a grid).""" + found = list(fig.legends) + [ax.get_legend() for ax in fig.axes + if ax.get_legend() is not None] + assert len(found) == 1 + return found[0] + + +def _pixels_near(fig, legend, color): + """How many pixels inside `legend`'s box are within 0.08 of `color` + in the figure as rendered.""" + fig.canvas.draw() + image = np.asarray(fig.canvas.buffer_rgba())[:, :, :3] / 255.0 + box = legend.get_window_extent() + height = image.shape[0] + crop = image[int(height - box.y1):int(height - box.y0), + int(box.x0):int(box.x1)] + return int((np.abs(crop - np.asarray(color)).max(axis=2) < 0.08).sum()) + + +@pytest.mark.parametrize('case', list(CASES)) +@pytest.mark.parametrize('frame', [0, 3, -1]) +def test_morph_legend_keys_show_the_marker_in_its_color(case, frame): + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + anim = hyp.plot(DATA, '.', animate='morph', legend=True, duration=2, + frame_rate=5, show=False, **CASES[case]) + reference = hyp.plot(DATA, '.', legend=True, show=False, + **{k: v for k, v in CASES[case].items() + if k == 'ndims'}) + anim.draw_frame(frame % anim.n_frames) + fig = anim.figure + legend = _legend(fig) + assert [t.get_text() for t in legend.get_texts()] == ['1', '2', '3'] + # the static plot of the same datasets keys them in the same colors + wanted = [to_rgb(h.get_color()) + for h in _legend(reference).legend_handles] + assert len(set(wanted)) == 3 + for handle, color in zip(legend.legend_handles, wanted): + assert handle.get_visible() + assert handle.get_marker() == '.' + assert handle.get_markersize() > 0 + assert to_rgb(handle.get_color()) == color + assert _pixels_near(fig, legend, color) >= 4, ( + f'no key of color {color} is drawn in the legend') From 69d1db574c7146f118fd14899445394ffc05a6f0 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 09:53:44 -0500 Subject: [PATCH 43/58] fix: giving up on a browser kills the processes that were started for it choreographer runs the browser under a wrapper it starts in a session of its own. scripts/render_multibyte_plotly.py left through `os._exit` at its deadline (or on a browser lifecycle error) and the wrapper, with the browser, lived on reparented to init for as long as the browser hung; the export path's `_kill_process_tree` signaled the worker's process group, which the wrapper had left. Both now read the process table once (`_descendant_pids`) and kill every descendant (`_kill_descendants`). The NO_BROWSER test watches the real process table while the script runs and asserts nothing the script started is alive after it exits; a second test kills a worker whose grandchild is in a session of its own. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/plot/plotly_backend.py | 78 +++++++++++++++++++- scripts/render_multibyte_plotly.py | 18 ++++- tests/test_animation_export.py | 51 +++++++++++++ tests/test_multibyte.py | 113 +++++++++++++++++++++++++++-- 4 files changed, 251 insertions(+), 9 deletions(-) diff --git a/hypertools/plot/plotly_backend.py b/hypertools/plot/plotly_backend.py index 8c47be55c..b7d3275cd 100644 --- a/hypertools/plot/plotly_backend.py +++ b/hypertools/plot/plotly_backend.py @@ -4143,14 +4143,89 @@ def _export_ceiling(n_frames): return max(_KALEIDO_MIN_CEILING, n_frames * _KALEIDO_CEILING_PER_FRAME) +def _descendant_pids(pid=None): + """Every live descendant of process `pid` (this process when None), as + process ids, parents before children. Read from ONE snapshot of the + process table (``ps`` on POSIX, PowerShell's ``Win32_Process`` on + Windows), so it also finds descendants that left the process group: + choreographer starts its browser wrapper in a session of its own, + which a ``killpg`` never reaches. Bounded, and an empty list when the + table cannot be read.""" + import subprocess + pid = os.getpid() if pid is None else int(pid) + if os.name == 'nt': + command = ['powershell', '-NoProfile', '-Command', + 'Get-CimInstance Win32_Process | ForEach-Object ' + '{ "$($_.ProcessId) $($_.ParentProcessId)" }'] + else: + command = ['ps', '-A', '-o', 'pid=,ppid='] + try: + lister = subprocess.Popen(command, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, text=True) + except OSError: + return [] + try: + listing, _ = lister.communicate(timeout=15) + except subprocess.TimeoutExpired: + lister.kill() + lister.communicate() + return [] + children = {} + for line in listing.splitlines(): + fields = line.split() + if len(fields) == 2 and fields[0].isdigit() and fields[1].isdigit(): + children.setdefault(int(fields[1]), []).append(int(fields[0])) + found, queue = [], [pid] + while queue: + for child in children.get(queue.pop(0), []): + # (the lister itself is a child of this process) + if child != lister.pid and child not in found: + found.append(child) + queue.append(child) + return found + + +def _kill_pids(pids): + """Kill each process in `pids` (children first), ignoring the ones + already gone. Best-effort and bounded.""" + import signal + import subprocess + for pid in reversed(list(pids)): + try: + if os.name == 'nt': + subprocess.run(['taskkill', '/F', '/PID', str(pid)], + capture_output=True, timeout=15) + else: + os.kill(pid, signal.SIGKILL) + except Exception: # noqa: BLE001 - teardown is best-effort + pass + + +def _kill_descendants(pid=None): + """Kill every descendant of process `pid` (this process when None) -- + what a process does before it gives up on a browser it started, so no + hung Chrome (or its wrapper) outlives it. Returns the process ids it + signaled.""" + pids = _descendant_pids(pid) + _kill_pids(pids) + return pids + + def _kill_process_tree(proc): """Kill a render subprocess AND its headless-Chrome children. On POSIX the subprocess is its own session leader, so the whole group is signaled; on - Windows ``taskkill /T`` walks the tree. Best-effort and BOUNDED at every + Windows ``taskkill /T`` walks the tree. Descendants that left the group + (choreographer's browser wrapper starts a session of its own) are found + in the process table BEFORE the kill -- afterwards they are orphans no + one can trace -- and killed too. Best-effort and BOUNDED at every step -- including `taskkill` itself, which is a subprocess that can stall and would otherwise block the recovery path indefinitely.""" import signal import subprocess + try: + strays = _descendant_pids(proc.pid) + except Exception: # noqa: BLE001 - teardown is best-effort + strays = [] try: if os.name == 'nt': try: @@ -4174,6 +4249,7 @@ def _kill_process_tree(proc): proc.kill() except Exception: # noqa: BLE001 pass + _kill_pids(strays) try: proc.wait(timeout=15) except Exception: # noqa: BLE001 diff --git a/scripts/render_multibyte_plotly.py b/scripts/render_multibyte_plotly.py index f7ad274eb..913d3297c 100644 --- a/scripts/render_multibyte_plotly.py +++ b/scripts/render_multibyte_plotly.py @@ -96,8 +96,22 @@ def _write_image(fig, out_png): kopts={'path': override, 'timeout': 30}) +def _kill_started_processes(): + """Kill every process this script started (the browser, and the + wrapper choreographer runs it under in a session of its own) before + giving up on the browser: `os._exit` runs no cleanup, and a browser + that never answers would otherwise outlive the script, reparented to + init, for as long as it hangs. Never raises.""" + try: + from hypertools.plot.plotly_backend import _kill_descendants + _kill_descendants() + except Exception: + pass + + def _exit_now(code): - """Leave with `code` WITHOUT joining other threads. + """Leave with `code` WITHOUT joining other threads, after killing the + processes this script started (`_kill_started_processes`). After a failed browser launch choreographer leaves non-daemon worker threads blocked on a queue and a pipe read, and a normal exit waits for @@ -112,6 +126,7 @@ def _exit_now(code): stream.flush() except Exception: pass + _kill_started_processes() os._exit(code) @@ -142,6 +157,7 @@ def _give_up(): # os.write, not print: another thread may hold sys.stderr's lock os.write(2, (f'NO_BROWSER: TimeoutError: the browser did not answer ' f'within {deadline:g} s\n').encode()) + _kill_started_processes() os._exit(NO_BROWSER_EXIT) # the export thread cannot be interrupted watchdog = threading.Timer(deadline, _give_up) diff --git a/tests/test_animation_export.py b/tests/test_animation_export.py index 4b3d55eca..9bd3aa3ff 100644 --- a/tests/test_animation_export.py +++ b/tests/test_animation_export.py @@ -4,6 +4,7 @@ import importlib import os import shutil +import signal import subprocess import sys import time @@ -287,6 +288,56 @@ def test_kill_process_tree_terminates_a_hung_subprocess_bounded(): assert time.time() - t0 < 20 # ... and bounded +@pytest.mark.skipif(os.name == 'nt', reason='sessions are a POSIX notion') +def test_kill_process_tree_reaches_a_descendant_in_its_own_session(tmp_path): + """choreographer runs the browser under a wrapper it starts in a NEW + session, which the group kill never reaches: after the render worker + was killed, the wrapper (and a hung Chrome) lived on, reparented to + init (1.2.0 review, round 3). Real processes: a child that starts a + grandchild in a session of its own and reports its pid.""" + pid_file = tmp_path / 'grandchild.pid' + child = ( + 'import subprocess, sys, time\n' + 'g = subprocess.Popen([sys.executable, "-c", ' + '"import time; time.sleep(600)"], start_new_session=True)\n' + f'open({str(pid_file)!r}, "w").write(str(g.pid))\n' + 'time.sleep(600)\n') + proc = subprocess.Popen([sys.executable, '-c', child], + start_new_session=True) + grandchild = None + try: + deadline = time.time() + 30 + while time.time() < deadline: + if pid_file.exists() and pid_file.read_text().strip(): + grandchild = int(pid_file.read_text()) + break + time.sleep(0.1) + assert grandchild is not None + assert grandchild in _pb._descendant_pids(proc.pid) + os.kill(grandchild, 0) # alive + _pb._kill_process_tree(proc) + assert proc.poll() is not None + deadline = time.time() + 10 + while time.time() < deadline and _is_running(grandchild): + time.sleep(0.25) + assert not _is_running(grandchild) + finally: + if proc.poll() is None: + proc.kill() + proc.wait() + if grandchild is not None and _is_running(grandchild): + os.kill(grandchild, signal.SIGKILL) + + +def _is_running(pid): + """Whether process `pid` is listed as running (a zombie awaiting its + reaper is not), from the real process table.""" + listing = subprocess.run(['ps', '-o', 'stat=', '-p', str(pid)], + capture_output=True, text=True, timeout=30) + state = listing.stdout.strip() + return bool(state) and not state.startswith('Z') + + def test_wait_with_progress_kills_a_stalled_render(): # no new frame ever completes -> wedged -> killed within the stall timeout, # regardless of how many frames the export has in total diff --git a/tests/test_multibyte.py b/tests/test_multibyte.py index 6d5f2cedc..09977edc8 100644 --- a/tests/test_multibyte.py +++ b/tests/test_multibyte.py @@ -22,8 +22,10 @@ import importlib.util import json import os +import signal import subprocess import sys +import time import warnings import numpy as np @@ -1052,6 +1054,79 @@ def leaks_stop_iteration(): f'{caught!r} is unrelated to the browser: {caught}') +def _process_table(): + """The live processes as ``{pid: (parent pid, command line)}``, from + one ``ps`` snapshot (POSIX).""" + listing = subprocess.run(['ps', '-A', '-o', 'pid=,ppid=,command='], + capture_output=True, text=True, timeout=30) + table = {} + for line in listing.stdout.splitlines(): + fields = line.split(None, 2) + if len(fields) >= 2 and fields[0].isdigit() and fields[1].isdigit(): + table[int(fields[0])] = (int(fields[1]), + fields[2] if len(fields) > 2 else '') + return table + + +def _descendants(pid): + """``{pid: command line}`` of every live descendant of process `pid` + (the ``ps`` that listed them excluded).""" + table = _process_table() + found, queue = {}, [pid] + while queue: + parent = queue.pop() + for child, (ppid, command) in table.items(): + if ppid == parent and child not in found \ + and not command.startswith('ps -A'): + found[child] = command + queue.append(child) + return found + + +def _alive(started): + """The entries of `started` (``{pid: command line}``) still running + the same command.""" + table = _process_table() + return {pid: command for pid, command in started.items() + if pid in table and table[pid][1] == command} + + +def _run_render_watching_its_processes(out_path, env, tmp_path): + """`_run_render`, also returning every process the render script was + seen to start while it ran (``{pid: command line}``, polled from the + real process table twice a second).""" + full = dict(os.environ) + full.update(env or {}) + started = {} + with open(tmp_path / 'render.out', 'w+') as out, \ + open(tmp_path / 'render.err', 'w+') as err: + proc = subprocess.Popen( + [sys.executable, _RENDER_PLOTLY_SCRIPT, json.dumps(['a', 'b']), + '', out_path], stdout=out, stderr=err, env=full) + limit = time.monotonic() + _KALEIDO_TIMEOUT_S + try: + while proc.poll() is None: + started.update(_descendants(proc.pid)) + if time.monotonic() > limit: + proc.kill() + proc.wait() + err.seek(0) + pytest.fail( + f'the render script did not finish in ' + f'{_KALEIDO_TIMEOUT_S} s.\n--- stderr ---\n' + f'{err.read()[-6000:]}') + time.sleep(0.5) + finally: + if proc.poll() is None: + proc.kill() + proc.wait() + out.seek(0) + err.seek(0) + result = subprocess.CompletedProcess(proc.args, proc.returncode, + out.read(), err.read()) + return result, started + + @requires_covering_font @pytest.mark.skipif(os.name == 'nt', reason='the stand-in browser is a POSIX shell script') def test_render_script_exits_NO_BROWSER_when_the_browser_never_answers( @@ -1066,10 +1141,34 @@ def test_render_script_exits_NO_BROWSER_when_the_browser_never_answers( silent = tmp_path / 'silent-browser' silent.write_text('#!/bin/sh\nexec sleep 600\n') silent.chmod(0o755) - result = _run_render(str(tmp_path / 'never.png'), - {_BROWSER_PATH_ENV: str(silent), - _render_mod.DEADLINE_ENV: '15'}) - assert result.returncode == _NO_BROWSER_EXIT, ( - f'expected exit {_NO_BROWSER_EXIT}, got {result.returncode}\n' - f'stderr:\n{result.stderr[-800:]}') - assert 'NO_BROWSER:' in result.stderr + result, started = _run_render_watching_its_processes( + str(tmp_path / 'never.png'), + {_BROWSER_PATH_ENV: str(silent), _render_mod.DEADLINE_ENV: '15'}, + tmp_path) + try: + assert result.returncode == _NO_BROWSER_EXIT, ( + f'expected exit {_NO_BROWSER_EXIT}, got {result.returncode}\n' + f'stderr:\n{result.stderr[-800:]}') + assert 'NO_BROWSER:' in result.stderr + # ...and it takes down what it started (review round 3, Q6): the + # stand-in browser, and the wrapper choreographer runs it under in + # a session of its own, used to outlive the script by the stand-in's + # whole 600 s, reparented to init -- in real use, a hung Chrome + # left behind after hypertools gave up + assert any('silent-browser' in command + for command in started.values()), ( + f'the stand-in browser was never seen running: {started}') + deadline = time.monotonic() + 10 + alive = _alive(started) + while alive and time.monotonic() < deadline: + time.sleep(0.25) + alive = _alive(started) + assert not alive, ( + f'processes the render script started outlived it: {alive}') + finally: + # whatever the verdict, this test leaves nothing running + for pid in _alive(started): + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass From 770dcf483d73fe57364f5a37bad8c57eb1b6681f Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 09:54:22 -0500 Subject: [PATCH 44/58] test: the plain-matplotlib _stop test no longer leaves an undrawn-animation warning The test builds a bare FuncAnimation to document upstream's non-idempotent `_stop` and never draws it, so matplotlib warned "Animation was deleted without rendering anything" when it was collected. The assertions are unchanged. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- tests/test_animation_close_nbagg.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/test_animation_close_nbagg.py b/tests/test_animation_close_nbagg.py index bdbb434bc..cb9aaa038 100644 --- a/tests/test_animation_close_nbagg.py +++ b/tests/test_animation_close_nbagg.py @@ -52,6 +52,10 @@ def test_plain_matplotlib_stop_is_not_idempotent_so_the_guard_is_needed(): line, = ax.plot([0, 1], [0, 1]) fa = matplotlib.animation.FuncAnimation( fig, lambda i: (line.set_ydata([0, i % 2]),), frames=2, interval=50) + # (never drawn, on purpose: only `_stop` is under test. Without this, + # matplotlib warns "Animation was deleted without rendering anything" + # when `fa` is collected) + fa._draw_was_started = True fa._stop() with pytest.raises(AttributeError, match='remove_callback'): fa._stop() From 351b7581266f7b8a9b58804a85909d651cc74fcb Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 09:55:40 -0500 Subject: [PATCH 45/58] docs: changelog, docstrings and session notes for the round-3 review fixes The 1.2.0 summary also names the shared axis labels drawn on the outer panels only. New "Fixed" entries: morph legend keys, forecast warnings once per grid call, the grid's `forecast_hue=` error, processes killed when a browser is given up on; the colorbar and animated-title entries cover RGB(A) tuples and `loc='left'`/`'right'`. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- CHANGELOG.md | 44 +++++++++++++++++-- hypertools/plot/plot.py | 10 ++++- ...sion_2026-11-22_feat295-animated-panels.md | 29 ++++++++++++ 3 files changed, 77 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c530c2466..d24e69cb5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,9 @@ A feature release. `animate=` now works with `panels=` (one animation of the whole grid, GH #295), `caption=` adds a figure-level caption that can change every frame, and saved `.mp4` files start playing before they have fully downloaded. Panel grids changed in look: each dataset keeps one color across -the figure, the grid has one legend and one colorbar, and the default figure -is sized by the grid (see "Changed"). The release also carries the fixes for +the figure, the grid has one legend and one colorbar, shared axis labels are +drawn on the outer panels only, and the default figure is sized by the grid +(see "Changed"). The release also carries the fixes for noise and side effects met when `hyp.plot` draws into a figure the caller built (GH #290, #291, #292), first drafted as a 1.1.1 patch release that was never published. @@ -97,6 +98,13 @@ never published. every panel; a categorical `hue=` uses one category-to-color mapping (in 1.1.0 each panel mapped its own values and its own categories, so the same color could mean different things in neighboring panels). + A matrix `hue=` is resolved once for the grid too: RGB rows + (`hue_mode='rgb'`, or a wide matrix reduced to RGB) are reduced and + scaled over every panel's rows, and signed mixture weights are shifted + by one rule, so one hue row is one color in every panel. A category + keeps its own color when a `legend=` list gives two categories the + same name, and DataFrames with a row MultiIndex passed as a list are + colored per dataset like any other. Clusters from a shared fit already used one mapping. - *Resolved once, for the whole grid.* Everything the colors mean is resolved once, exactly as the single-axes call of all the datasets @@ -119,6 +127,11 @@ never published. `colorbar=True`; the second took the first palette color). Warnings about the whole call (the number of non-finite `hue=` values, a legend asked of a continuous `hue=`) are issued once, not once per panel. + Resolving the colors draws nothing: it stops before any geometry is + built, and is skipped when there is no `hue=`, clustering, legend or + colorbar to resolve. An animated grid is resolved as animated (a + mixture clustering's quantized groups take a discrete colorbar there, + as on one axes), and `font=` reaches the grid's one colorbar. - *Legend and colorbar.* The grid draws one legend (the union of the panels' entries, each once, in the order the single-axes call lists them: datasets in dataset order, categories and clusters in their own @@ -235,7 +248,29 @@ never published. - **A colorbar for datasets drawn in one explicit color shows that color.** `hyp.plot([a, b], color='red', colorbar=True)` drew red lines beside a colorbar of the palette's first two colors, and reported those - in the bundle's `'colors'`; both now show the color drawn. + in the bundle's `'colors'`; both now show the color drawn. An RGB or + RGBA tuple as long as the dataset count (`color=(0.2, 0.4, 0.6)` with + three datasets) is one color here as it is for the drawing; it was read + as one entry per dataset and the colorbar failed on its tick count. +- **An `animate='morph'` legend shows its keys.** The legend listed the + datasets' names with no marker beside them (the morphing datasets' own + artists are hidden, and the keys copied that); each key now shows the + dataset's marker in its color, on one axes and in a grid. +- **Forecast warnings are issued once per `panels=` call.** A warning + every panel repeated word for word (`forecast_n_clusters=` without + `forecast_cluster=`, "forecast_cluster= needs at least two forecasts") + is issued once, and an animated `predict=` grid's forecast-cost notice + is one warning giving the whole grid's fits and projected time (it was + one per panel, each projecting that panel alone). +- **A per-observation `forecast_hue=` in a grid gets the single-axes + error.** A list of arrays raised `TypeError: unhashable type: + 'numpy.ndarray'`; it now raises the `ValueError` that says + `forecast_hue=` takes one scalar per dataset. +- **Giving up on a browser that never answers no longer leaves it + running.** When a plotly image export is abandoned (a stalled + animation export, or `scripts/render_multibyte_plotly.py` at its + deadline), every process started for it is killed, including the + browser wrapper that runs in a session of its own. - **`names=` alone shows the legend on a plotly `panels=` grid.** `hyp.plot([a, b], panels=True, names=['a', 'b'], backend='plotly')` named the traces but hid the legend; it is shown, as on one axes and on @@ -271,7 +306,8 @@ never published. first, middle and last frames' titles (it was sized for frame 0), in a grid and in a single plot; a 2-D animation's figure grows upward for a title taller than its default margin (a fixed eight-line title left the - canvas). + canvas), also when `title_kwargs={'loc': 'left'}` or `'right'` places + it. - **A shared grid legend too wide for its figure is wrapped.** With a small explicit `size=`, long legend labels were clipped at the canvas edge; they are wrapped onto more lines instead. diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index b4499f732..643dad00b 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -9670,7 +9670,10 @@ def plot( plotted -- so the notice exists to make a long wait expected rather than mysterious. It is emitted once fits at two or more history lengths (one of at least 10 rows, or the longest available) have - been timed, not after the wait. + been timed, not after the wait. An animated `panels=` grid emits + ONE notice, for the whole grid: the total number of fits and the + projected time of all its panels, taking each panel still to come + to cost what the first one timed does. frame_rate (animation only) : int or float Frame rate for animation in frames per second (default: 30). @@ -10269,7 +10272,10 @@ def plot( finite value, or no labeled observation, is drawn in the neutral gray under the grid's scale; and a warning about the whole call (the number of non-finite `hue=` values, a legend asked of a - continuous `hue=`) is issued once, not once per panel. + continuous `hue=`, a forecast argument that has no effect) is + issued once, not once per panel. A matrix `hue=` is resolved once + as well: RGB rows are reduced and scaled over every panel's rows, + so one hue row is one color in every panel. The legend and the colorbar are then drawn ONCE for the figure: one legend holding the union of the panels' entries without diff --git a/notes/session_2026-11-22_feat295-animated-panels.md b/notes/session_2026-11-22_feat295-animated-panels.md index e0ca616b2..59186b47a 100644 --- a/notes/session_2026-11-22_feat295-animated-panels.md +++ b/notes/session_2026-11-22_feat295-animated-panels.md @@ -286,3 +286,32 @@ and animated through one path. - docs/prebuilt_gallery.json and docs/tutorials notebooks NOT touched: static and animated `panels=` gallery figures with axis labels change and need republishing at release. + +## Review round 3 fixes (2026-11-22, after c7b6d0b2) + +Brief: scratchpad `feat295/fix_round3.md` (Codex 1-8, tester Q1-Q5, suite Q6). All fixed; commits in order: + +| Commit | Items | Tests | +|-|-|-| +| ed4a491d | Codex 1, 2, 4, 5, 7, 8 (grid color resolution) | tests/test_panel_color_invariant.py (403 cases), tests/test_panels_review_round3.py | +| ba7f9ddc | Codex 3 (RGB(A) tuple under colorbar=) | tests/test_panels_review_round3.py | +| bca7c05d | Codex 6 (animated title at loc left/right) | tests/test_panels_review_round3.py | +| 56c82d34 | Q1 (per-frame caption added an on_frame= call) | tests/test_panels_review_round3.py | +| 936ce719 | Q2, Q3, Q4 (predict= grids) | tests/test_panels_forecast_review_round3.py | +| (next) | Q5 (morph legend keys) | tests/test_morph_legend_keys.py | +| (next) | Q6 (process tree on browser give-up) | tests/test_multibyte.py, tests/test_animation_export.py | + +How the color resolution works now: +- `_resolve_grid_colors` re-enters `plot()` with `_panel_shared={'resolve_only': True, ...}`; `plot()` returns right after `colorbar_info`/`colors_info` are built, before interpolation, figure creation or drawing. Arguments are forwarded by blacklist (`_GRID_RESOLUTION_DROPPED_KWARGS`), so `animate=`, `font=`, `antialias=` and the rest reach it. +- `_grid_needs_color_resolution`: no `hue=`/cluster/legend/colorbar means no resolution call at all. +- Categories are keyed by the category (never the legend label). Matrix hue: the resolver returns the resolved rows (`matrix_hue`: RGB rows, or shifted mixture weights) and the quantized blend groups (`blend_groups`); `_panel_apply_hue_scale` slices them per panel. +- Rule chosen: two categories given one `legend=` name keep their colors; the shared legend cannot show one name for two colors, so each panel keeps its own legend (existing conflict rule). +- Timings (best of 3/2, same machine, back to back): 12 panels x 5,000 rows with continuous hue 0.57 s -> 0.50 s; two 500,000-row datasets, no hue 0.24 s -> 0.18 s. + +Other rules chosen: +- Q3: identical draw-time warnings from several panels are re-issued once (`_reemit_panel_warnings`); the forecast-cost notice is issued by the first schedule able to project, as spent + that schedule's projection x schedules still to come (`forecast.grid_cost_report`). +- Q5: every legend hypertools builds forces its keys visible (`show_legend_keys`). +- Q6: `_descendant_pids` reads one `ps` snapshot (PowerShell on Windows; untested there) and `_kill_process_tree` now also kills descendants outside the process group. +- Q1 cause: `_wrap_caption` measured through `_measurement_renderer`, which replaces the figure's canvas; mid-save that drops matplotlib's `_is_saving` guard and the animation starts (extra frame 0). Now measured on a bare `RendererAgg` (`_text_metrics_renderer`). + +Scratch `repro.py` once wrote `tmp*/x.mp4` into the repo root; moved out to the scratchpad (`fix3/stray/`). From 03f986efb2d32cd451dab5d6fda9c313a1042dd5 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 09:55:50 -0500 Subject: [PATCH 46/58] test: drop two unused imports that failed the repository lint `ruff check .` (the CI lint step) reported F401 twice in tests/test_panels_shared_legend_colors.py. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- tests/test_panels_shared_legend_colors.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/test_panels_shared_legend_colors.py b/tests/test_panels_shared_legend_colors.py index 55ae02d38..89c8260f1 100644 --- a/tests/test_panels_shared_legend_colors.py +++ b/tests/test_panels_shared_legend_colors.py @@ -7,11 +7,10 @@ """ import warnings -import matplotlib import matplotlib.pyplot as plt import numpy as np import pytest -from matplotlib.colors import to_rgb, to_rgba +from matplotlib.colors import to_rgb import hypertools as hyp from hypertools.plot.plot import (CAPTION_GID, SHARED_COLORBAR_GID, From 35d515d2bda657334ec5c450204f04bdd0ff2a2e Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 10:01:39 -0500 Subject: [PATCH 47/58] notes: round-3 commit ids and final test counts Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- notes/session_2026-11-22_feat295-animated-panels.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/notes/session_2026-11-22_feat295-animated-panels.md b/notes/session_2026-11-22_feat295-animated-panels.md index 59186b47a..c77e3cfe5 100644 --- a/notes/session_2026-11-22_feat295-animated-panels.md +++ b/notes/session_2026-11-22_feat295-animated-panels.md @@ -298,8 +298,8 @@ Brief: scratchpad `feat295/fix_round3.md` (Codex 1-8, tester Q1-Q5, suite Q6). A | bca7c05d | Codex 6 (animated title at loc left/right) | tests/test_panels_review_round3.py | | 56c82d34 | Q1 (per-frame caption added an on_frame= call) | tests/test_panels_review_round3.py | | 936ce719 | Q2, Q3, Q4 (predict= grids) | tests/test_panels_forecast_review_round3.py | -| (next) | Q5 (morph legend keys) | tests/test_morph_legend_keys.py | -| (next) | Q6 (process tree on browser give-up) | tests/test_multibyte.py, tests/test_animation_export.py | +| 4fa57422 | Q5 (morph legend keys) | tests/test_morph_legend_keys.py | +| 69d1db57 | Q6 (process tree on browser give-up) | tests/test_multibyte.py, tests/test_animation_export.py | How the color resolution works now: - `_resolve_grid_colors` re-enters `plot()` with `_panel_shared={'resolve_only': True, ...}`; `plot()` returns right after `colorbar_info`/`colors_info` are built, before interpolation, figure creation or drawing. Arguments are forwarded by blacklist (`_GRID_RESOLUTION_DROPPED_KWARGS`), so `animate=`, `font=`, `antialias=` and the rest reach it. @@ -315,3 +315,5 @@ Other rules chosen: - Q1 cause: `_wrap_caption` measured through `_measurement_renderer`, which replaces the figure's canvas; mid-save that drops matplotlib's `_is_saving` guard and the animation starts (extra frame 0). Now measured on a bare `RendererAgg` (`_text_metrics_renderer`). Scratch `repro.py` once wrote `tmp*/x.mp4` into the repo root; moved out to the scratchpad (`fix3/stray/`). + +Final run of the brief's test list (99 files, 8 shards) at 03f986ef: 4132 passed, 13 skipped (release gate x6, example smoke x6, CI-only font check x1), 0 failed, no warnings. `ruff check .` clean. From 92d5ac936e05688802f57e075ef047d58759d241 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 10:12:48 -0500 Subject: [PATCH 48/58] fix: a panels= grid reduces its matrix hue= to RGB once The grid's shared probe and its color resolution (with panel_fit='independent', an early and a final resolution; in a reducer-list grid, every panel's probe and draw) each reduced a matrix hue= under color_reduce=: repeated work, and a stochastic reducer's randomness consumed more than once, so a seeded grid call did not draw the colors of the single-axes call. The calls a grid makes on the whole matrix now share one record of the reduction (_matrix_hue_to_rgb_once). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/plot/plot.py | 87 ++++++++++++++++++----- tests/test_panel_color_invariant.py | 104 ++++++++++++++++++++++++++++ 2 files changed, 172 insertions(+), 19 deletions(-) diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index 643dad00b..c8b8d443e 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -1759,6 +1759,30 @@ def _matrix_hue_to_rgb(hue_array, color_reduce): return rgb +def _matrix_hue_to_rgb_once(hue_array, color_reduce, cache): + """`_matrix_hue_to_rgb`, run at most ONCE per `panels=` grid call for + one matrix: `cache` is the dict a grid shares between the calls it + makes of `plot()` (``_panel_shared['matrix_cache']``: its probe, its + color resolution and, in a reducer-list grid, every panel), None in + any other call. The first of those calls reduces the matrix; the others + are given that very result for the same matrix (compared by value). + Reducing it again would repeat the work and, with a stochastic reducer, + consume randomness a second time -- so a seeded grid call would not + draw the colors of the equivalent single-axes call, and two panels of + one grid could disagree about a row's color.""" + if cache is None: + return _matrix_hue_to_rgb(hue_array, color_reduce) + source = np.asarray(hue_array, dtype=np.float64) + entries = cache.setdefault('rgb', []) + for seen, rgb in entries: + if seen.shape == source.shape and np.array_equal( + seen, source, equal_nan=True): + return rgb.copy() + rgb = _matrix_hue_to_rgb(source, color_reduce) + entries.append((source.copy(), np.array(rgb, copy=True))) + return rgb + + def _hierarchy_hue_per_leaf(hue, n_rows, n_leaves): """Normalize a hue argument to ONE value sequence per hierarchy leaf. @@ -4773,7 +4797,10 @@ def _panel_probe(data, kw, ndims, caught_warnings, panel_shared=None): `_reemit_panel_warnings`). `panel_shared` is the panel's share of the grid's color resolution (``plot``'s ``_panel_shared``), for a probe of ONE panel (``panel_fit='independent'``): the probe reads its `hue=` as - the panel's drawing call will.""" + the panel's drawing call will. A probe of EVERY dataset is given the + grid's ``'matrix_cache'`` there instead, so the matrix `hue=` it + reduces to RGB is not reduced again by the grid's color resolution + (`_matrix_hue_to_rgb_once`).""" probe_kwargs = dict(kw) if panel_shared: probe_kwargs['_panel_shared'] = dict(panel_shared) @@ -5017,7 +5044,8 @@ def _grid_needs_color_resolution(grid_kw): def _resolve_grid_colors(rows, grid_kw, ndims, caught_warnings, - clustering=None, furniture=True): + clustering=None, furniture=True, + matrix_cache=None): """Resolve, ONCE and for the whole grid, everything a one-panel-per- dataset `panels=` grid's colors mean -- exactly as the equivalent single-axes call of all the datasets resolves it, by running THAT @@ -5041,7 +5069,9 @@ def _resolve_grid_colors(rows, grid_kw, ndims, caught_warnings, dataset has, a `colorbar=` nothing can be put on), and its warnings are appended to `caught_warnings`, to be issued once for the grid (the number of non-finite hue values over all the panels, a legend asked of - a continuous hue). + a continuous hue). `matrix_cache` is the grid's record of the matrix + `hue=` it has already reduced to RGB (`_matrix_hue_to_rgb_once`): the + call reuses it rather than reducing the matrix again. Returns a dict: @@ -5075,14 +5105,15 @@ def _resolve_grid_colors(rows, grid_kw, ndims, caught_warnings, if clustering is not None: kw.update(cluster=clustering, n_clusters=None) report, colorbars = {}, [] + call_shared = {'colorbars': colorbars, 'report': report, + 'resolve_only': True} + if matrix_cache is not None: + call_shared['matrix_cache'] = matrix_cache with warnings.catch_warnings(record=True) as caught: warnings.simplefilter('always') probe = plot(rows, reduce=None, normalize=None, align=None, ndims=ndims, show=False, return_model=True, - backend='matplotlib', - _panel_shared={'colorbars': colorbars, - 'report': report, - 'resolve_only': True}, **kw) + backend='matplotlib', _panel_shared=call_shared, **kw) caught_warnings.extend(caught) legend = report.get('legend') groups = report.get('group_names') @@ -5105,7 +5136,7 @@ def _resolve_grid_colors(rows, grid_kw, ndims, caught_warnings, 'blend_groups': report.get('blend_groups')} -def _panel_hue_scale_probe(lengths, grid_kw): +def _panel_hue_scale_probe(lengths, grid_kw, matrix_cache=None): """What the single-axes call of every dataset resolves for the grid's `hue=` (a `_resolve_grid_colors` result, of which the scale, its categories and a matrix hue's rows are read), for @@ -5115,10 +5146,13 @@ def _panel_hue_scale_probe(lengths, grid_kw): names the grid's categories, not one panel's). Resolved on placeholder rows of the datasets' own lengths, without the legend and the colorbar; None when that fails -- the full resolution, run once the - panels are fit, then reports the error.""" + panels are fit, then reports the error. A matrix `hue=` this call + reduces to RGB is recorded in `matrix_cache`, where the full + resolution finds it.""" try: return _resolve_grid_colors( - _placeholder_rows(lengths), grid_kw, 3, [], furniture=False) + _placeholder_rows(lengths), grid_kw, 3, [], furniture=False, + matrix_cache=matrix_cache) except Exception: # noqa: BLE001 - reported by the full resolution return None @@ -6242,6 +6276,11 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): #: the grid's ONE clustering (a shared fit's), replayed by the color #: resolution over every dataset grid_clustering = None + #: the matrix `hue=` this grid call has reduced to RGB + #: (`_matrix_hue_to_rgb_once`), shared by every call the grid makes on + #: the whole matrix -- its probe(s), its color resolution(s) and a + #: reducer-list grid's panels -- so the matrix is reduced ONCE + matrix_cache = {} #: per panel: the input datasets it draws (for their index/column #: labels), its analyzed rows (one array per dataset), its fitted #: pipeline, and its narrowed kwargs @@ -6254,8 +6293,12 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): kw = dict(shared) kw['reduce'] = spec panel_kwargs.append(kw) - probes = [_panel_probe(x, kw, ndims, probe_warnings) + probes = [_panel_probe(x, kw, ndims, probe_warnings, + panel_shared={'matrix_cache': matrix_cache}) for kw in panel_kwargs] + # (each reducer panel draws EVERY dataset, under the whole hue) + for _shared in panel_shared: + _shared['matrix_cache'] = matrix_cache panel_xforms = [probe[0] for probe in probes] panel_pipelines = [probe[1] for probe in probes] grid_scale = probes[0][3] @@ -6288,7 +6331,7 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): # over -- BEFORE any of them runs: a ``{category: color}`` # palette names the GRID's categories, and a panel refused the # ones it does not hold - _early = _panel_hue_scale_probe(lengths, shared) + _early = _panel_hue_scale_probe(lengths, shared, matrix_cache) _starts = np.cumsum([0] + lengths) for i in range(n_panels): if not _panel_apply_hue_scale( @@ -6313,7 +6356,8 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): # would have made without panels=, take its analyzed (pre-display- # rescale) data, and give each panel its own dataset's rows xform, shared_pipeline, shared_clustering, grid_scale = _panel_probe( - x, shared, ndims, probe_warnings) + x, shared, ndims, probe_warnings, + panel_shared={'matrix_cache': matrix_cache}) lengths = [int(xi.shape[0]) for xi in xform] panel_sources = [[datasets[i]] for i in range(n_panels)] panel_xforms = [[xform[i]] for i in range(n_panels)] @@ -6396,7 +6440,7 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): _rows = [np.asarray(row) for row in _rows] resolution = _resolve_grid_colors( _rows, shared, panel_ndims, probe_warnings, - clustering=grid_clustering) + clustering=grid_clustering, matrix_cache=matrix_cache) grid_scale = resolved_scale = resolution['scale'] elif panel_fit == 'shared': resolved_scale = grid_scale @@ -10990,7 +11034,10 @@ def plot( # whole grid (reduced and scaled over every panel's rows), which the # panel draws as it is; and ``'blend_groups'``, the grid's # ``{quantized color: drawn color}`` for the groups a blended (mixture) - # coloring is quantized into. The grid's own RESOLUTION call + # coloring is quantized into; and ``'matrix_cache'``, a dict + # the grid shares between its calls so a matrix `hue=` is reduced to + # RGB once for all of them (`_matrix_hue_to_rgb_once`). The grid's + # own RESOLUTION call # (`_resolve_grid_colors`) passes ``'report'``, a dict this call fills # with what it resolved (its legend, its ``{category: color}``, the # RGB of a matrix hue, its blend groups), and ``'resolve_only'``: the @@ -11056,7 +11103,6 @@ def plot( # ...and, for the same reason, the COLUMN labels `ndims=1` series mode # names its per-column lines with (GH #285). _column_names = _capture_column_names(x) - # fmt: accept plain-bytes format strings like np.bytes_ (F01-017) -- # decoded here once so every downstream fmt consumer sees str. if isinstance(fmt, bytes): @@ -13335,8 +13381,9 @@ def _compute_forecasts(datasets): f"pass one weight ROW per row for every leaf.") if multicolor_hue.ndim == 2 and _matrix_hue_wants_rgb( multicolor_hue, color_reduce, hue_mode): - multicolor_hue = _matrix_hue_to_rgb(multicolor_hue, - color_reduce) + multicolor_hue = _matrix_hue_to_rgb_once( + multicolor_hue, color_reduce, + (_panel_shared or {}).get('matrix_cache')) multicolor_hue_is_rgb = True if legend is True or _legend_user_list: # a legend LIST is dropped here for the same reason @@ -13866,7 +13913,9 @@ def _compute_forecasts(datasets): elif hue_is_matrix and _matrix_hue_wants_rgb(hue_array, color_reduce, hue_mode): - hue_array = _matrix_hue_to_rgb(hue_array, color_reduce) + hue_array = _matrix_hue_to_rgb_once( + hue_array, color_reduce, + (_panel_shared or {}).get('matrix_cache')) multicolor_hue_is_rgb = True elif hue_is_matrix: # mixture weights: a SIGNED matrix is shifted row by row diff --git a/tests/test_panel_color_invariant.py b/tests/test_panel_color_invariant.py index f077a68a2..b159516a9 100644 --- a/tests/test_panel_color_invariant.py +++ b/tests/test_panel_color_invariant.py @@ -17,6 +17,7 @@ import pytest from matplotlib.collections import LineCollection, PathCollection from matplotlib.colors import to_rgba, to_rgba_array +from sklearn.base import BaseEstimator, TransformerMixin import hypertools as hyp from hypertools.plot.plot import SHARED_COLORBAR_GID @@ -313,3 +314,106 @@ def test_panel_colors_are_the_single_axes_calls(kwargs, factory, fmt, mode): f'{key}: grid {got.get(key)} != single {expected.get(key)}' for key in sorted(set(got) | set(expected)) if got.get(key) != expected.get(key))[:600]) + + +# -------------------------------------------------------------------------- +# 1.2.0 review round 4: a matrix `hue=` is reduced ONCE per grid call. +# -------------------------------------------------------------------------- + +class _CountingRandomProjection(BaseEstimator, TransformerMixin): + """A small real reducer (sklearn API): projects onto `n_components` + random directions drawn from numpy's GLOBAL random state at fit time -- + so two fits under one seed differ, as a stochastic embedding's do -- + and counts every fit made by any instance in `fits`.""" + + fits = 0 + + def __init__(self, n_components=3): + self.n_components = n_components + + def fit(self, X, y=None): + """Draw the projection (one more fit).""" + type(self).fits += 1 + X = np.asarray(X, dtype=float) + self.mean_ = X.mean(axis=0) + self.components_ = np.random.normal( + size=(self.n_components, X.shape[1])) + return self + + def transform(self, X): + """Project the rows of `X`.""" + return (np.asarray(X, dtype=float) - self.mean_) @ self.components_.T + + +def _seeded_draw(data, kwargs, seed=11): + """`_draw` with numpy's global random state reset to `seed` first, and + the number of reducer fits the call made.""" + _CountingRandomProjection.fits = 0 + np.random.seed(seed) + figure = _draw(data, kwargs) + return figure, _CountingRandomProjection.fits + + +def _assert_panels_match_single(single, grid): + """Every panel of `grid` draws its dataset's rows in the colors + `single` (the single-axes figure of all the datasets) gives them.""" + want = _row_colors(single.axes[0], 0, TOTAL - 1) + for i, ax in enumerate(grid.axes[:N_DATASETS]): + first, last = i * ROWS, (i + 1) * ROWS - 1 + expected = {key: value for key, value in want.items() + if first <= key[1] <= last} + assert expected + assert _row_colors(ax, first, last) == expected, f'panel {i}' + + +REDUCED_HUES = { + 'counting-class': {'color_reduce': _CountingRandomProjection}, + 'counting-spec': {'color_reduce': { + 'model': _CountingRandomProjection, + 'kwargs': {'n_components': 3}}}, +} + + +@pytest.mark.parametrize('fit', ['shared', 'independent']) +@pytest.mark.parametrize('fmt', ['-', 'o']) +@pytest.mark.parametrize('mode', ['static', 'reveal']) +@pytest.mark.parametrize('spec', list(REDUCED_HUES)) +def test_matrix_hue_is_reduced_once_per_grid(spec, mode, fmt, fit): + call = dict(REDUCED_HUES[spec], hue=_wide_matrix(), reduce=None, ndims=2, + fmt=fmt, **MODES[mode]) + single, single_fits = _seeded_draw(_datasets(), call) + assert single_fits == 1 + grid, grid_fits = _seeded_draw( + _datasets(), dict(call, panels=True, panel_fit=fit)) + assert grid_fits == 1, ( + f'the grid reduced its hue matrix {grid_fits} times') + # ...so, under one seed, the grid's colors are the single-axes call's + _assert_panels_match_single(single, grid) + + +@pytest.mark.parametrize('fit', ['shared', 'independent']) +def test_seeded_tsne_hue_colors_are_the_single_axes_calls(fit): + call = dict(hue=_wide_matrix(), reduce=None, ndims=2, fmt='o', + color_reduce={'model': 'TSNE', + 'kwargs': {'perplexity': 5, 'init': 'random'}}) + single, _ = _seeded_draw(_datasets(), call) + grid, _ = _seeded_draw(_datasets(), + dict(call, panels=True, panel_fit=fit)) + _assert_panels_match_single(single, grid) + + +@pytest.mark.parametrize('backend', ['matplotlib', 'plotly']) +def test_reducer_list_grid_reduces_its_matrix_hue_once(backend): + """A one-panel-per-REDUCER grid draws every dataset in every panel: + one reduction of the hue matrix colors all of them alike.""" + call = dict(hue=_wide_matrix(), color_reduce=_CountingRandomProjection, + reduce=['PCA', 'IncrementalPCA'], ndims=2, fmt='o', + panels=True, backend=backend) + grid, fits = _seeded_draw(_datasets(3), call) + assert fits == 1 + if backend == 'matplotlib': + first, second = ( + sorted(tuple(np.round(c, 6)) for coll in ax.collections + for c in to_rgba_array(coll.get_facecolor())) + for ax in grid.axes[:2]) + assert first and first == second From b18c34afbfcf100f18e99f81c996e48c4ea329c4 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 10:13:03 -0500 Subject: [PATCH 49/58] fix: a named mixture hue='s columns name the panels= grid's shared legend Each panel is handed its rows of the matrix the grid resolved as a bare array, so a DataFrame hue='s column names were lost and the shared legend read 1, 2, ... on both backends. The resolution now reports the names and every panel labels its swatches with them, as the single-axes call does. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/plot/plot.py | 21 +++++++++- tests/test_panel_color_invariant.py | 59 ++++++++++++++++++++++++++++- 2 files changed, 76 insertions(+), 4 deletions(-) diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index c8b8d443e..7e3aaaaac 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -5093,6 +5093,9 @@ def _resolve_grid_colors(rows, grid_kw, ndims, caught_warnings, - ``'matrix_hue'``: ``(kind, rows)`` for a matrix `hue=` -- ``'rgb'`` with the RGB of every observation, reduced and scaled over the whole grid, or ``'mixture'`` with its weight rows -- else None; + - ``'hue_columns'``: the column names of a matrix `hue=` given as a + DataFrame (what a mixture hue's legend entries are called), else + None; - ``'blend_groups'``: ``{quantized color: drawn color}`` where a blended coloring is drawn as quantized groups (animated mixture clusters, a matrix hue on markers), else None. @@ -5133,6 +5136,7 @@ def _resolve_grid_colors(rows, grid_kw, ndims, caught_warnings, else None), 'legend_order': None if order is None else list(order), 'matrix_hue': report.get('matrix_hue'), + 'hue_columns': report.get('hue_columns'), 'blend_groups': report.get('blend_groups')} @@ -5192,7 +5196,9 @@ def _panel_apply_hue_scale(kw, resolution, shared, rows=None): draws), and a matrix hue is replaced by the panel's rows (`rows`, its ``(start, stop)`` among the grid's observations) of the matrix the grid resolved -- RGB reduced and scaled over every panel - (``shared['hue_rgb']``), or its mixture weights. A blended coloring + (``shared['hue_rgb']``), or its mixture weights, with the matrix's + column names (``shared['hue_columns']``: the rows are a bare array, + and a mixture hue's legend names its columns). A blended coloring drawn as quantized groups takes the grid's group colors (``shared['blend_groups']``). Returns False when the panel has a category the scale does not know -- the grid then cannot claim one @@ -5210,6 +5216,8 @@ def _panel_apply_hue_scale(kw, resolution, shared, rows=None): values = np.asarray(values) if rows[1] <= len(values): kw['hue'] = values[rows[0]:rows[1]] + if resolution.get('hue_columns') is not None: + shared['hue_columns'] = list(resolution['hue_columns']) if kind == 'rgb': kw['hue_mode'] = 'rgb' kw['color_reduce'] = None @@ -11034,7 +11042,9 @@ def plot( # whole grid (reduced and scaled over every panel's rows), which the # panel draws as it is; and ``'blend_groups'``, the grid's # ``{quantized color: drawn color}`` for the groups a blended (mixture) - # coloring is quantized into; and ``'matrix_cache'``, a dict + # coloring is quantized into; ``'hue_columns'``, the column names of + # the grid's matrix `hue=` (this panel's rows of it are a bare array), + # which name the mixture legend's entries; ``'matrix_cache'``, a dict # the grid shares between its calls so a matrix `hue=` is reduced to # RGB once for all of them (`_matrix_hue_to_rgb_once`). The grid's # own RESOLUTION call @@ -13755,6 +13765,11 @@ def _compute_forecasts(datasets): _hue_column_names = list(hue.columns) elif is_series_like(hue): hue = _series_values_list(hue) + if (_hue_column_names is None + and (_panel_shared or {}).get('hue_columns') is not None): + # a `panels=` cell: its matrix hue is its rows of the matrix + # the grid resolved, a bare array; the names are the grid's + _hue_column_names = list(_panel_shared['hue_columns']) # NESTED per-dataset hue: when the data is a list of datasets, hue may # be given with the SAME nesting -- one hue sub-sequence per dataset, @@ -14754,6 +14769,8 @@ def _compute_forecasts(datasets): _grid_report.update( categories=dict(_by_category.get('categories') or {}), matrix_hue=_resolved_matrix_hue, + hue_columns=(None if _hue_column_names is None + else list(_hue_column_names)), blend_groups=_blend_group_colors) return {'colors': colors_info} diff --git a/tests/test_panel_color_invariant.py b/tests/test_panel_color_invariant.py index b159516a9..7b1fd42d2 100644 --- a/tests/test_panel_color_invariant.py +++ b/tests/test_panel_color_invariant.py @@ -20,7 +20,7 @@ from sklearn.base import BaseEstimator, TransformerMixin import hypertools as hyp -from hypertools.plot.plot import SHARED_COLORBAR_GID +from hypertools.plot.plot import SHARED_COLORBAR_GID, SHARED_LEGEND_GID ROWS = 12 N_DATASETS = 3 @@ -317,7 +317,8 @@ def test_panel_colors_are_the_single_axes_calls(kwargs, factory, fmt, mode): # -------------------------------------------------------------------------- -# 1.2.0 review round 4: a matrix `hue=` is reduced ONCE per grid call. +# 1.2.0 review round 4: a matrix `hue=` is reduced ONCE per grid call, and +# its column names reach the shared legend. # -------------------------------------------------------------------------- class _CountingRandomProjection(BaseEstimator, TransformerMixin): @@ -417,3 +418,57 @@ def test_reducer_list_grid_reduces_its_matrix_hue_once(backend): for c in to_rgba_array(coll.get_facecolor())) for ax in grid.axes[:2]) assert first and first == second + + +def _legend_entries(figure): + """The labels of the legend(s) `figure` shows: a matplotlib figure's + one legend (the grid's shared one, or the single axes') -- asserting + there is exactly one -- or a plotly figure's legend entries.""" + if hasattr(figure, 'data'): + return [trace.name for trace in figure.data + if trace.showlegend is not False and trace.name is not None] + legends = list(figure.legends) + [ + ax.get_legend() for ax in figure.axes if ax.get_legend() is not None] + assert len(legends) == 1, f'{len(legends)} legends' + return [text.get_text() for text in legends[0].get_texts()] + + +def _named_mixture(): + """Mixture weights as a DataFrame whose columns are named.""" + return pd.DataFrame(_mixture(), columns=['signal', 'noise', 'drift']) + + +@pytest.mark.parametrize('backend', ['matplotlib', 'plotly']) +@pytest.mark.parametrize('fit', ['shared', 'independent']) +@pytest.mark.parametrize('fmt', ['-', 'o']) +def test_mixture_hue_column_names_reach_the_shared_legend(fmt, fit, backend): + call = dict(hue=_named_mixture(), hue_mode='mixture', legend=True, + reduce=None, ndims=2, fmt=fmt, backend=backend) + single = _legend_entries(_draw(_datasets(), call)) + assert single == ['signal', 'noise', 'drift'] + grid = _draw(_datasets(), dict(call, panels=True, panel_fit=fit)) + assert _legend_entries(grid) == single + if backend == 'matplotlib': + assert grid.legends[0].get_gid() == SHARED_LEGEND_GID + + +def test_mixture_hue_column_names_reach_an_animated_grids_legend(): + call = dict(hue=_named_mixture(), hue_mode='mixture', legend=True, + reduce=None, ndims=2, **MODES['reveal']) + single = _legend_entries(_draw(_datasets(), call)) + assert single == ['signal', 'noise', 'drift'] + assert _legend_entries(_draw(_datasets(), dict(call, panels=True))) \ + == single + + +def test_mixture_hue_names_are_in_the_grids_color_scale(): + call = dict(hue=_named_mixture(), hue_mode='mixture', legend=True, + reduce=None, ndims=2, return_model=True, show=False) + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + single = hyp.plot(_datasets(), **call) + grid = hyp.plot(_datasets(), panels=True, **call) + assert list(single['colors']['categories']) == ['signal', 'noise', + 'drift'] + assert list(grid['colors']['categories']) \ + == list(single['colors']['categories']) From dc30f14c2520ff8596451d55c360a2a4d5f9bd0b Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 10:13:19 -0500 Subject: [PATCH 50/58] fix: an independent ndims=1 grid keeps its series' names in the shared legend Frames whose columns are named differently are resolved on bare rows (they cannot be stacked by feature name), which named every series 'dataset i' and installed that over the panel's own column name. The column names are now handed to the resolution beside the rows, so the legend, its order and the grid's color scale name each series by its column, as each dataset's own call does. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/plot/plot.py | 41 +++++++++++++++++------ tests/test_panel_color_invariant.py | 52 +++++++++++++++++++++++++++-- 2 files changed, 80 insertions(+), 13 deletions(-) diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index 7e3aaaaac..cca52b8d6 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -5045,7 +5045,7 @@ def _grid_needs_color_resolution(grid_kw): def _resolve_grid_colors(rows, grid_kw, ndims, caught_warnings, clustering=None, furniture=True, - matrix_cache=None): + matrix_cache=None, column_names=None): """Resolve, ONCE and for the whole grid, everything a one-panel-per- dataset `panels=` grid's colors mean -- exactly as the equivalent single-axes call of all the datasets resolves it, by running THAT @@ -5071,7 +5071,10 @@ def _resolve_grid_colors(rows, grid_kw, ndims, caught_warnings, number of non-finite hue values over all the panels, a legend asked of a continuous hue). `matrix_cache` is the grid's record of the matrix `hue=` it has already reduced to RGB (`_matrix_hue_to_rgb_once`): the - call reuses it rather than reducing the matrix again. + call reuses it rather than reducing the matrix again. `column_names` + is each dataset's column names (`_capture_column_names`) where `rows` + are bare arrays that cannot carry them: an `ndims=1` series is named + in the legend by its column. Returns a dict: @@ -5112,6 +5115,8 @@ def _resolve_grid_colors(rows, grid_kw, ndims, caught_warnings, 'resolve_only': True} if matrix_cache is not None: call_shared['matrix_cache'] = matrix_cache + if column_names is not None: + call_shared['series_columns'] = column_names with warnings.catch_warnings(record=True) as caught: warnings.simplefilter('always') probe = plot(rows, reduce=None, normalize=None, align=None, @@ -6432,6 +6437,8 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): if _grid_needs_color_resolution(shared): _rows = [_panel_frame(src[0], xf[0]) for src, xf in zip(panel_sources, panel_xforms)] + #: the rows' column names, where the rows cannot carry them + _row_columns = None if len({int(xf[0].shape[1]) if xf[0].ndim == 2 else 1 for xf in panel_xforms}) > 1: # panels of unequal width (independent fits) share no axes @@ -6441,14 +6448,17 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): if is_frame_dataset(row)}) > 1: # panels whose DataFrames name their columns differently # (independent fits: each panel has its own features) - # cannot be stacked by feature name; colors, legend entries - # and the colorbar do not depend on the names, so resolve - # them on the bare rows (this call refused such a grid - # outright) + # cannot be stacked by feature name, so the grid's colors + # are resolved on the bare rows (the single-axes call + # refuses such frames outright). Only an `ndims=1` series' + # legend entry depends on the names -- a series is called + # by its column -- so they are handed over beside the rows + _row_columns = _capture_column_names(_rows) _rows = [np.asarray(row) for row in _rows] resolution = _resolve_grid_colors( _rows, shared, panel_ndims, probe_warnings, - clustering=grid_clustering, matrix_cache=matrix_cache) + clustering=grid_clustering, matrix_cache=matrix_cache, + column_names=_row_columns) grid_scale = resolved_scale = resolution['scale'] elif panel_fit == 'shared': resolved_scale = grid_scale @@ -6474,8 +6484,9 @@ def _plot_panels_impl(x, panels, call_kwargs, _name='panels'): and kw.get('names') is None and _labels is not None and len(_labels) == n_panels): # the single-axes call numbers its datasets 1..n (or, in - # ndims=1 series mode, calls them 'dataset 1'..'dataset - # n'); every panel called its own dataset the first + # ndims=1 series mode, calls each by its column's name, + # 'dataset 1'..'dataset n' where it has none); every panel + # called its own dataset the first kw['legend'] = [_labels[i]] if resolution['legend_names'] is not None: # a `legend=` list naming the grid's categories/clusters: @@ -11046,8 +11057,9 @@ def plot( # the grid's matrix `hue=` (this panel's rows of it are a bare array), # which name the mixture legend's entries; ``'matrix_cache'``, a dict # the grid shares between its calls so a matrix `hue=` is reduced to - # RGB once for all of them (`_matrix_hue_to_rgb_once`). The grid's - # own RESOLUTION call + # RGB once for all of them (`_matrix_hue_to_rgb_once`); and + # ``'series_columns'``, each dataset's column names where the rows the + # call is given cannot carry them. The grid's own RESOLUTION call # (`_resolve_grid_colors`) passes ``'report'``, a dict this call fills # with what it resolved (its legend, its ``{category: color}``, the # RGB of a matrix hue, its blend groups), and ``'resolve_only'``: the @@ -11113,6 +11125,13 @@ def plot( # ...and, for the same reason, the COLUMN labels `ndims=1` series mode # names its per-column lines with (GH #285). _column_names = _capture_column_names(x) + if (_column_names is None + and (_panel_shared or {}).get('series_columns') is not None): + # a `panels=` grid's color resolution, run on bare rows because its + # frames name their columns differently: the names are still the + # series' names + _column_names = list(_panel_shared['series_columns']) + # fmt: accept plain-bytes format strings like np.bytes_ (F01-017) -- # decoded here once so every downstream fmt consumer sees str. if isinstance(fmt, bytes): diff --git a/tests/test_panel_color_invariant.py b/tests/test_panel_color_invariant.py index 7b1fd42d2..917879b63 100644 --- a/tests/test_panel_color_invariant.py +++ b/tests/test_panel_color_invariant.py @@ -317,8 +317,8 @@ def test_panel_colors_are_the_single_axes_calls(kwargs, factory, fmt, mode): # -------------------------------------------------------------------------- -# 1.2.0 review round 4: a matrix `hue=` is reduced ONCE per grid call, and -# its column names reach the shared legend. +# 1.2.0 review round 4: a matrix `hue=` is reduced ONCE per grid call, its +# column names reach the shared legend, and so do `ndims=1` series names. # -------------------------------------------------------------------------- class _CountingRandomProjection(BaseEstimator, TransformerMixin): @@ -472,3 +472,51 @@ def test_mixture_hue_names_are_in_the_grids_color_scale(): 'drift'] assert list(grid['colors']['categories']) \ == list(single['colors']['categories']) + + +def _series_frames(names): + """One single-column frame per name: a named series each.""" + return [pd.DataFrame({name: np.sin(np.arange(ROWS) / 2.0 + i)}) + for i, name in enumerate(names)] + + +@pytest.mark.parametrize('backend', ['matplotlib', 'plotly']) +def test_independent_series_grid_keeps_its_series_names(backend): + """Frames whose columns are named differently share no single-axes + call (it matches features by name and refuses them); each is a named + series, which the legend of its own call -- and of the single-axes call + of same-named series -- names by its column.""" + call = dict(reduce=None, ndims=1, legend=True, backend=backend) + frames = _series_frames(['temperature', 'pressure', 'humidity']) + own = [_legend_entries(_draw(frame, call)) for frame in frames] + assert own == [['temperature'], ['pressure'], ['humidity']] + same = _series_frames(['temperature'] * 3) + assert _legend_entries(_draw(same, call)) == ['temperature'] * 3 + grid = _draw(frames, dict(call, panels=True, panel_fit='independent')) + assert _legend_entries(grid) == ['temperature', 'pressure', 'humidity'] + + +def test_independent_series_grid_names_its_color_scale_by_series(): + frames = _series_frames(['temperature', 'pressure', 'humidity']) + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + grid = hyp.plot(frames, panels=True, panel_fit='independent', + reduce=None, ndims=1, legend=True, show=False, + return_model=True) + assert [str(label) for label in grid['colors']['labels']] \ + == ['temperature', 'pressure', 'humidity'] + lines = [ax.lines[0] for ax in grid['fig'].axes[:3]] + for line, color in zip(lines, grid['colors']['colors']): + assert np.allclose(to_rgba(line.get_color())[:3], + np.asarray(color)[:3], atol=1e-6) + + +def test_independent_two_column_series_grid_keeps_its_series_names(): + frames = [pd.DataFrame({'temperature': np.arange(ROWS, dtype=float), + 'humidity': np.arange(ROWS, dtype=float) ** 2}), + pd.DataFrame({'pressure': np.arange(ROWS, dtype=float), + 'wind': np.sqrt(np.arange(ROWS))})] + grid = _draw(frames, dict(reduce=None, ndims=1, legend=True, + panels=True, panel_fit='independent')) + assert _legend_entries(grid) == ['temperature', 'humidity', 'pressure', + 'wind'] From f6f11e095b8a21337aa680a4d8f539800bdbccec Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 10:13:53 -0500 Subject: [PATCH 51/58] docs: changelog and session notes for the round-4 review fixes Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- CHANGELOG.md | 7 ++++++- .../session_2026-11-22_feat295-animated-panels.md | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d24e69cb5..43da93472 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -101,7 +101,12 @@ never published. A matrix `hue=` is resolved once for the grid too: RGB rows (`hue_mode='rgb'`, or a wide matrix reduced to RGB) are reduced and scaled over every panel's rows, and signed mixture weights are shifted - by one rule, so one hue row is one color in every panel. A category + by one rule, so one hue row is one color in every panel. The matrix is + reduced exactly once per grid call, so a seeded call with a stochastic + `color_reduce=` draws the single-axes call's colors; that holds for a + one-panel-per-reducer grid as well, where 1.1.0 reduced the matrix + again for every panel and a stochastic reducer could give one hue row + a different color in each. A category keeps its own color when a `legend=` list gives two categories the same name, and DataFrames with a row MultiIndex passed as a list are colored per dataset like any other. diff --git a/notes/session_2026-11-22_feat295-animated-panels.md b/notes/session_2026-11-22_feat295-animated-panels.md index c77e3cfe5..f3f44476b 100644 --- a/notes/session_2026-11-22_feat295-animated-panels.md +++ b/notes/session_2026-11-22_feat295-animated-panels.md @@ -317,3 +317,18 @@ Other rules chosen: Scratch `repro.py` once wrote `tmp*/x.mp4` into the repo root; moved out to the scratchpad (`fix3/stray/`). Final run of the brief's test list (99 files, 8 shards) at 03f986ef: 4132 passed, 13 skipped (release gate x6, example smoke x6, CI-only font check x1), 0 failed, no warnings. `ruff check .` clean. + +## Review round 4 fixes (2026-11-22, after 35d515d2) + +Brief: scratchpad `feat295/fix_round4.md` (Codex fourth review, 3 items). All fixed; tests in `tests/test_panel_color_invariant.py`. + +| Commit | Item | Tests | +|-|-|-| +| 92d5ac93 | 1: matrix `hue=` + `color_reduce=` reduced twice per grid | `test_matrix_hue_is_reduced_once_per_grid`, `test_seeded_tsne_hue_colors_are_the_single_axes_calls`, `test_reducer_list_grid_reduces_its_matrix_hue_once` | +| b18c34af | 2: named mixture hue columns lost in the shared legend | `test_mixture_hue_column_names_reach_the_shared_legend`, `..._reach_an_animated_grids_legend`, `test_mixture_hue_names_are_in_the_grids_color_scale` | +| dc30f14c | 3: `ndims=1` series names lost under `panel_fit='independent'` with differing column names | `test_independent_series_grid_keeps_its_series_names`, `..._names_its_color_scale_by_series`, `test_independent_two_column_series_grid_keeps_its_series_names` | + +How: +- Item 1: `_plot_panels` owns one `matrix_cache` dict per grid call, passed in `_panel_shared['matrix_cache']` to every call made on the WHOLE matrix (shared probe, early and final resolution, and a reducer-list grid's probes and panel draws). `_matrix_hue_to_rgb_once` reduces on the first call and returns the stored RGB (matched by value) afterwards. Reducer-list grids went from 2 fits per panel to 1 per grid (noted in CHANGELOG, since 1.1.0 behavior changes there for a stochastic reducer). +- Item 2: the resolution reports `hue_columns`; `_panel_apply_hue_scale` puts them in `shared['hue_columns']`, which `plot()` uses as `_hue_column_names` when the panel's hue is a bare array. +- Item 3: the single-axes call REFUSES frames with differing column names (GH #132), so there is no single-axes legend to match for that exact data. Rule chosen: each series is called by its column name, which is what each dataset's own call and the single-axes call of same-named series read. The names are captured before the rows are stripped and handed to the resolution as `_panel_shared['series_columns']`, so legend labels, legend order and the bundle's `colors['labels']` all carry them. From c71d3a7b4e05362ca36eac2d26f45942cc1de919 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 10:19:41 -0500 Subject: [PATCH 52/58] test: the composition gate calls hyp.align with model=, not the deprecated align= Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- tests/test_aligned_composition_gate.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_aligned_composition_gate.py b/tests/test_aligned_composition_gate.py index 6e159f72f..c5f50982c 100644 --- a/tests/test_aligned_composition_gate.py +++ b/tests/test_aligned_composition_gate.py @@ -44,7 +44,7 @@ def _compose(mean_is_mean=True, heavier=True, mixture=True, date_title=True, advancing=True): """The composition the gate describes, with one claim optionally broken.""" reduced = [hyp.reduce(s, reduce='PCA', ndims=3) for s in _sectors()] - aligned = hyp.align(reduced, align='HyperAlign') + aligned = hyp.align(reduced, model='HyperAlign') market = np.mean(aligned, axis=0) if not mean_is_mean: market = market + 0.5 * np.std(market) # a shifted 'mean' From 55f8399ad7840fd0e1e159760de209002b14a896 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 10:35:25 -0500 Subject: [PATCH 53/58] test: recognize the stand-in browser by its sleep process too The stand-in execs 'sleep 600', so its own command line no longer names the script, and under load ps reports a process's bare name in parentheses with no arguments: the 'was it ever running' sanity check then saw '(Python)' and '(sleep)' only and failed. The leak assertion itself is unchanged. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- tests/test_multibyte.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/test_multibyte.py b/tests/test_multibyte.py index 09977edc8..46ecc8c92 100644 --- a/tests/test_multibyte.py +++ b/tests/test_multibyte.py @@ -1155,7 +1155,10 @@ def test_render_script_exits_NO_BROWSER_when_the_browser_never_answers( # a session of its own, used to outlive the script by the stand-in's # whole 600 s, reparented to init -- in real use, a hung Chrome # left behind after hypertools gave up - assert any('silent-browser' in command + # the stand-in `exec`s `sleep 600`, so its own command line reads + # "sleep 600"; only the wrapper's arguments name the script, and + # under load `ps` reports a bare "(sleep)" with no arguments at all + assert any('silent-browser' in command or 'sleep' in command for command in started.values()), ( f'the stand-in browser was never seen running: {started}') deadline = time.monotonic() + 10 From fa4e765b815bc2b48979091a639872f7e86d9823 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 11:10:06 -0500 Subject: [PATCH 54/58] docs: the gallery's own videos are fast start too sphinx-gallery saves an example's animation with matplotlib's stock ffmpeg writer, so every video on the documentation site had its index after the media data (found in the 1.2.0 gallery build: all 16 read ftyp, free, mdat, moov). The scraper now remuxes the videos each block wrote with -c copy -movflags +faststart; no frame is re-encoded. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- CHANGELOG.md | 1 + docs/_gallery_scrapers.py | 59 +++++++++++++++++++++++++++++++++ tests/test_docs_site_fixes.py | 61 +++++++++++++++++++++++++++++++++++ 3 files changed, 121 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 43da93472..f4caa088b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -80,6 +80,7 @@ never published. is still downloading instead of fetching the whole file first. This applies to `save_path=`, `HyperAnimation.save`, the streaming recorder and the plotly export; `.avi` and `.mkv` files are unchanged. + The videos in the documentation's example gallery are fast start as well. ### Changed diff --git a/docs/_gallery_scrapers.py b/docs/_gallery_scrapers.py index a61ebf2c5..ec57db12a 100644 --- a/docs/_gallery_scrapers.py +++ b/docs/_gallery_scrapers.py @@ -59,8 +59,67 @@ def matplotlib_and_hyperanimation_scraper(block, block_vars, gallery_conf, if ani._fig not in managed: # else the matplotlib scraper has it pending.append(ani) + image_dir = _image_dir(block_vars) + before = _video_stamps(image_dir) rst = [matplotlib_scraper(block, block_vars, gallery_conf, **kwargs)] for ani in pending: image_path = PurePosixPath(next(block_vars['image_path_iterator'])) rst.append(_anim_rst(ani, image_path, gallery_conf)) + _faststart_videos(image_dir, before) return '\n'.join(part for part in rst if part) + + +def _image_dir(block_vars): + """The directory this example's images and videos are written to, or + None when the iterator does not say (nothing is post-processed then).""" + import os + template = getattr(block_vars.get('image_path_iterator'), 'image_path', + None) + return os.path.dirname(template) if template else None + + +def _video_stamps(image_dir): + """``{path: (mtime_ns, size)}`` of the ``.mp4`` files in `image_dir`.""" + import glob + import os + if not image_dir: + return {} + stamps = {} + for path in glob.glob(os.path.join(glob.escape(image_dir), '*.mp4')): + stat = os.stat(path) + stamps[path] = (stat.st_mtime_ns, stat.st_size) + return stamps + + +def _faststart_videos(image_dir, before): + """Rewrite the videos this block wrote so they are "fast start". + + sphinx-gallery saves an example's animation with matplotlib's stock + ffmpeg writer, which puts the file's index (the ``moov`` atom) AFTER the + media data, so a browser has to fetch the whole clip before it can start + playing it. `hyp.plot(..., save_path=)` writes its own videos fast start + (GH #295); the gallery's are remuxed here to match. The remux copies the + encoded stream (``-c copy``): no frame is re-encoded or changed. + + Only files that are new or rewritten since `before` (see + `_video_stamps`) are touched. A failed remux leaves the original file in + place and raises, so a build cannot silently ship a half-written video. + """ + import os + import subprocess + import tempfile + for path, stamp in sorted(_video_stamps(image_dir).items()): + if before.get(path) == stamp: + continue + handle, tmp = tempfile.mkstemp(suffix='.mp4', + dir=os.path.dirname(path)) + os.close(handle) + try: + subprocess.run( + ['ffmpeg', '-y', '-loglevel', 'error', '-i', path, + '-c', 'copy', '-movflags', '+faststart', tmp], + check=True, capture_output=True) + os.replace(tmp, path) + finally: + if os.path.exists(tmp): + os.remove(tmp) diff --git a/tests/test_docs_site_fixes.py b/tests/test_docs_site_fixes.py index 9aad67fc3..f743c5bbd 100644 --- a/tests/test_docs_site_fixes.py +++ b/tests/test_docs_site_fixes.py @@ -145,6 +145,67 @@ def blocks(ns): assert _scrape_blocks(tmp_path, blocks) == [1, 1, 0] +def _top_level_atoms(path): + """The top-level atom names of an ISO media file, in file order.""" + import struct + names = [] + with open(path, 'rb') as f: + while True: + head = f.read(8) + if len(head) < 8: + break + size, name = struct.unpack('>I4s', head) + if size == 1: + size = struct.unpack('>Q', f.read(8))[0] + f.seek(size - 16, 1) + elif size == 0: + names.append(name.decode('latin-1')) + break + else: + f.seek(size - 8, 1) + names.append(name.decode('latin-1')) + return names + + +def test_gallery_videos_are_fast_start(tmp_path): + """The gallery's own videos start playing before they have fully + downloaded, like the ones `save_path=` writes (GH #295): the index + (`moov`) comes before the media data (`mdat`). sphinx-gallery's stock + writer puts it last; the scraper remuxes what each block wrote. Covers + both paths: a pyplot-managed animation (sphinx-gallery's scraper writes + it) and a `show=False` one (ours does), and the remux keeps every + frame.""" + import shutil + import subprocess + import hypertools as hyp + + def blocks(ns): + ns['fig'], ns['ani'] = hyp.plot(_data(), animate=True, + backend='matplotlib', duration=1) + yield + ns['hidden'] = hyp.plot(_data(), animate=True, show=False, + backend='matplotlib', duration=1) + yield + + assert _scrape_blocks(tmp_path, blocks) == [1, 1] + videos = sorted((tmp_path / 'images').glob('*.mp4')) + assert len(videos) == 2 + for video in videos: + atoms = _top_level_atoms(video) + assert atoms.index('moov') < atoms.index('mdat'), (video.name, atoms) + if shutil.which('ffprobe'): + frames = subprocess.run( + ['ffprobe', '-v', 'error', '-select_streams', 'v:0', + '-count_frames', '-show_entries', 'stream=nb_read_frames', + '-of', 'csv=p=0', str(video)], + check=True, capture_output=True, text=True).stdout.strip() + assert int(frames) == 30, (video.name, frames) + # no temporary file is left beside the videos (the remux writes its + # output to a temporary .mp4 first; the gif thumbnails are the build's) + assert sorted(p.suffix for p in (tmp_path / 'images').iterdir()) == [ + '.gif', '.gif', '.mp4', '.mp4'] + + def test_unmanaged_show_false_animation_is_still_scraped_once(tmp_path): """The reason the HyperAnimation scraper exists: ``show=False`` leaves the figure unmanaged by pyplot, so the matplotlib scraper never sees it. It From b81e1d2dac63467a2f383e72a726c56e3611be0b Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 11:14:20 -0500 Subject: [PATCH 55/58] docs: two example comments say what their figures show plot_autoencoders passes panels=(1, 3), not panels=True; the Datasaurus grid is 3 x 5 (found by the independent review of the 1.2.0 gallery). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- examples/plot_autoencoders.py | 2 +- examples/plot_datasaurus.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/plot_autoencoders.py b/examples/plot_autoencoders.py index 12639ac2e..b62dc1c63 100644 --- a/examples/plot_autoencoders.py +++ b/examples/plot_autoencoders.py @@ -15,7 +15,7 @@ noisy spiral manifold embedded in 10-D, with each point colored by its position along the spiral, so a reducer that unfolds the manifold shows a smooth color gradient. Passing `reduce=` a LIST gives one panel per reducer -(`panels=True`), so all three embeddings are computed and drawn by a single +(here `panels=(1, 3)`, one row), so all three embeddings are computed and drawn by a single `hyp.plot` call instead of three separate `hyp.reduce` calls plus a hand-built grid. """ diff --git a/examples/plot_datasaurus.py b/examples/plot_datasaurus.py index 58a6d7015..df82bd1fd 100644 --- a/examples/plot_datasaurus.py +++ b/examples/plot_datasaurus.py @@ -25,8 +25,8 @@ f'sd=({df.x.std():.2f}, {df.y.std():.2f}), ' f'r={df.x.corr(df.y):.2f}') -# small black dots via the '.' point marker; one panel per dataset, sized -# to a near-square grid, sharing one pipeline fit (a no-op here since +# small black dots via the '.' point marker; one panel per dataset, laid +# out automatically (3 rows of 5 here), sharing one pipeline fit (a no-op here since # ndims=2 already matches the data) fig = hyp.plot(datasets, '.', color='k', ndims=2, panels=True, title=[f'Dataset {i + 1}' for i in range(len(datasets))]) From 5f104d0adead7b69e45f81401109db2ac6be6d33 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 12:36:12 -0500 Subject: [PATCH 56/58] fix: text room is measured, not assumed (matplotlib 3.11 line metrics) Hosted CI on matplotlib 3.11.2 failed nine tests that pass on 3.10.8. matplotlib 3.11 changed two things hypertools relied on: * Text._get_layout takes a line's height from the font's own ascent, descent and line gap (OS/2 / hhea tables) instead of the measured height of the glyphs "lp". In Noto Sans, the bundled default face, a line is 1.362 em tall, against about 1.0 em (1.2 em between lines) before. * Axis3D no longer positions an axis label that has no text. Three places assumed the older behavior: * _add_caption reserved lines * 1.2 * font size under the figure, so a wrapped caption ended below the canvas. The room is now the height the wrapped text is laid out at, measured with the caption's own font at the figure's DPI (_caption_text_height_in), and never less than the nominal line grid, so figures drawn under 3.10 keep their size. * A shared axis label emptied on an inner 3-D panel kept the position of the draw made before the cubes were fitted, outside its panel. _place_emptied_cube_labels has matplotlib place the emptied labels once in the finished layout. * A static labeled 3-D grid at an explicit size= was reported as too small when the taller label boxes of one panel overlapped, although no cube size inside the panel's square can part them and blank room lay beside every square. Such a grid is now fitted once more with the labels let into that room (_label_gutter_room); it is kept only if the labels then clear, otherwise the grid is put back and the warning is raised as before. tests/test_text_room_measured.py checks each against the real renderer. The five gallery examples checked (animate_panels, plot_datasaurus, plot_shapes_zoo, plot_impute, plot_autoencoders) render byte-identical under matplotlib 3.10.8 before and after. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/plot/plot.py | 216 +++++++++++++-- ...sion_2026-11-22_feat295-animated-panels.md | 25 ++ tests/test_text_room_measured.py | 247 ++++++++++++++++++ 3 files changed, 468 insertions(+), 20 deletions(-) create mode 100644 tests/test_text_room_measured.py diff --git a/hypertools/plot/plot.py b/hypertools/plot/plot.py index cca52b8d6..9bf1289f8 100644 --- a/hypertools/plot/plot.py +++ b/hypertools/plot/plot.py @@ -4712,6 +4712,34 @@ def _fits(candidate): return '\n'.join(lines) +def _caption_text_height_in(artist, text): + """The height (inches) the caption `artist` takes when it shows the + already wrapped `text`: the extent matplotlib lays that text out in, + in the caption's own font at its figure's DPI (`_text_metrics_renderer`: + nothing is drawn, and the artist is left as it was). + + The room under a figure is reserved from THIS, not from a line count + times a nominal line height: how tall a line of text is belongs to + matplotlib and to the font. Up to matplotlib 3.10 a line is 1.2 times + the measured height of the glyphs ``lp``; from 3.11 on it is the + font's own ascent, descent and line gap (its ``OS/2``/``hhea`` + tables), which for many fonts is more than 1.2 times the font size -- + a room of ``lines * 1.2 * size`` then ended above the caption's last + line, which ran off the bottom of the canvas. + """ + shown, visible = artist.get_text(), artist.get_visible() + # (an invisible Text reports no extent) + artist.set_visible(True) + try: + artist.set_text(text) + height_px = artist.get_window_extent( + _text_metrics_renderer(artist)).height + finally: + artist.set_text(shown) + artist.set_visible(visible) + return float(height_px) / float(artist.figure.dpi) + + def _set_caption_text(artist, text): """Show `text` in the caption `artist`, wrapped to its figure's width (`_wrap_caption`): how every frame of a per-frame caption is set.""" @@ -4731,8 +4759,12 @@ def _add_caption(fig, text, font=None, family=None, samples=()): legend, a colorbar or a companion panel and always lies inside the canvas. - HOW THE ROOM'S HEIGHT IS DECIDED. The room holds as many lines as the - tallest of `text` and `samples` has once wrapped. `text` is what the + HOW THE ROOM'S HEIGHT IS DECIDED. The room holds the tallest of + `text` and `samples` once wrapped, at the height matplotlib lays it + out in (`_caption_text_height_in`, measured in the caption's own font + at the figure's DPI) and never less than 1.2 times the font size per + line, so a caption of as many lines gets the same room whatever its + glyphs are. `text` is what the figure shows now: a fixed caption, a static figure's resolved one, or frame 0's. `samples` are a per-frame caption's texts on the frames `_caption_sample_frames` names (first, middle, last), so a caption @@ -4758,11 +4790,13 @@ def _add_caption(fig, text, font=None, family=None, samples=()): # excluded from the "lowest thing drawn" measurement artist.set_visible(False) wrapped = _wrap_caption(artist, text) - n_lines = max(candidate.count('\n') + 1 for candidate in - [wrapped] + [_wrap_caption(artist, str(sample)) - for sample in samples]) + candidates = [wrapped] + [_wrap_caption(artist, str(sample)) + for sample in samples] line_in = 1.2 * props.get_size_in_points() / 72.0 - strip_in = n_lines * line_in + 2 * _CAPTION_PAD_IN + text_in = max(max((candidate.count('\n') + 1) * line_in, + _caption_text_height_in(artist, candidate)) + for candidate in candidates) + strip_in = text_in + 2 * _CAPTION_PAD_IN blank_in = _blank_bottom_in(fig) if blank_in < strip_in: _grow_figure_downward(fig, strip_in - blank_in) @@ -5986,7 +6020,11 @@ def _apply_outer_labels(fig, panel_axes, nrows, ncols): so nothing downstream -- `tight_layout`, the 3-D cube fit (`_fit_panel_cubes`), a ``bbox_inches='tight'`` save -- reserves room for a label that is not drawn. Called once the panels are drawn and - BEFORE the grid is laid out. Tick labels are not touched.""" + BEFORE the grid is laid out. Tick labels are not touched. + + An emptied 3-D label is marked (``_hyp_emptied``) for + `_place_emptied_cube_labels`, which keeps it where matplotlib would + draw it once the grid is laid out.""" if not panel_axes: return cubes = hasattr(panel_axes[0], 'get_proj') @@ -6002,6 +6040,39 @@ def _apply_outer_labels(fig, panel_axes, nrows, ncols): for name, label in found.items(): if name not in keep and label.get_text(): label.set_text('') + label._hyp_emptied = cubes + + +def _place_emptied_cube_labels(fig, panel_axes): + """Put every 3-D axis label `_apply_outer_labels` emptied where + matplotlib would draw it in the grid's FINAL layout, so the + (zero-size) extent it reports is the place of the label the panel + shares, in every matplotlib version. + + A 3-D axis label is positioned by matplotlib during a draw. Through + matplotlib 3.10 that was done for every label; from 3.11 on a label + with no text (or a hidden one) is skipped + (``Axis3D._update_all_positions``), so a label emptied after a draw + kept that draw's position -- once the cubes were refitted and the + figure resized, a point outside its own panel, and a label out of + place for anything that asks where a panel's labels are. The emptied + labels are therefore given a stand-in text for ONE measurement draw of + the laid-out figure (`_measurement_renderer`: nothing is shown or + saved) and emptied again: matplotlib itself places them, and + ``ax.get_xlabel()`` stays ``''``.""" + emptied = [label for ax in panel_axes if hasattr(ax, 'get_proj') + for label in _axis_label_artists(ax).values() + if getattr(label, '_hyp_emptied', False) + and not label.get_text()] + if not emptied: + return + for label in emptied: + label.set_text('x') + try: + _measurement_renderer(fig) + finally: + for label in emptied: + label.set_text('') #: room (pixels) a plotly 3-D grid's left margin is given for the z titles @@ -7110,22 +7181,100 @@ def _has_axis_labels(axis): for axis3d in axis._axis_map.values()) -def _axis_labels_collide(fig, cells): - """Whether any 3-D panel in `cells` draws two of its own axis labels - over each other (their drawn boxes, less two pixels of antialiasing a - side, overlap) at its current view and zoom.""" +def _colliding_axis_labels(fig, cells): + """The 3-D axes' ``Axis`` objects (x, y or z) in `cells` whose label + is laid out over another label of the SAME panel at the panel's + current view and zoom: the boxes matplotlib lays the two labels out + in, on a real draw (`_measurement_renderer`), less two pixels of + antialiasing a side, overlap. Empty when no panel's labels collide. + + The boxes are matplotlib's own, so they are whatever the running + matplotlib makes them: through 3.10 a line of text is as tall as the + glyphs ``lp``, from 3.11 on as tall as the font's own ascent plus + descent (a third more in Noto Sans, hypertools' default face).""" renderer = _measurement_renderer(fig) + colliding = [] for cell in cells: - boxes = [axis3d.label.get_window_extent(renderer) + found = [(axis3d, axis3d.label.get_window_extent(renderer)) for axis3d in cell['axes']._axis_map.values() if axis3d.label.get_text() and axis3d.label.get_visible()] - for i, one in enumerate(boxes): - for other in boxes[i + 1:]: + for i, (one_axis, one) in enumerate(found): + for other_axis, other in found[i + 1:]: if (min(one.x1, other.x1) - max(one.x0, other.x0) > 4.0 and min(one.y1, other.y1) - max(one.y0, other.y0) > 4.0): - return True - return False + colliding.extend( + axis3d for axis3d in (one_axis, other_axis) + if axis3d not in colliding) + return colliding + + +def _axis_labels_collide(fig, cells): + """Whether any 3-D panel in `cells` draws two of its own axis labels + over each other (`_colliding_axis_labels`).""" + return bool(_colliding_axis_labels(fig, cells)) + + +#: blank room (pixels) kept between an axis label that reaches into the +#: gutter beside its panel and the middle of that gutter (the next panel's +#: labels may reach the middle from the other side) +_GUTTER_LABEL_PAD_PX = 2.0 + + +def _label_gutter_room(fig, cubes, limit): + """Per cell of `cubes`, ``{'left': reach, 'right': reach}``: how far + from the center of its square (0.5 is the square's edge) a 3-D + panel's axis labels may reach sideways when they are let into the + BLANK room beside the square -- up to the middle of the gutter + between it and the next panel's square, or up to anything else drawn + there (a colorbar, a legend) or the canvas' edge, less + `_OUTER_LABEL_PAD_IN`. Never less than `limit`, the reach allowed + inside the square itself, which is all a panel with a legend of its + own gets. Measured on a real draw (`_measurement_renderer`). Titles + sit above the squares and other rows below them, so there is no such + room up or down.""" + renderer = _measurement_renderer(fig) + canvas_width = float(fig.bbox.width) + pad = _OUTER_LABEL_PAD_IN * fig.dpi + squares = [cell['axes'].bbox for cell in cubes] + panels = {id(cell['axes']) for cell in cubes} + others = [] + for axis in fig.axes: + if axis.get_visible() and id(axis) not in panels: + others.append(axis.get_tightbbox(renderer)) + others.extend(legend.get_window_extent(renderer) + for legend in fig.legends) + rooms = [] + for cell, square in zip(cubes, squares): + if cell['axes'].get_legend() is not None or square.width <= 0: + rooms.append({'left': limit, 'right': limit}) + continue + center = 0.5 * (square.x0 + square.x1) + left, right = pad, canvas_width - pad + for other in squares: + if other is square or (other.y1 <= square.y0 + or other.y0 >= square.y1): + continue + if other.x0 >= square.x1: + right = min(right, 0.5 * (square.x1 + other.x0) + - _GUTTER_LABEL_PAD_PX) + elif other.x1 <= square.x0: + left = max(left, 0.5 * (square.x0 + other.x1) + + _GUTTER_LABEL_PAD_PX) + for other in others: + if other is None: + continue + if other.x0 >= center: + right = min(right, other.x0 - pad) + elif other.x1 <= center: + left = max(left, other.x1 + pad) + else: + # something drawn across the panel itself: no extra room + left, right = square.x0, square.x1 + rooms.append({ + 'left': max(limit, (center - left) / square.width), + 'right': max(limit, (right - center) / square.width)}) + return rooms def _fit_panel_cubes(fig, cells, resize=True, rotations=1, static=False, @@ -7176,7 +7325,9 @@ def _fit_panel_cubes(fig, cells, resize=True, rotations=1, static=False, never refused -- the call always drew, before the labels were fitted at all: where the size cannot hold the labeled grid legibly (a cube would fall under that share, or a panel's own labels would be drawn - over each other, `_axis_labels_collide`) the cubes are kept at that + over each other, `_axis_labels_collide`, even with the blank room + beside the panels' squares given to them, `_label_gutter_room`) the + cubes are kept at that share at least, the labels fall where they fall, and ONE `UserWarning` names a size that works (found the same way) and the alternative of dropping the labels. @@ -7198,12 +7349,15 @@ def _fit_cube(cell, target): break cell['stub'].zoom_scale[0] *= target / cell['reach'] - def _fit(least=0.0): + def _fit(least=0.0, gutters=False): """Fit every cube, then every labeled cube's labels, at the figure's current size; returns the smallest share of its unlabeled size a labeled cube is left with. No labeled cube is drawn smaller than the share `least` of its unlabeled size (its - labels then reach past the panel's box).""" + labels then reach past the panel's box). With `gutters` the + labels may reach sideways as far as each cell's ``'gutter'`` + says (`_label_gutter_room`) instead of staying inside the + panel's square.""" for cell in cubes: # every grid cube starts at the size a static panel's is drawn # at (matplotlib's default box zoom, times the animation's own @@ -7221,8 +7375,12 @@ def _fit(least=0.0): pending, _axis_label_reach(fig, pending, rotations)): # (an open side holds nothing the labels could run into: # `_open_label_sides`) + room = cell.get('gutter', {}) if gutters else {} + # (a reach into the gutter counts as the reach inside the + # square that uses the same share of the room there) label_reach = max([0.0] + [ - reach for side, reach in sides.items() + reach * limit / room[side] if side in room else reach + for side, reach in sides.items() if side not in cell.get('open', {})]) if label_reach - limit <= 0.004: continue @@ -7258,6 +7416,23 @@ def _illegible(): return (smallest < floor - (0.02 if size_checked else 0.004) or (explicit_static and _axis_labels_collide(fig, labeled))) + if (explicit_static and labeled and smallest >= floor - 0.02 + and _axis_labels_collide(fig, labeled)): + # the cubes are big enough at the caller's size, but a panel's own + # labels are laid out over each other. Labels fan out from their + # cube, so a slightly larger cube parts them -- and there is + # blank room for its labels beside every panel's square + # (`_label_gutter_room`). Fit the grid into that room before + # calling the size too small; where the labels still collide, the + # grid is put back as it was and the size is reported. + for cell, room in zip(labeled, _label_gutter_room( + fig, labeled, limit)): + cell['gutter'] = room + widened = _fit(gutters=True) + if _axis_labels_collide(fig, labeled): + smallest = _fit() + else: + smallest = widened size_checked = True if labeled and _illegible(): size_checked = False @@ -7407,6 +7582,7 @@ def _lay_out_panel_grid(fig, panel_axes, grid, strip, cells=None, # a still of the grid shows frame 0 (a 2-D panel was laid out # showing its tallest per-frame title; see `plot`) cell['stub'].draw(0) + _place_emptied_cube_labels(fig, panel_axes) caption_artist = None if caption is not None or dynamic_caption is not None: dynamic = dynamic_caption is not None diff --git a/notes/session_2026-11-22_feat295-animated-panels.md b/notes/session_2026-11-22_feat295-animated-panels.md index f3f44476b..f8249616f 100644 --- a/notes/session_2026-11-22_feat295-animated-panels.md +++ b/notes/session_2026-11-22_feat295-animated-panels.md @@ -332,3 +332,28 @@ How: - Item 1: `_plot_panels` owns one `matrix_cache` dict per grid call, passed in `_panel_shared['matrix_cache']` to every call made on the WHOLE matrix (shared probe, early and final resolution, and a reducer-list grid's probes and panel draws). `_matrix_hue_to_rgb_once` reduces on the first call and returns the stored RGB (matched by value) afterwards. Reducer-list grids went from 2 fits per panel to 1 per grid (noted in CHANGELOG, since 1.1.0 behavior changes there for a stochastic reducer). - Item 2: the resolution reports `hue_columns`; `_panel_apply_hue_scale` puts them in `shared['hue_columns']`, which `plot()` uses as `_hue_column_names` when the panel's hue is a bare array. - Item 3: the single-axes call REFUSES frames with differing column names (GH #132), so there is no single-axes legend to match for that exact data. Rule chosen: each series is called by its column name, which is what each dataset's own call and the single-axes call of same-named series read. The names are captured before the rows are stripped and handed to the resolution as `_panel_shared['series_columns']`, so legend labels, legend order and the bundle's `colors['labels']` all carry them. + +## matplotlib 3.11 text metrics (2026-11-22, branch fix/mpl311, after b81e1d2d) + +Hosted CI "test (ubuntu-latest, 3.13)" failed 9 tests on b81e1d2d with matplotlib 3.11.2; all passed locally on 3.10.8. Reproduced on macOS with a Python 3.13 venv pinned to matplotlib 3.11.2, numpy 2.5.5, pillow 13.0.0, fonttools 4.68.0 (no Docker needed: the default face is the bundled Noto Sans on every OS). + +Cause: two behavior changes in matplotlib 3.11, three places in hypertools that assumed the older behavior. + +- `Text._get_layout`: a line's height is now the font's own ascent + descent (+ line gap between lines), read from its `OS/2`/`hhea` tables. Through 3.10 it was the measured height of the glyphs `lp` (times 1.2 between lines). Noto Sans: 1.362 em per line, against about 1.0 em (1.2 em between lines) before. +- `Axis3D._update_all_positions`: a label with no text (or hidden) is no longer positioned on a draw. + +| What failed | Why | Fix (`hypertools/plot/plot.py`) | +|-|-|-| +| `caption=` ended below the canvas (7 tests) | `_add_caption` reserved `lines * 1.2 * font size` | `_caption_text_height_in` measures the wrapped text with the caption's own font at the figure's DPI; the room is the larger of that and the nominal line grid (so 3.10 output is unchanged) | +| `test_axis_labels_enlarge_the_figure_and_stay_inside_their_cells`, `(0, 0, '')` | a shared label emptied on an inner 3-D panel kept the position of the draw before the cube fit | `_place_emptied_cube_labels`: one measurement draw of the finished layout with a stand-in text in the emptied labels, then emptied again | +| `test_a_static_labeled_grid_that_fits_its_size_does_not_warn[long-1x4-8x3]` | the taller label boxes of the last panel's y and z labels overlap by more than the 4 px allowed, inside the panel's square, at any cube size | `_label_gutter_room`: when a static grid at an explicit `size=` has big enough cubes but colliding labels, it is fitted once more with the labels let into the blank room beside each square (half the gutter to the next panel, or up to the canvas edge / a legend / a colorbar less the label pad); kept only if the labels then clear, otherwise the grid is put back and the warning is raised as before | + +Tried and dropped: comparing the labels' painted pixels instead of their layout boxes (the tests' own overlap count uses layout boxes, so the library must too); pushing colliding labels out with `labelpad` (the fit shrinks the cube by exactly as much, the labels do not move). + +Not changed: `_axis_label_reach` still measures layout boxes, so labeled 3-D cubes are a few percent smaller under 3.11 than under 3.10 (taller boxes need more room). No CHANGELOG entry: all of this is 1.2.0 code that 1.1.0 does not have. + +Tests: `tests/test_text_room_measured.py` (caption room against the real renderer in four fonts; emptied labels against matplotlib's own placement; gutter room; the 1x4 grid at three sizes). + +Pixel check under matplotlib 3.10.8, before/after: `examples/animate_panels.py` (frames 0, 150, 299), `plot_datasaurus.py`, `plot_shapes_zoo.py`, `plot_impute.py`, `plot_autoencoders.py` are byte-identical (canvas RGBA buffers). + +Final checks after the last change (panel, caption, animation, plot-review, docstring and datatype-gate files plus the new one; `ruff check .` clean): matplotlib 3.11.2 / Python 3.13: 3053 passed, 0 failed; matplotlib 3.10.8 / Python 3.12: 3053 passed, 0 failed. diff --git a/tests/test_text_room_measured.py b/tests/test_text_room_measured.py new file mode 100644 index 000000000..46e83cd01 --- /dev/null +++ b/tests/test_text_room_measured.py @@ -0,0 +1,247 @@ +"""The room hypertools reserves for text is the room matplotlib draws it in. + +How tall a line of text is belongs to matplotlib and to the font: through +matplotlib 3.10 a line is as tall as the glyphs ``lp``, from 3.11 on as +tall as the font's own ascent plus descent (a third more in Noto Sans, +hypertools' default face), and 3.11 no longer places a 3-D axis label that +has no text. Three places assumed the older behavior (found on the +matplotlib 3.11.2 leg of CI, 2026-11-22): + +* a caption's room was ``lines * 1.2 * font size``, so a wrapped caption + ended below the canvas; +* a shared axis label emptied on an inner 3-D panel kept the position of + an earlier layout, outside its panel; +* a static labeled 3-D grid whose labels' taller boxes touched was reported + as too small for its ``size=``, with blank room left beside every panel. + +Every test here draws real figures headless and reads the extents off the +real renderer (nothing is mocked or patched), and asserts the invariant +itself rather than a number that holds under one matplotlib version. +""" +import itertools +import warnings + +import matplotlib +matplotlib.use('Agg') + +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +import pytest + +import hypertools as hyp +from hypertools.plot.plot import (CAPTION_GID, _CAPTION_PAD_IN, + _OUTER_LABEL_PAD_IN, _PANEL_CUBE_FILL, + _caption_text_height_in, + _label_gutter_room) + + +def _walk(seed, rows=30, cols=3): + rng = np.random.default_rng(seed) + return np.cumsum(rng.normal(size=(rows, cols)), axis=0) + + +X = _walk(0) +DATA = [_walk(seed) for seed in range(4)] +LONG = [pd.DataFrame(d, columns=['first axis', 'second axis', + 'third axis']) for d in DATA] +SENTENCE = ('A caption sentence that is far too long for one line of a ' + 'small figure, so that it has to be wrapped to the width of ' + 'the figure it is drawn under, and stay there. ') + + +@pytest.fixture(autouse=True) +def _close_figures(): + yield + plt.close('all') + + +def _caption(fig): + found = fig.findobj(lambda a: a.get_gid() == CAPTION_GID) + assert len(found) == 1 + return found[0] + + +def _drawn_box(fig, artist): + """`artist`'s box (pixels) on a real draw of `fig`.""" + fig.canvas.draw() + return artist.get_window_extent(fig.canvas.get_renderer()) + + +# -------------------------------------------------------------------------- +# a caption's room is the height its text is drawn at +# -------------------------------------------------------------------------- + +@pytest.mark.parametrize('font', [None, 'DejaVu Sans', 'DejaVu Serif', + 'DejaVu Sans Mono']) +@pytest.mark.parametrize('text', ['short', SENTENCE * 2, SENTENCE * 5, + 'W' * 400], + ids=['1-line', 'wrapped', 'long', 'one-word']) +@pytest.mark.parametrize('call', [ + dict(x=X), dict(x=X, ndims=2), dict(x=DATA, panels=(2, 2)), + dict(x=X, animate=True, duration=1, frame_rate=4), +], ids=['3d', '2d', 'grid', 'animated']) +def test_caption_room_holds_the_drawn_text_with_its_pad(call, text, font): + """Under the caption's last line there is the caption's own pad, in + every font: the room is sized from the drawn text's height.""" + call = dict(call, show=False) + if font is not None: + call['font'] = font + result = hyp.plot(call.pop('x'), caption=text, **call) + fig = getattr(result, 'figure', result) + box = _drawn_box(fig, _caption(fig)) + pad_px = _CAPTION_PAD_IN * fig.dpi + # (one pixel for the renderer's rounding of the canvas height) + assert box.y0 >= pad_px - 1.0, (box.y0, pad_px) + assert box.y1 <= fig.canvas.get_width_height()[1] + + +@pytest.mark.parametrize('text', ['one line', 'two\nlines', SENTENCE * 3]) +def test_caption_height_is_measured_as_it_is_drawn(text): + """`_caption_text_height_in` (which draws nothing) reports the height + the figure's real renderer then draws the same text at.""" + fig = hyp.plot(X, caption=text, show=False) + artist = _caption(fig) + shown = artist.get_text() + measured = _caption_text_height_in(artist, shown) + assert artist.get_text() == shown and artist.get_visible() + drawn = _drawn_box(fig, artist).height / fig.dpi + assert measured == pytest.approx(drawn, abs=0.5 / fig.dpi) + + +def test_caption_that_grows_over_the_frames_keeps_its_pad(): + """The sampled frames (first, middle, last) of a per-frame caption fit + the room with the pad under them.""" + anim = hyp.plot(X, caption=lambda ctx: SENTENCE * (1 + ctx.frame), + animate=True, duration=1, frame_rate=5, show=False) + fig = anim.figure + pad_px = _CAPTION_PAD_IN * fig.dpi + for frame in sorted({0, anim.n_frames // 2, anim.n_frames - 1}): + anim.draw_frame(frame) + assert _drawn_box(fig, _caption(fig)).y0 >= pad_px - 1.0, frame + + +# -------------------------------------------------------------------------- +# an emptied shared label is where matplotlib would draw it +# -------------------------------------------------------------------------- + +def _emptied_labels(fig, n): + return [(ax, axis.label) for ax in fig.axes[:n] + for axis in (ax.xaxis, ax.yaxis, ax.zaxis) + if not axis.label.get_text()] + + +@pytest.mark.parametrize('call', [ + dict(panels=(2, 2)), dict(panels=(1, 4)), dict(panels=(2, 2), size=(9, 8)), + dict(panels=(2, 2), caption='a caption'), + dict(panels=(1, 4), animate=True, duration=1, frame_rate=4), +], ids=['2x2', '1x4', '2x2-sized', '2x2-caption', 'animated']) +def test_emptied_shared_3d_labels_sit_where_they_would_be_drawn(call): + """Shared axis labels are drawn on the outer panels only. The labels + emptied on the other panels report the place matplotlib draws that + panel's label at in the finished layout, at their own panel.""" + result = hyp.plot(LONG, show=False, **call) + fig = getattr(result, 'figure', result) + found = _emptied_labels(fig, 4) + assert found + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + reported = [label.get_window_extent(renderer).get_points()[0] + for _, label in found] + for (ax, label), where in zip(found, reported): + box = ax.get_window_extent() + # (a drawn label may hang a little past its panel's square where + # nothing else is drawn; so may the place of an emptied one) + slack = 0.06 * box.width + assert box.x0 - slack <= where[0] <= box.x1 + slack + assert box.y0 - slack <= where[1] <= box.y1 + slack + # matplotlib's own placement, read off a draw with a text in each + for _, label in found: + label.set_text('x') + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + for (_, label), where in zip(found, reported): + placed = label.get_transform().transform(label.get_position()) + assert np.allclose(placed, where, atol=0.5), (placed, where) + + +# -------------------------------------------------------------------------- +# labels are given the blank room beside their panel before a size= is +# reported as too small +# -------------------------------------------------------------------------- + +def _label_boxes(fig, n): + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + return [[axis.label.get_window_extent(renderer) + for axis in (ax.xaxis, ax.yaxis, ax.zaxis) + if axis.label.get_text()] for ax in fig.axes[:n]] + + +def test_gutter_room_is_the_blank_room_beside_each_square(): + fig = hyp.plot(LONG, '-', panels=(1, 4), size=(8, 3), show=False) + fig.canvas.draw() + axes = fig.axes[:4] + limit = 0.5 * _PANEL_CUBE_FILL + rooms = _label_gutter_room( + fig, [{'axes': ax} for ax in axes], limit) + squares = [ax.bbox for ax in axes] + width = fig.canvas.get_width_height()[0] + pad_px = _OUTER_LABEL_PAD_IN * fig.dpi + for i, (room, square) in enumerate(zip(rooms, squares)): + center = 0.5 * (square.x0 + square.x1) + for side in ('left', 'right'): + assert room[side] >= limit + # never past the middle of the gutter to the next square, nor + # nearer the canvas' edge than the labels' pad + if i + 1 < len(squares): + middle = 0.5 * (square.x1 + squares[i + 1].x0) + assert center + room['right'] * square.width <= middle + assert room['right'] > 0.5 + else: + assert (center + room['right'] * square.width + == pytest.approx(width - pad_px)) + if i: + middle = 0.5 * (squares[i - 1].x1 + square.x0) + assert center - room['left'] * square.width >= middle + else: + assert (center - room['left'] * square.width + == pytest.approx(pad_px)) + + +def test_gutter_room_stops_at_a_shared_legend(): + fig = hyp.plot(LONG, '-', panels=(1, 4), size=(10, 3), legend=True, + show=False) + fig.canvas.draw() + axes = fig.axes[:4] + legend = fig.legends[0].get_window_extent(fig.canvas.get_renderer()) + square = axes[-1].bbox + room = _label_gutter_room( + fig, [{'axes': ax} for ax in axes], 0.5 * _PANEL_CUBE_FILL)[-1] + reach_px = 0.5 * (square.x0 + square.x1) + room['right'] * square.width + assert reach_px <= max(legend.x0, square.x1) + + +@pytest.mark.parametrize('size', [(8, 3), (8.4, 3), (9, 3.2)]) +def test_a_static_grid_with_room_beside_its_panels_fits_its_size(size): + """Four labeled cubes side by side, with blank room between and + beside their squares: no warning, no label laid out over another of + its own panel, every label on the canvas and clear of the other + panels' labels.""" + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + fig = hyp.plot(LONG, '-', panels=(1, 4), size=size, show=False) + assert not [str(w.message) for w in caught] + assert tuple(fig.get_size_inches()) == tuple(float(v) for v in size) + boxes = _label_boxes(fig, 4) + width, height = fig.canvas.get_width_height() + for own in boxes: + for box in own: + assert box.x0 >= 0 and box.x1 <= width + assert box.y0 >= 0 and box.y1 <= height + for a, b in itertools.combinations(own, 2): + assert not (min(a.x1, b.x1) - max(a.x0, b.x0) > 4.0 + and min(a.y1, b.y1) - max(a.y0, b.y0) > 4.0) + for own, theirs in itertools.combinations(boxes, 2): + for a, b in itertools.product(own, theirs): + assert not a.overlaps(b) From 9e6ababc5c70763a37c0a45290b668b0a4e554df Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 14:04:42 -0500 Subject: [PATCH 57/58] fix: the process-tree cleanup never follows a stale parent link On Windows a process keeps its parent's id after the parent exits, and ids are reused, so the descendants of a render worker could include unrelated older processes -- the calling process among them. A hosted Windows job died with no pytest summary in the first test that kills a render worker. A parent link is now followed only when the child is not older than the parent, and the calling process and its ancestors are never returned. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- hypertools/plot/plotly_backend.py | 86 +++++++++++++++---- ...sion_2026-11-22_feat295-animated-panels.md | 7 ++ tests/test_animation_export.py | 49 +++++++++++ 3 files changed, 127 insertions(+), 15 deletions(-) diff --git a/hypertools/plot/plotly_backend.py b/hypertools/plot/plotly_backend.py index b7d3275cd..6dfa799a7 100644 --- a/hypertools/plot/plotly_backend.py +++ b/hypertools/plot/plotly_backend.py @@ -4143,20 +4143,76 @@ def _export_ceiling(n_frames): return max(_KALEIDO_MIN_CEILING, n_frames * _KALEIDO_CEILING_PER_FRAME) +def _descendants_in_table(rows, pid, exclude=()): + """The descendants of `pid` in one process-table snapshot, parents before + children. `rows` are ``(pid, parent pid, creation time or None)``. + + A parent link is only trusted when it cannot be stale. Windows never + clears a process's recorded parent id when the parent exits, and reuses + process ids freely, so a long-running process can name as its "parent" + an id that now belongs to a much younger, unrelated process (hosted + Windows CI, 2026-11-22: the test runner itself was killed as a + "descendant" of a render worker that had been handed the id of the + runner's dead launcher). When creation times are known, a child must + therefore not be older than its parent; a row without a creation time is + then never taken for a child. Tables without creation times (POSIX + ``ps``, where an orphan is re-parented at once and the link is always + current) are walked as they are. + + `exclude` (this process, its ancestors, the lister) is never returned + and never walked through, whatever the table says.""" + created = {row[0]: row[2] for row in rows} + timed = any(value is not None for value in created.values()) + children = {} + for child, parent, _ in rows: + children.setdefault(parent, []).append(child) + barred = set(exclude) + found, queue = [], [pid] + while queue: + parent = queue.pop(0) + for child in children.get(parent, []): + if child in barred or child in found or child == pid: + continue + if timed: + born, parent_born = created.get(child), created.get(parent) + if born is None or parent_born is None or born < parent_born: + continue + found.append(child) + queue.append(child) + return found + + +def _ancestors_in_table(rows, pid): + """`pid` and every ancestor the snapshot `rows` records for it (see + `_descendants_in_table`), nearest first. Bounded by the table size.""" + parent_of = {row[0]: row[1] for row in rows} + chain = [pid] + while parent_of.get(chain[-1]) not in (None, 0) and len(chain) <= len(rows): + nxt = parent_of[chain[-1]] + if nxt in chain: + break + chain.append(nxt) + return chain + + def _descendant_pids(pid=None): """Every live descendant of process `pid` (this process when None), as process ids, parents before children. Read from ONE snapshot of the process table (``ps`` on POSIX, PowerShell's ``Win32_Process`` on Windows), so it also finds descendants that left the process group: choreographer starts its browser wrapper in a session of its own, - which a ``killpg`` never reaches. Bounded, and an empty list when the - table cannot be read.""" + which a ``killpg`` never reaches. Stale parent links are not followed, + and this process and its ancestors are never returned unless they are + what was asked about (see `_descendants_in_table`). Bounded, and an + empty list when the table cannot be read.""" import subprocess - pid = os.getpid() if pid is None else int(pid) + own = os.getpid() + pid = own if pid is None else int(pid) if os.name == 'nt': command = ['powershell', '-NoProfile', '-Command', 'Get-CimInstance Win32_Process | ForEach-Object ' - '{ "$($_.ProcessId) $($_.ParentProcessId)" }'] + '{ "$($_.ProcessId) $($_.ParentProcessId) ' + '$($_.CreationDate.Ticks)" }'] else: command = ['ps', '-A', '-o', 'pid=,ppid='] try: @@ -4170,19 +4226,19 @@ def _descendant_pids(pid=None): lister.kill() lister.communicate() return [] - children = {} + rows = [] for line in listing.splitlines(): fields = line.split() - if len(fields) == 2 and fields[0].isdigit() and fields[1].isdigit(): - children.setdefault(int(fields[1]), []).append(int(fields[0])) - found, queue = [], [pid] - while queue: - for child in children.get(queue.pop(0), []): - # (the lister itself is a child of this process) - if child != lister.pid and child not in found: - found.append(child) - queue.append(child) - return found + if (len(fields) in (2, 3) and fields[0].isdigit() + and fields[1].isdigit()): + born = (int(fields[2]) if len(fields) == 3 + and fields[2].isdigit() else None) + rows.append((int(fields[0]), int(fields[1]), born)) + # (the lister itself is a child of this process) + exclude = {lister.pid} + if pid != own: + exclude.update(_ancestors_in_table(rows, own)) + return _descendants_in_table(rows, pid, exclude) def _kill_pids(pids): diff --git a/notes/session_2026-11-22_feat295-animated-panels.md b/notes/session_2026-11-22_feat295-animated-panels.md index f8249616f..329d26231 100644 --- a/notes/session_2026-11-22_feat295-animated-panels.md +++ b/notes/session_2026-11-22_feat295-animated-panels.md @@ -357,3 +357,10 @@ Tests: `tests/test_text_room_measured.py` (caption room against the real rendere Pixel check under matplotlib 3.10.8, before/after: `examples/animate_panels.py` (frames 0, 150, 299), `plot_datasaurus.py`, `plot_shapes_zoo.py`, `plot_impute.py`, `plot_autoencoders.py` are byte-identical (canvas RGBA buffers). Final checks after the last change (panel, caption, animation, plot-review, docstring and datatype-gate files plus the new one; `ruff check .` clean): matplotlib 3.11.2 / Python 3.13: 3053 passed, 0 failed; matplotlib 3.10.8 / Python 3.12: 3053 passed, 0 failed. + +## Windows CI: the suite died in the first test that kills a render worker (after 5f104d0a) + +- CI on 5f104d0a: 12 jobs green (all ubuntu, windows 3.10/3.12/3.13, the gates, docs-clean); the four macOS jobs were still queued at the waiter's deadline; `test (windows-latest, 3.11)` ended with exit code 1 and NO pytest summary, its last line `tests/test_animation_export.py::test_real_export_succeeds_after_a_killed_export` (job 137294099026). +- Reading (not reproduced: no Windows machine here): `_kill_process_tree` now also kills `_descendant_pids(proc.pid)` (round 3, Q6). On Windows that list came from `Win32_Process` parent ids, which are never cleared when a parent exits, while process ids are reused. A render worker handed the id of a dead ancestor of the test runner makes the runner its "descendant", and `taskkill /F` ends it (exit code 1, no summary). Intermittent by nature, which fits three green Windows jobs beside one dead one. +- Fix: `_descendants_in_table` follows a parent link only when the child is not older than the parent (Windows creation ticks; a row without a creation time is never taken for a child), and `_descendant_pids` never returns the calling process or its ancestors. POSIX tables carry no creation times and are walked as before. Tests: `test_a_stale_parent_link_is_not_followed`, `test_this_process_and_its_ancestors_are_never_descendants`, `test_descendant_pids_finds_a_real_child_and_never_this_process` (real process table). +- Also in this stretch: the gallery's own videos are remuxed fast start by the scraper (fa4e765b), two example comments corrected (b81e1d2d), matplotlib 3.11 text metrics (5f104d0a). The user confirmed on 2026-11-22 that the 1.2.0 gallery figures are correct ("Current versions are correct for all figures"). diff --git a/tests/test_animation_export.py b/tests/test_animation_export.py index 9bd3aa3ff..62dbc7e78 100644 --- a/tests/test_animation_export.py +++ b/tests/test_animation_export.py @@ -720,3 +720,52 @@ def test_plotly_animation_export_honours_set_autoinstall_on_over_the_environment [str(py), '-c', "import importlib.util; print(importlib.util.find_spec('kaleido') is None)"], capture_output=True, text=True, check=True, timeout=120) assert still.stdout.strip() == 'True' + + +# --- stale parent links (hosted Windows CI, 2026-11-22) ---------------------- + +def test_a_stale_parent_link_is_not_followed(): + """Windows keeps a dead parent's id in its children and reuses ids: here + the test runner (pid 500, started at t=10) still names pid 900 as its + parent, and pid 900 now belongs to a render worker started at t=50. The + runner is NOT the worker's descendant -- on 2026-11-22 a hosted Windows + job died mid-suite, with no pytest summary, in the first test that kills + a render worker. The worker's real child (pid 901, t=60) and grandchild + are still found, parents first.""" + from hypertools.plot.plotly_backend import _descendants_in_table + rows = [(4, 0, 1), (500, 900, 10), (501, 500, 20), + (900, 500, 50), (901, 900, 60), (902, 901, 61), + (903, 900, None)] # no creation time: never trusted + assert _descendants_in_table(rows, 900) == [901, 902] + + +def test_this_process_and_its_ancestors_are_never_descendants(): + """Whatever the table claims (equal creation ticks, a link cycle), the + asking process and its ancestors are excluded and not walked through.""" + from hypertools.plot.plotly_backend import (_ancestors_in_table, + _descendants_in_table) + rows = [(100, 300, 5), (200, 100, 5), (300, 200, 5), (301, 300, 6)] + assert _ancestors_in_table(rows, 200) == [200, 100, 300] + exclude = _ancestors_in_table(rows, 200) + assert _descendants_in_table(rows, 300, exclude) == [301] + # a POSIX table has no creation times and is walked as it is + posix = [(10, 1, None), (11, 10, None), (12, 11, None), (13, 1, None)] + assert _descendants_in_table(posix, 10) == [11, 12] + + +def test_descendant_pids_finds_a_real_child_and_never_this_process(): + """Against the real process table: a child this process started is found + as its descendant; asking about that child returns neither this process + nor any of its ancestors.""" + import subprocess + import sys + from hypertools.plot.plotly_backend import _descendant_pids + child = subprocess.Popen([sys.executable, '-c', + 'import time; time.sleep(60)']) + try: + assert child.pid in _descendant_pids() + below = _descendant_pids(child.pid) + assert os.getpid() not in below and os.getppid() not in below + finally: + child.kill() + child.wait() From 8086b5b8101c82d56f861b118fe3dda3d55facc7 Mon Sep 17 00:00:00 2001 From: Jeremy Manning Date: Sun, 22 Nov 2026 14:41:25 -0500 Subject: [PATCH 58/58] docs: record the pre-built 1.2.0 gallery docs-gallery-v1.2.0 = afb1e0d9, built from 9e6ababc. Read the Docs reuses it instead of executing every example inside its build time limit. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DcKtysUSGLqA8RApYP9xYG --- docs/prebuilt_gallery.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/prebuilt_gallery.json b/docs/prebuilt_gallery.json index ac65d5ae4..41dcc14ef 100644 --- a/docs/prebuilt_gallery.json +++ b/docs/prebuilt_gallery.json @@ -1,5 +1,5 @@ { - "commit": "598c4d87cd56c0e02d45b7282716381458673ab9", - "source_commit": "12e98347ace2fedd241a1d1623799eeee03ae648", - "version": "1.1.1" + "commit": "afb1e0d907b65adac1d63bf7357f3a73d8653008", + "source_commit": "9e6ababc5c70763a37c0a45290b668b0a4e554df", + "version": "1.2.0" }