Skip to content

Refactor Plotting functions - #1631

Merged
janfb merged 23 commits into
sbi-dev:mainfrom
abelaba:pairplot-refactoring
Oct 8, 2025
Merged

janfb merged 23 commits into
sbi-dev:mainfrom
abelaba:pairplot-refactoring

Conversation

@abelaba

@abelaba abelaba commented Aug 7, 2025 •

Copy link
Copy Markdown
Collaborator

This PR refactors the plotting functions by improving code modularity for the pairplot and marginal_pairplot functions and provides typed configuration using dataclasses. The changes include:

  • Adds new dataclasses KdeDiagOptions, HistDiagOptions, ScatterDiagOptions passed to pairplot and marginal_pairplot functions, for customizing the diagonal plotting regions which are passed to the diag_kwargs argument.
  • Adds new dataclasses KdeOffDiagOptions, HistOffDiagOptions, ScatterOffDiagOptions, ContourOffDiagOptions, PlotOffDiagKwargs passed to the pairplot function, for customizing the upper and lower plotting regions, which are passed to the upper_kwargs and lower_kwargs arguments.
  • Adds a new dataclass FigOptions passed to pairplot and marginal_pairplot functions, for customizing the figure which is passed to the fig_kwargs argument.
  • Moves helper functions to a separate file sbi/utils/plotting_helpers.py
  • Modularizes repeated logic in pairplot and marginal_pairplot functions.
  • Maintains backward compatibility with the previous dictionary-based configuration.
  • Update the plotting tutorial to use the newly added dataclasses, docs/advanced_tutorials/17_plotting_functionality.ipynb.

This pull request builds upon the idea by @danielmk in PR #1529.

@codecov

codecov Bot commented Aug 7, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.02899% with 22 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (main@ebb8c6f). Learn more about missing BASE report.
⚠️ Report is 25 commits behind head on main.

Files with missing lines Patch % Lines
sbi/analysis/plot.py 85.54% 12 Missing ⚠️
sbi/utils/plotting_helpers.py 90.16% 6 Missing ⚠️
sbi/analysis/plotting_classes.py 96.94% 4 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main    #1631   +/-   ##
=======================================
  Coverage        ?   84.42%           
=======================================
  Files           ?      136           
  Lines           ?    11254           
  Branches        ?        0           
=======================================
  Hits            ?     9501           
  Misses          ?     1753           
  Partials        ?        0           
Flag Coverage Δ
unittests 84.42% <92.02%> (?)

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

Files with missing lines Coverage Δ
sbi/analysis/__init__.py 100.00% <100.00%> (ø)
sbi/analysis/plotting_classes.py 96.94% <96.94%> (ø)
sbi/utils/plotting_helpers.py 90.16% <90.16%> (ø)
sbi/analysis/plot.py 75.56% <85.54%> (ø)

Comment thread sbi/analysis/plot.py Resolved
Comment thread sbi/analysis/plot.py Resolved
Comment thread sbi/analysis/plot.py Resolved
Comment thread sbi/analysis/plotting_classes.py Resolved
Comment thread sbi/analysis/plotting_classes.py Resolved
@abelaba abelaba changed the title Pairplot refactoring Refactor Plotting functions Sep 1, 2025
@danielmk danielmk mentioned this pull request Sep 8, 2025

@janfb janfb left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a great improvement for the plotting functions in terms of typing, thanks @abelaba !

It would be great if you could test the following things, either by dedicated tests (e.g., for the warning / error raising), or by just testing it once in your local setup:

  • Dataclasses and defaults
    • Ensure asdict conversion + deep merge via update() works for nested mpl_kwargs and np_hist_kwargs.
    • Confirm HistDiagOptions merges density=False, histtype='step' when users pass partial overrides.
  • Runtime validation
    • FigOptions.legend=True with insufficient samples_labels raises ValueError.
    • to_list_kwargs accepts a dataclass, dict, list of both, and None; raises TypeError on invalid inputs.
    • offdiag deprecation triggers warning and yields equivalent result to upper.
  • Plotting behavior
    • ContourOffDiagOptions color forwarding: assert line colors are applied by checking Matplotlib line artists when using contour.
    • Square subplot aspect respected when fig_kwargs.square_subplots.
  • Backcompat smoke tests
    • Old-style dict kwargs still accepted.
    • Legacy offdiag works.

Comment thread sbi/analysis/plotting_classes.py Resolved
Comment thread sbi/analysis/plotting_classes.py Resolved
Comment thread sbi/analysis/plot.py Resolved
Comment thread sbi/analysis/plot.py Resolved
Comment thread sbi/analysis/plot.py Resolved
Comment thread sbi/analysis/plot.py Resolved

@janfb janfb left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All good now, great work @abelaba ! I also went over the tutorial notebook and saw that you updated it with the dataclass options accordingly, that's great!

@janfb
janfb merged commit 68fb53b into sbi-dev:main Oct 8, 2025
dgedon added a commit that referenced this pull request Nov 23, 2026
…l under the legend (#2160)

* fix(plot): warn visibly before the old pairplot path is removed in v0.29

Passing old-style keyword arguments to `pairplot` or `marginal_plot` sends
the call to the pre-v0.23 implementation. Since #1631 the
DeprecationWarning pointed into sbi, so Python's default filters hid it. It
named no removal version, and the old implementation silently dropped the
newer arguments passed with it.

Raise a FutureWarning at the caller's line instead. It names the keys,
v0.29.0 and where the keys go, and lists the newer arguments that the call
ignores. `pairplot_dep`, `marginal_plot_dep` and `PlotOffDiagOptions` warn
too. The old implementation itself is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs: pass tutorial 19's pairplot options in fig_kwargs

Cells 16, 19, 26 and 28 of advanced tutorial 19 passed `legend`,
`samples_labels`, `points_labels`, `points_colors` and `points_offdiag`
directly to `pairplot`. That sent them to the old implementation, which
ignored their `diag_kwargs` and `upper_kwargs`. Pass these options in
`fig_kwargs` instead, so that the requested contour levels and KDE bins
are drawn.

Also drop the deprecated `PlotOffDiagOptions` from tutorial 17's list of
option classes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs: rerun tutorial 19

Rerun advanced tutorial 19 so that its stored figures show what the cells
ask for: the 95 % contour and 100 KDE bins in the MAP figure, and the
99 % contours in the i.i.d. and guidance figures. Outputs are stored as
in the other docs notebooks: plots and printed output only, with
consecutive prints merged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(plot): don't draw the legend cell's x-label in pairplot

With `fig_kwargs=dict(legend=True)` and an empty lower triangle, pairplot
puts the legend into the bottom-left cell. That cell got its x-label (e.g.
"dim 1") before it was turned off, and `_place_legend_in_empty_cell` (#1830)
turned it back on, hiding only its ticks and spines. Clear the labels too.

Only figures with a legend in the bottom-left cell change. The old
implementation never labels that cell, so it draws the same as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs: rerun tutorials 17 and 19 with the legend fix

Their legend figures no longer show the stray x-label under the legend.
Outputs are stored as in the other docs notebooks: plots and printed
output only, consecutive prints merged, and no execution timestamps. This
also drops the timestamps that the previous rerun of tutorial 19 stored.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(plot): name a diag style that the old pairplot path doesn't draw

The old implementation draws only "hist" and "kde" on the diagonal, and
"scatter" only when the upper triangle is scatter too. With an old-style
keyword argument, `pairplot(s, legend=True, diag="bar")` and
`marginal_plot(s, legend=True, diag="scatter")` drew an empty diagonal,
and the warning did not say so. Name `diag` as ignored in these cases.

`_warn_deprecated_kwargs` now also checks the `LabeledSamples` names
itself, so `pairplot` and `marginal_plot` no longer repeat that check.

The removal of the old path in v0.29 is tracked in #2218.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(plot): warn about offdiag at the caller and name v0.29

`pairplot`'s `offdiag` argument has warned since v0.23.0 with a
`UserWarning` that points into `sbi/analysis/plot.py` and names no
removal version. Raise a `FutureWarning` at the caller's line instead,
like the other deprecated `pairplot` arguments, and say that it will be
removed in v0.29.0. It maps only to `upper`, so the message no longer
suggests `lower`.

The removal is tracked in #2218.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(plot): name diag as ignored exactly when the old diagonal doesn't draw it

Per sample, the old diagonal draws "hist" or "kde" if asked, and
otherwise draws scatter lines if that sample's upper style is "scatter",
and nothing if not. The warning approximated this. It named `diag` for
`diag=["scatter", "hist"], upper=["scatter", "hist"]`, which the old
path draws, and stayed silent for `diag=None, upper="scatter"`, where the
old path draws scatter lines nobody asked for. Pair each sample's `diag`
with its `upper` and apply the old rule.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(plot): compare only one diag and upper style per sample set

The old implementation uses one style per sample set and ignores extra
list entries. The warning compared all entries, so for one sample set,
`pairplot(s, legend=True, diag="scatter", upper=["scatter", "hist"])`
named `diag` although the old diagonal draws the scatter lines. Count
the sample sets as the old implementation does and compare only that
many pairs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants