diff --git a/src/maxplotlib/backends/matplotlib/import_state.py b/src/maxplotlib/backends/matplotlib/import_state.py index fb864a8..20c7d86 100644 --- a/src/maxplotlib/backends/matplotlib/import_state.py +++ b/src/maxplotlib/backends/matplotlib/import_state.py @@ -6,7 +6,10 @@ reparented, and repeated renders do not share mutable Matplotlib state. """ +import ast import copy +import copyreg +import itertools from dataclasses import asdict, dataclass, field from matplotlib.artist import Artist @@ -20,6 +23,21 @@ from matplotlib.transforms import Bbox, BboxTransformTo +def _reduce_count(counter): + """Rebuild an ``itertools.count`` from its repr, ``count(start)`` or ``count(start, step)``.""" + args = ast.literal_eval(repr(counter)[len("count") :]) + return itertools.count, args if isinstance(args, tuple) else (args,) + + +# Python 3.14 no longer copies or pickles itertools objects, and Matplotlib's categorical units +# (matplotlib.category.UnitData, also held by the category locator and formatter) keep a count: +# without this, copying the state of a categorical axis fails. +try: + copy.deepcopy(itertools.count()) +except TypeError: + copyreg.pickle(itertools.count, _reduce_count) + + @dataclass class ImportDiagnostic: artist_id: int @@ -136,6 +154,14 @@ def __init__(self, payload, ax=None, fig=None): if callbacks is not None: memo[id(callbacks)] = CallbackRegistry() self.payload = copy.deepcopy(payload, memo) + # Python 3.14 returns functions and builtin methods as they are before it reads the memo, + # so the copies would still hold the source's removal and stale callbacks (and through + # them its axes and figure): drop them, as the memo does on older versions. + for artist in artists: + copied = memo.get(id(artist)) + for name in ("_remove_method", "stale_callback"): + if getattr(copied, name, None) is not None: + setattr(copied, name, None) def clone(self, ax=None, fig=None): fig = fig if fig is not None else ax.figure diff --git a/src/maxplotlib/canvas/canvas.py b/src/maxplotlib/canvas/canvas.py index 2afde69..ebd676f 100644 --- a/src/maxplotlib/canvas/canvas.py +++ b/src/maxplotlib/canvas/canvas.py @@ -322,7 +322,9 @@ def __init__( nrows (int): Number of subplot rows. Default is 1. ncols (int): Number of subplot columns. Default is 1. figsize (tuple): Figure size. - caption (str): Caption for the figure. + caption (str): Caption for the figure: the Matplotlib figure carries it as + ``fig.caption``, the Plotly figure as ``layout.meta["caption"]``, and a + web figure as its title (the caption the docs page shows). description (str): Description for the figure. label (str): Label for the figure. fontsize (int): Font size. Default is 10. @@ -2637,7 +2639,9 @@ def _plot_matplotlib( if verbose: print("Set suptitle.") - # Set caption, labels, etc., if needed + if self._caption: + # read by the docs and gallery tools that write the figure on a page + fig.caption = self._caption self._plotted = True self._matplotlib_fig = fig self._matplotlib_axes = axes @@ -3233,6 +3237,9 @@ def plot_plotly( fig.update_layout(legend=legend_layout) if self._suptitle: fig.update_layout(title=dict(text=self._suptitle, x=0.5)) + if self._caption: + meta = fig.layout.meta if isinstance(fig.layout.meta, dict) else {} + fig.update_layout(meta={**meta, "caption": self._caption}) if savefig: try: @@ -3263,7 +3270,8 @@ def to_json( Parameters: layers (list, optional): The layers to draw. - title (str, optional): The title and default caption. Default: the canvas title. + title (str, optional): The title and default caption. Default: the canvas caption, + else the canvas title. alt (str, optional): A text alternative for the figure. white_plot (bool, optional): Keep a white plot area in dark mode. """ diff --git a/src/maxplotlib/tests/test_web.py b/src/maxplotlib/tests/test_web.py index e642eb9..ba38fd8 100644 --- a/src/maxplotlib/tests/test_web.py +++ b/src/maxplotlib/tests/test_web.py @@ -186,3 +186,24 @@ def test_write_posters(tmp_path, monkeypatch): assert dark.data[0].line.color == "#f0b030" # and in the dark one assert dark.data[1].line.color == "#eeeadd" # black as the text colour assert list(dark.layout.colorway)[0] == "#4fa8e0" + + +def test_a_canvas_caption_goes_with_its_figures(): + canvas = Canvas(caption="A rising line.") + canvas.plot(np.arange(3), np.arange(3)) + figure, _ = canvas.plot_matplotlib() + assert figure.caption == "A rising line." + plotly_figure = canvas.plot_plotly(show=False) + assert plotly_figure.layout.meta["caption"] == "A rising line." + web = json.loads(canvas.to_json()) + assert web["layout"]["meta"]["web"]["title"] == "A rising line." + # an explicit title wins over the caption + web = json.loads(canvas.to_json(title="Line")) + assert web["layout"]["meta"]["web"]["title"] == "Line" + + +def test_a_figure_without_caption_has_none(): + canvas = Canvas() + canvas.plot(np.arange(3), np.arange(3)) + figure, _ = canvas.plot_matplotlib() + assert getattr(figure, "caption", None) is None diff --git a/src/maxplotlib/web.py b/src/maxplotlib/web.py index 9aecb2b..53f3f54 100644 --- a/src/maxplotlib/web.py +++ b/src/maxplotlib/web.py @@ -19,7 +19,8 @@ ``version`` The format version, :data:`FORMAT_VERSION`. ``title`` - The figure's title, also the default caption. + The figure's caption (``layout.meta["caption"]``, as a Canvas with a caption sets it), else + its title. ``alt`` A text alternative for readers who cannot see the figure. ``aspect`` @@ -193,7 +194,8 @@ def web_figure( figure : plotly.graph_objects.Figure or dict The figure, or its JSON as a dict (e.g. read from a file). title : str, optional - The title and default caption. Default: the figure's own title. + The title and default caption. Default: the figure's caption + (``layout.meta["caption"]``), else its own title. alt : str, optional A text alternative for the figure. Default: none. aspect : float, optional @@ -227,7 +229,8 @@ def web_figure( aspect = float(width) / float(height) if white_plot is None: white_plot = meta.get("converted_from") == "matplotlib" - title = title if title is not None else _title_text(layout) + if title is None: + title = meta.get("caption") or _title_text(layout) layout.pop("template", None) layout["autosize"] = True