From 03b52b00369dbb938b1205a279bf342b9e7c91f2 Mon Sep 17 00:00:00 2001 From: Max Lindqvist Date: Mon, 23 Nov 2026 06:55:17 +0000 Subject: [PATCH] Matplotlib parity for subplots: format strings and short keyword names, shared axes, scale options, text in axes coordinates, legend() --- src/maxplotlib/canvas/canvas.py | 82 ++++-- src/maxplotlib/subfigure/line_plot.py | 132 ++++++++-- .../tests/test_matplotlib_parity.py | 237 ++++++++++++++++++ src/maxplotlib/tests/test_xarray.py | 2 - src/maxplotlib/utils/plot_format.py | 106 ++++++++ ...tutorial_14_axis_and_layout_controls.ipynb | 99 ++++++++ 6 files changed, 608 insertions(+), 50 deletions(-) create mode 100644 src/maxplotlib/tests/test_matplotlib_parity.py create mode 100644 src/maxplotlib/utils/plot_format.py diff --git a/src/maxplotlib/canvas/canvas.py b/src/maxplotlib/canvas/canvas.py index ebd676f..8cc60fa 100644 --- a/src/maxplotlib/canvas/canvas.py +++ b/src/maxplotlib/canvas/canvas.py @@ -34,6 +34,19 @@ def to_gridspec_kw(self) -> dict[str, float]: return {"wspace": self.wspace, "hspace": self.hspace} +def _share_mode(value, name: str) -> str: + """Return ``"all"``, ``"row"``, ``"col"`` or ``"none"`` for a sharex/sharey value.""" + if value is True: + return "all" + if value is False or value is None: + return "none" + if value in ("all", "row", "col", "none"): + return value + raise ValueError( + f"{name} must be a bool or one of 'all', 'row', 'col', 'none', got {value!r}" + ) + + def _parse_bool_env_var(name: str, default: bool = False) -> bool: value = os.getenv(name) if value is None: @@ -314,6 +327,8 @@ def __init__( usetex: bool | None = None, subplot_spacing: SubplotSpacing | None = None, gridspec_kw: Mapping[str, float] | None = None, + sharex: bool | str = False, + sharey: bool | str = False, ): """ Initialize the Canvas class for multiple subplots. @@ -337,7 +352,15 @@ def __init__( Default is SubplotSpacing(wspace=0.08, hspace=0.1). gridspec_kw (Mapping[str, float]): Optional matplotlib gridspec kwargs. Kept for compatibility with existing code. + sharex, sharey (bool | str): Share the x or y axis between subplots, + as in ``matplotlib.pyplot.subplots``: ``True`` or ``"all"`` (every + subplot), ``"col"`` (each column), ``"row"`` (each row), ``False`` + or ``"none"``. Shared axes have the same limits, and only the + outer subplots carry tick labels. The Matplotlib, TikZ and Plotly + backends share; the terminal backend draws each subplot alone. """ + self._sharex = _share_mode(sharex, "sharex") + self._sharey = _share_mode(sharey, "sharey") self._nrows = nrows self._ncols = ncols @@ -456,7 +479,8 @@ def subplots( list when the grid is 1×1 or when one dimension is 1. wspace, hspace (float): Convenience subplot spacing arguments. These map to matplotlib gridspec spacing values. - **canvas_kwargs: Forwarded to the Canvas constructor. + **canvas_kwargs: Forwarded to the Canvas constructor, among them + ``sharex`` and ``sharey``. Returns: (canvas, axes): A tuple of the Canvas and either a single LinePlot, @@ -467,6 +491,7 @@ def subplots( >>> canvas, ax = Canvas.subplots() >>> canvas, (ax1, ax2) = Canvas.subplots(ncols=2) >>> canvas, axes = Canvas.subplots(nrows=2, ncols=2) # axes[row][col] + >>> canvas, (top, bottom) = Canvas.subplots(nrows=2, sharex=True) """ spacing_given = wspace is not None or hspace is not None if spacing_given and ( @@ -689,6 +714,7 @@ def add_line( self, x, y, + fmt=None, layer=0, subplot: LinePlot | None = None, row: int | None = None, @@ -709,8 +735,9 @@ def add_line( subplot = self.add_subplot(col=col, row=row) subplot.add_line( - x=x, - y=y, + x, + y, + fmt, layer=layer, **kwargs, ) @@ -1399,19 +1426,30 @@ def set_legend( self._get_or_create_subplot(row, col).set_legend(visible, **kwargs) def legend(self, row=None, col=None, **kwargs): - self._get_or_create_subplot(row, col).set_legend(**kwargs) + """Show the legend of a subplot, as Matplotlib's ``Axes.legend``.""" + self._get_or_create_subplot(row, col).legend(**kwargs) def tick_params(self, row: int | None = None, col: int | None = None, **kwargs): """Configure major/minor tick appearance for a subplot.""" self._get_or_create_subplot(row, col).tick_params(**kwargs) - def set_xscale(self, scale: str, row: int | None = None, col: int | None = None): - """Set x-axis scale ('linear', 'log', 'symlog') for a subplot.""" - self._get_or_create_subplot(row, col).set_xscale(scale) + def set_xscale( + self, scale: str, row: int | None = None, col: int | None = None, **kwargs + ): + """Set x-axis scale ('linear', 'log', 'symlog') for a subplot. + + ``kwargs`` are Matplotlib's options of the scale, e.g. ``linthresh``. + """ + self._get_or_create_subplot(row, col).set_xscale(scale, **kwargs) + + def set_yscale( + self, scale: str, row: int | None = None, col: int | None = None, **kwargs + ): + """Set y-axis scale ('linear', 'log', 'symlog') for a subplot. - def set_yscale(self, scale: str, row: int | None = None, col: int | None = None): - """Set y-axis scale ('linear', 'log', 'symlog') for a subplot.""" - self._get_or_create_subplot(row, col).set_yscale(scale) + ``kwargs`` are Matplotlib's options of the scale, e.g. ``linthresh``. + """ + self._get_or_create_subplot(row, col).set_yscale(scale, **kwargs) def set_axis_off(self, row: int | None = None, col: int | None = None): """Hide the axis frame, ticks, and labels for a subplot.""" @@ -2289,7 +2327,9 @@ def savefig( def plot(self, *args, backend=None, **kwargs): """Add a line, or render when called with backend options. - ``canvas.plot(x, y, **style)`` is the convenient direct plotting form. + ``canvas.plot(x, y, **style)`` is the convenient direct plotting form; + ``canvas.plot(x, y, "o--")`` takes a Matplotlib format string and + ``canvas.plot(y)`` plots against the index, as ``Axes.plot`` does. ``canvas.plot(da)`` plots a 1-D ``xarray.DataArray`` against its coordinate, labelling the axes from its attributes; ``hue=`` draws a 2-D one as one line per value of ``dim``. @@ -2297,21 +2337,13 @@ def plot(self, *args, backend=None, **kwargs): ``canvas.plot(backend=...)`` form remains supported. """ explicit_render = backend is not None or (args and isinstance(args[0], str)) - if len(args) == 1 and xarray_support.is_dataarray(args[0]): - layer = kwargs.pop("layer", 0) - row = kwargs.pop("row", None) - col = kwargs.pop("col", None) - self._get_or_create_subplot(row, col).plot(args[0], layer=layer, **kwargs) - return self if args and not isinstance(args[0], str): - if len(args) < 2: - raise TypeError("plot(x, y) requires both x and y data") - if len(args) > 2: - raise TypeError("plot() accepts only x and y positional data") + if len(args) > 3: + raise TypeError("plot() takes x, y and a format string") layer = kwargs.pop("layer", 0) row = kwargs.pop("row", None) col = kwargs.pop("col", None) - self.add_line(args[0], args[1], layer=layer, row=row, col=col, **kwargs) + self._get_or_create_subplot(row, col).plot(*args, layer=layer, **kwargs) return self if args: if len(args) > 1: @@ -2517,6 +2549,8 @@ def _plot_matplotlib( subplot_kwargs = { "squeeze": False, "gridspec_kw": self._gridspec_kw, + "sharex": self._sharex, + "sharey": self._sharey, } if self._figsize is not None: subplot_kwargs["figsize"] = self._figsize @@ -2951,11 +2985,15 @@ def plot_plotly( [{"secondary_y": (r, c) in self._twinx_subplots} for c in range(self.ncols)] for r in range(self.nrows) ] + # Matplotlib's names of the sharing, in Plotly's + plotly_share = {"all": "all", "col": "columns", "row": "rows", "none": False} fig = make_subplots( rows=self.nrows, cols=self.ncols, subplot_titles=subplot_titles, specs=specs, + shared_xaxes=plotly_share[self._sharex], + shared_yaxes=plotly_share[self._sharey], ) if self._hide_empty_subplots: for row in range(self.nrows): diff --git a/src/maxplotlib/subfigure/line_plot.py b/src/maxplotlib/subfigure/line_plot.py index b5bc79c..d33f5bc 100644 --- a/src/maxplotlib/subfigure/line_plot.py +++ b/src/maxplotlib/subfigure/line_plot.py @@ -5,6 +5,7 @@ import plotly.graph_objects as go from maxplotlib.utils import xarray_support +from maxplotlib.utils.plot_format import apply_plot_format, draws_no_line # Keyword arguments that every drawing method accepts and that are handled by # maxplotlib itself rather than being forwarded to a backend drawing call. @@ -112,6 +113,21 @@ def _colormap_to_plotly_colorscale(colormap, steps=17): return [[float(position), color] for position, color in zip(positions, colors)] +def _named_transform(ax, name: str): + """The Matplotlib transform of a named coordinate system of ``ax``.""" + transforms = { + "data": ax.transData, + "axes": ax.transAxes, + "figure": ax.figure.transFigure, + } + if name not in transforms: + raise ValueError( + f"transform must be one of {sorted(transforms)} or a Matplotlib " + f"transform, got {name!r}" + ) + return transforms[name] + + class Node: def __init__(self, x, y, label="", content="", layer=0, **kwargs): self.x = x @@ -216,6 +232,8 @@ def __init__( # Axis scale type ('linear', 'log', 'symlog') self._xaxis_scale: str | None = None self._yaxis_scale: str | None = None + self._xaxis_scale_kwargs: dict = {} + self._yaxis_scale_kwargs: dict = {} self._axis_off = False self._axisbelow = None self._facecolor = None @@ -301,6 +319,7 @@ def add_line( self, x, y, + fmt=None, layer=0, **kwargs, ): @@ -310,16 +329,27 @@ def add_line( Parameters: x (array-like): X-axis data. y (array-like): Y-axis data. + fmt (str): Matplotlib format string, e.g. ``"o"``, ``"x--"`` or + ``"k:"`` (see :func:`~maxplotlib.utils.plot_format.parse_plot_format`). + A marker without a line style draws the markers only. A keyword + argument wins over the same setting in ``fmt``. layer (int): Layer index (default 0). **kwargs: Additional keyword arguments forwarded to the backend - (e.g., color, linestyle, label, linewidth). + (e.g., color, linestyle, label, linewidth). Matplotlib's short + names (``ls``, ``lw``, ``ms``, ``c``, ``mec``, ``mew``, ``mfc``) + are accepted by every backend. """ + if fmt is not None and not isinstance(fmt, str): + raise TypeError( + "the third positional argument of a line is a format string; " + "pass the layer as layer=..." + ) ld = { "x": np.array(x), "y": np.array(y), "layer": layer, "plot_type": "plot", - "kwargs": kwargs, + "kwargs": apply_plot_format(fmt, kwargs), } self._add(ld, layer) @@ -368,18 +398,28 @@ def _plot_dataarray(self, method, da, layer, kwargs): if hue is not None and add_legend: self._legend = True - def plot(self, x, y=None, layer=0, **kwargs): - """Matplotlib-style alias for :meth:`add_line`. + def plot(self, x, y=None, fmt=None, layer=0, **kwargs): + """Draw a line, as Matplotlib's ``Axes.plot``. + + ``plot(x, y)``, ``plot(x, y, "o--")`` and ``plot(y)`` or + ``plot(y, "o")`` (against the index) are accepted; the format string + and the keyword arguments are those of :meth:`add_line`. ``plot(da)`` with a 1-D ``xarray.DataArray`` plots it against its coordinate; see :meth:`_plot_dataarray`. """ + if isinstance(y, str): # plot(y, fmt) + if fmt is not None: + raise TypeError("plot() got two format strings") + y, fmt = None, y if y is None: - if not xarray_support.is_dataarray(x): - raise TypeError("plot(x, y) requires both x and y data") - self._plot_dataarray(self.add_line, x, layer, kwargs) - return - self.add_line(x, y, layer=layer, **kwargs) + if xarray_support.is_dataarray(x): + if fmt is not None: + kwargs = apply_plot_format(fmt, kwargs) + self._plot_dataarray(self.add_line, x, layer, kwargs) + return + x, y = np.arange(len(x)), x + self.add_line(x, y, fmt, layer=layer, **kwargs) @staticmethod def _mesh_of(da, kwargs, method): @@ -971,15 +1011,26 @@ def set_legend(self, visible: bool = True, **kwargs): self._legend = visible self._legend_kwargs = dict(kwargs) - def set_xscale(self, scale: str): - """Set the x-axis scale type: 'linear', 'log', or 'symlog'.""" + def set_xscale(self, scale: str, **kwargs): + """Set the x-axis scale type: 'linear', 'log', or 'symlog'. + + ``kwargs`` are Matplotlib's options of the scale, e.g. ``linthresh`` + and ``linscale`` of ``"symlog"`` or ``base`` of ``"log"``. They apply + to the Matplotlib and TikZ output; the other backends draw the scale + with their own defaults. + """ self._xaxis_scale = scale + self._xaxis_scale_kwargs = dict(kwargs) if hasattr(self, "_import_scales"): self._import_xscale_edited = True - def set_yscale(self, scale: str): - """Set the y-axis scale type: 'linear', 'log', or 'symlog'.""" + def set_yscale(self, scale: str, **kwargs): + """Set the y-axis scale type: 'linear', 'log', or 'symlog'. + + ``kwargs`` are Matplotlib's options of the scale, see :meth:`set_xscale`. + """ self._yaxis_scale = scale + self._yaxis_scale_kwargs = dict(kwargs) if hasattr(self, "_import_scales"): self._import_yscale_edited = True @@ -1428,6 +1479,10 @@ def text(self, x, y, s, layer=0, **kwargs): x, y (float): Position. s (str): Text string. **kwargs: Forwarded to ax.text (e.g., fontsize, color, ha, va). + ``transform`` names the coordinates of (x, y): ``"data"`` (the + default), ``"axes"`` (fractions of the subplot, (0, 0) its lower + left corner) or ``"figure"`` (fractions of the figure). A + Matplotlib transform is passed on to the Matplotlib backend. """ ld = { "x": x, @@ -1828,7 +1883,11 @@ def plot_matplotlib( ann_kwargs["xytext"] = line["xytext"] ax.annotate(line["text"], xy=line["xy"], **ann_kwargs) elif line["plot_type"] == "text": - ax.text(line["x"], line["y"], line["s"], **line["kwargs"]) + text_kwargs = dict(line["kwargs"]) + transform = text_kwargs.get("transform") + if isinstance(transform, str): + text_kwargs["transform"] = _named_transform(ax, transform) + ax.text(line["x"], line["y"], line["s"], **text_kwargs) elif line["plot_type"] == "axvline": ax.axvline(x=line["x"], **line["kwargs"]) elif line["plot_type"] == "axhline": @@ -1908,13 +1967,13 @@ def plot_matplotlib( or self._xaxis_scale != self._import_scales[0] or getattr(self, "_import_xscale_edited", False) ): - ax.set_xscale(self._xaxis_scale) + ax.set_xscale(self._xaxis_scale, **self._xaxis_scale_kwargs) if self._yaxis_scale is not None and ( not hasattr(self, "_import_scales") or self._yaxis_scale != self._import_scales[1] or getattr(self, "_import_yscale_edited", False) ): - ax.set_yscale(self._yaxis_scale) + ax.set_yscale(self._yaxis_scale, **self._yaxis_scale_kwargs) if self._xticks is not None: ax.set_xticks( self._xticks, @@ -2335,6 +2394,8 @@ def bar_marker(kwargs): kwargs = line["kwargs"] marker = kwargs.get("marker") mode = "lines+markers" if marker is not None else "lines" + if draws_no_line(kwargs.get("linestyle", "solid")): + mode = "markers" if marker is not None else "none" trace = go.Scatter( x=tx(line["x"]), y=ty(line["y"]), @@ -3424,8 +3485,23 @@ def error_spec(values, scale): weight=kwargs.get("fontweight", None), ) if plot_type == "text": - x = txs(float(line["x"])) - y = tys(float(line["y"])) + transform = kwargs.get("transform", "data") + if transform == "data": + x = txs(float(line["x"])) + y = tys(float(line["y"])) + refs = {} + elif transform in ("axes", "figure"): + # fractions of the subplot or of the whole figure + x, y = float(line["x"]), float(line["y"]) + ref = "domain" if transform == "axes" else "paper" + refs = {"xref": f"x {ref}", "yref": f"y {ref}"} + if transform == "figure": + refs = {"xref": "paper", "yref": "paper"} + else: + raise NotImplementedError( + "Plotly places text in 'data', 'axes' or 'figure' " + f"coordinates, not {transform!r}" + ) text = line["s"] annotations.append( dict( @@ -3436,6 +3512,7 @@ def error_spec(values, scale): xanchor=ha_to_xanchor.get(kwargs.get("ha"), "left"), yanchor=va_to_yanchor.get(kwargs.get("va"), "bottom"), font=font, + **refs, ) ) else: @@ -4160,7 +4237,10 @@ def plot_plotext(self, ax, layers=None): x = self._transform_x(line["x"]).tolist() y = self._transform_y(line["y"]).tolist() plot_kwargs = self._plotext_plot_kwargs(kwargs) - ax.plot(x, y, **plot_kwargs) + if draws_no_line(kwargs.get("linestyle", "solid")): + ax.scatter(x, y, **plot_kwargs) + else: + ax.plot(x, y, **plot_kwargs) legend_entries.append((kwargs.get("label"), kwargs.get("color"))) elif plot_type == "scatter": x = self._transform_x(line["x"]).tolist() @@ -4485,14 +4565,14 @@ def grid(self): def grid(self, value): self._grid = value - # Getter and Setter for legend - @property - def legend(self): - return self._legend + def legend(self, **kwargs): + """Show the legend, as Matplotlib's ``Axes.legend``. - @legend.setter - def legend(self, value): - self._legend = value + ``kwargs`` are Matplotlib's (``loc``, ``fontsize``, ``ncols``, ...). + The entries are the labelled artists of the subplot; ``set_legend`` + hides the legend again. + """ + self.set_legend(True, **kwargs) if __name__ == "__main__": diff --git a/src/maxplotlib/tests/test_matplotlib_parity.py b/src/maxplotlib/tests/test_matplotlib_parity.py new file mode 100644 index 0000000..9f2bc00 --- /dev/null +++ b/src/maxplotlib/tests/test_matplotlib_parity.py @@ -0,0 +1,237 @@ +"""Calls that work on Matplotlib's ``Axes`` and work the same on a subplot: +format strings, short keyword names, shared axes, scale options, text in +axes coordinates and ``legend()``.""" + +import matplotlib + +matplotlib.use("Agg") + +import matplotlib.pyplot as plt # noqa: E402 +import numpy as np # noqa: E402 +import pytest # noqa: E402 + +from maxplotlib import Canvas # noqa: E402 +from maxplotlib.utils.plot_format import ( # noqa: E402 + canonical_line_kwargs, + parse_plot_format, +) + +X = np.linspace(0.0, 1.0, 5) + + +def _mpl_axes(canvas): + fig, axes = canvas.render(backend="matplotlib") + return fig, np.asarray(axes) + + +# --- format strings --------------------------------------------------------------- + + +@pytest.mark.parametrize( + "fmt, expected", + [ + ("o", {"marker": "o", "linestyle": "None"}), + ("x--", {"marker": "x", "linestyle": "--"}), + ("--x", {"marker": "x", "linestyle": "--"}), + ("k:", {"color": "k", "linestyle": ":"}), + ("-.", {"linestyle": "-."}), + ("C1s-", {"color": "C1", "marker": "s", "linestyle": "-"}), + ("ro", {"color": "r", "marker": "o", "linestyle": "None"}), + ("C3", {"color": "C3"}), + ("red", {"color": "red"}), + ("0.5", {"color": "0.5"}), + ("1", {"marker": "1", "linestyle": "None"}), + ("", {}), + ], +) +def test_parse_plot_format(fmt, expected): + assert parse_plot_format(fmt) == expected + + +@pytest.mark.parametrize("fmt", ["oo", "---", "kr", "q", "o?"]) +def test_parse_plot_format_rejects_what_matplotlib_rejects(fmt): + with pytest.raises(ValueError, match="format string"): + parse_plot_format(fmt) + + +def test_short_keyword_names_are_spelled_out(): + assert canonical_line_kwargs( + {"ls": ":", "lw": 2, "ms": 3, "c": "k", "mfc": "none"} + ) == { + "linestyle": ":", + "linewidth": 2, + "markersize": 3, + "color": "k", + "markerfacecolor": "none", + } + with pytest.raises(TypeError, match="aliases"): + canonical_line_kwargs({"ls": ":", "linestyle": "-"}) + + +def test_a_format_string_draws_as_in_matplotlib(): + canvas, ax = Canvas.subplots() + ax.plot(X, X, "o") + ax.plot(X, 2 * X, "x--", color="C3") + ax.plot(X, 3 * X, "k:", ls="-") # the keyword wins over the format string + fig, axes = _mpl_axes(canvas) + markers, dashed, solid = axes[0, 0].get_lines() + assert (markers.get_marker(), markers.get_linestyle()) == ("o", "None") + assert (dashed.get_marker(), dashed.get_linestyle()) == ("x", "--") + assert matplotlib.colors.same_color(dashed.get_color(), "C3") + assert solid.get_linestyle() == "-" + assert matplotlib.colors.same_color(solid.get_color(), "k") + plt.close(fig) + + +def test_plot_against_the_index_and_from_the_canvas(): + canvas = Canvas() + canvas.plot([3.0, 1.0, 2.0]) + canvas.plot([3.0, 1.0, 2.0], "s") + canvas.plot(X, X, "v-", lw=3) + fig, axes = _mpl_axes(canvas) + index, squares, wide = axes[0, 0].get_lines() + np.testing.assert_allclose(index.get_xdata(), [0, 1, 2]) + np.testing.assert_allclose(index.get_ydata(), [3, 1, 2]) + assert (squares.get_marker(), squares.get_linestyle()) == ("s", "None") + assert (wide.get_marker(), wide.get_linewidth()) == ("v", 3) + plt.close(fig) + + +def test_a_positional_layer_is_refused(): + _, ax = Canvas.subplots() + with pytest.raises(TypeError, match="layer="): + ax.plot(X, X, 1) + ax.plot(X, X, layer=1) + assert ax.layers == [1] + + +def test_markers_only_in_plotly_plotext_and_tikz(): + canvas, ax = Canvas.subplots() + ax.plot(X, X, "o", ms=7, label="markers") + ax.plot(X, 2 * X, "s-", lw=2.5) + plotly_fig = canvas.render(backend="plotly") + assert plotly_fig.data[0].mode == "markers" + assert plotly_fig.data[0].marker.size == 7 + assert plotly_fig.data[1].mode == "lines+markers" + assert plotly_fig.data[1].line.width == 2.5 + assert canvas.render(backend="plotext").build() + tikz = canvas.render(backend="tikzfigure").generate_tikz() + assert "only marks" in tikz + + +# --- shared axes -------------------------------------------------------------------- + + +def test_shared_axes_in_matplotlib(): + canvas, axes = Canvas.subplots(nrows=2, ncols=2, sharex=True, sharey="row") + axes[0][0].plot([0, 1], [0, 1]) + axes[1][1].plot([0, 10], [0, 5]) + fig, m = _mpl_axes(canvas) + assert m[0, 0].get_xlim() == m[1, 1].get_xlim() # x shared by all + assert m[0, 0].get_ylim() == m[0, 1].get_ylim() # y shared within a row + assert m[0, 0].get_ylim() != m[1, 0].get_ylim() + fig.canvas.draw() + assert not any(t.get_visible() for t in m[0, 0].get_xticklabels()) + assert any(t.get_visible() for t in m[1, 0].get_xticklabels()) + assert not any(t.get_visible() for t in m[1, 1].get_yticklabels()) + plt.close(fig) + + +def test_shared_columns_keep_their_own_range(): + canvas, axes = Canvas.subplots(nrows=2, ncols=2, sharex="col") + axes[0][0].plot([0, 1], [0, 1]) + axes[1][1].plot([0, 10], [0, 5]) + fig, m = _mpl_axes(canvas) + assert m[0, 0].get_xlim() == m[1, 0].get_xlim() + assert m[0, 1].get_xlim() == m[1, 1].get_xlim() + assert m[0, 0].get_xlim() != m[0, 1].get_xlim() + plt.close(fig) + + +def test_shared_axes_in_plotly_and_tikz(): + canvas, (top, bottom) = Canvas.subplots(nrows=2, sharex=True) + top.plot([0, 1], [0, 1]) + bottom.plot([0, 10], [0, 5]) + fig = canvas.render(backend="plotly") + # one x axis follows the other (Plotly anchors the group on the bottom row) + assert {fig.layout.xaxis.matches, fig.layout.xaxis2.matches} - {None} + unshared = Canvas(nrows=2) + unshared.plot([0, 1], [0, 1], row=0, col=0) + unshared.plot([0, 10], [0, 5], row=1, col=0) + layout = unshared.render(backend="plotly").layout + assert layout.xaxis.matches is None and layout.xaxis2.matches is None + tikz = canvas.render(backend="tikzfigure").generate_tikz() + limits = [ + line.split("xmin=")[1].split(",")[0] + for line in tikz.splitlines() + if "xmin=" in line + ] + assert len(limits) == 2 and limits[0] == limits[1] + + +def test_an_unknown_sharing_is_refused(): + with pytest.raises(ValueError, match="sharex"): + Canvas(nrows=2, sharex="columns") + + +# --- scale options, text coordinates, legend -------------------------------------------- + + +def test_scale_options_reach_matplotlib(): + canvas, ax = Canvas.subplots() + ax.plot([-10, 10], [-10, 10]) + ax.set_yscale("symlog", linthresh=0.5) + canvas.set_xscale("log", base=2) + fig, axes = _mpl_axes(canvas) + assert axes[0, 0].yaxis.get_transform().linthresh == 0.5 + assert axes[0, 0].xaxis.get_transform().base == 2 + plt.close(fig) + + +def test_text_in_axes_and_figure_coordinates(): + canvas, ax = Canvas.subplots() + ax.plot([0, 100], [0, 100]) + ax.text(0.5, 0.9, "in the axes", transform="axes", ha="center") + ax.text(0.01, 0.01, "in the figure", transform="figure") + ax.text(50, 50, "in the data") + fig, axes = _mpl_axes(canvas) + in_axes, in_figure, in_data = axes[0, 0].texts + assert in_axes.get_transform() == axes[0, 0].transAxes + assert in_figure.get_transform() == fig.transFigure + assert in_data.get_transform() == axes[0, 0].transData + plt.close(fig) + + annotations = { + a.text: a for a in canvas.render(backend="plotly").layout.annotations + } + assert annotations["in the axes"].xref == "x domain" + assert annotations["in the axes"].y == 0.9 + assert annotations["in the figure"].xref == "paper" + assert annotations["in the data"].xref == "x" + + assert "in the axes" in canvas.render(backend="tikzfigure").generate_tikz() + + +def test_an_unknown_text_coordinate_system_is_refused(): + canvas, ax = Canvas.subplots() + ax.text(0.5, 0.5, "where?", transform="polar") + with pytest.raises(ValueError, match="transform"): + canvas.render(backend="matplotlib") + with pytest.raises(NotImplementedError, match="polar"): + canvas.render(backend="plotly") + + +def test_legend_is_a_method_as_in_matplotlib(): + canvas, (left, right) = Canvas.subplots(ncols=2) + left.plot(X, X, label="a") + right.plot(X, X, label="b") + left.legend(loc="lower right", fontsize=7) + canvas.legend(row=0, col=1, title="right") + fig, axes = _mpl_axes(canvas) + assert axes[0, 0].get_legend().get_texts()[0].get_fontsize() == 7 + assert axes[0, 1].get_legend().get_title().get_text() == "right" + plt.close(fig) + left.set_legend(False) + fig, axes = _mpl_axes(canvas) + assert axes[0, 0].get_legend() is None + plt.close(fig) diff --git a/src/maxplotlib/tests/test_xarray.py b/src/maxplotlib/tests/test_xarray.py index 0713d5e..441b788 100644 --- a/src/maxplotlib/tests/test_xarray.py +++ b/src/maxplotlib/tests/test_xarray.py @@ -98,8 +98,6 @@ def test_plot_rejects_wrong_ndim(): canvas = Canvas() with pytest.raises(ValueError, match="1-D DataArray.*sel"): canvas.plot(_mesh()) - with pytest.raises(TypeError, match="both x and y"): - canvas.plot(np.arange(3)) def test_plot_x_y_arrays_still_work_with_dataarrays(): diff --git a/src/maxplotlib/utils/plot_format.py b/src/maxplotlib/utils/plot_format.py new file mode 100644 index 0000000..5ab46cc --- /dev/null +++ b/src/maxplotlib/utils/plot_format.py @@ -0,0 +1,106 @@ +"""Matplotlib's shorthand for line plots: format strings and keyword aliases.""" + +import re + +from matplotlib.colors import is_color_like + +#: Matplotlib's one-character markers. +MARKERS = frozenset(".,ov^<>1234sp*hH+xDd|_PX") +#: Matplotlib's one-letter colours. +COLORS = frozenset("bgrcmykw") +#: Line styles of a format string, the two-character ones first. +LINESTYLES = ("--", "-.", "-", ":") + +#: Short keyword names of a line and the ones the backends read. +LINE_ALIASES = { + "c": "color", + "ls": "linestyle", + "lw": "linewidth", + "ms": "markersize", + "mec": "markeredgecolor", + "mew": "markeredgewidth", + "mfc": "markerfacecolor", +} + +_CYCLE_COLOR = re.compile(r"C\d+") + + +def parse_plot_format(fmt: str) -> dict: + """Return the ``color``, ``marker`` and ``linestyle`` of a format string. + + The format is Matplotlib's ``"[marker][line][color]"`` in any order, for + example ``"o"``, ``"x--"``, ``"k:"`` or ``"C1s-"``; a string that is a colour + on its own (``"red"``, ``"C2"``, ``"0.5"``) sets the colour only. As in + Matplotlib, a marker without a line style draws no line + (``linestyle="None"``). Only the parts the string gives are returned. + + Raises: + ValueError: for a character that is none of the three, or a part given twice. + """ + if not isinstance(fmt, str): + raise TypeError(f"a format string must be a str, got {type(fmt).__name__}") + # "1" to "4" are markers (tri_down, ...), not the grey levels they also spell + if fmt not in MARKERS and (_CYCLE_COLOR.fullmatch(fmt) or is_color_like(fmt)): + return {"color": fmt} + + parts = {} + + def take(key, value): + if key in parts: + raise ValueError(f"Illegal format string {fmt!r}: two {key} symbols") + parts[key] = value + + i = 0 + while i < len(fmt): + cycle = _CYCLE_COLOR.match(fmt, i) + style = next((s for s in LINESTYLES if fmt.startswith(s, i)), None) + if cycle: + take("color", cycle.group()) + i = cycle.end() + elif style: + take("linestyle", style) + i += len(style) + elif fmt[i] in MARKERS: + take("marker", fmt[i]) + i += 1 + elif fmt[i] in COLORS: + take("color", fmt[i]) + i += 1 + else: + raise ValueError( + f"Unrecognized character {fmt[i]!r} in format string {fmt!r}" + ) + if "marker" in parts and "linestyle" not in parts: + parts["linestyle"] = "None" + return parts + + +def canonical_line_kwargs(kwargs: dict) -> dict: + """Return ``kwargs`` with Matplotlib's short names spelled out. + + ``ls``, ``lw``, ``ms``, ``c``, ``mec``, ``mew`` and ``mfc`` become + ``linestyle``, ``linewidth``, ``markersize``, ``color``, ``markeredgecolor``, + ``markeredgewidth`` and ``markerfacecolor``, which is what every backend + reads. Giving a short name together with its long one is an error, as in + Matplotlib. + """ + out = {} + for key, value in kwargs.items(): + name = LINE_ALIASES.get(key, key) + if name in out or (name != key and name in kwargs): + raise TypeError(f"Got both {name!r} and {key!r}, which are aliases") + out[name] = value + return out + + +def apply_plot_format(fmt: str | None, kwargs: dict) -> dict: + """Return the line keywords of ``fmt`` and ``kwargs``; a keyword wins.""" + kwargs = canonical_line_kwargs(kwargs) + if fmt is None: + return kwargs + return {**parse_plot_format(fmt), **kwargs} + + +def draws_no_line(linestyle) -> bool: + """Whether a line style means markers only (``"None"``, ``"none"``, ``""``).""" + return isinstance(linestyle, str) and linestyle.strip().lower() in ("", "none") diff --git a/tutorials/tutorial_14_axis_and_layout_controls.ipynb b/tutorials/tutorial_14_axis_and_layout_controls.ipynb index 1f50022..01bafc5 100644 --- a/tutorials/tutorial_14_axis_and_layout_controls.ipynb +++ b/tutorials/tutorial_14_axis_and_layout_controls.ipynb @@ -182,6 +182,105 @@ "plotly_canvas.set_xticklabels([\"small\", \"medium\", \"large\"], color=\"darkgreen\")\n", "plotly_canvas.show(backend=\"plotly\")" ] + }, + { + "cell_type": "markdown", + "id": "14", + "metadata": {}, + "source": [ + "## Format strings and short keyword names\n", + "\n", + "`plot()` takes Matplotlib's format string, `\"[marker][line][color]\"`: `\"o\"` draws markers only, `\"x--\"` crosses on a dashed line, `\"k:\"` a black dotted line. A keyword argument wins over the same setting in the format string. Matplotlib's short names (`ls`, `lw`, `ms`, `c`, `mec`, `mew`, `mfc`) work on every backend." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "15", + "metadata": {}, + "outputs": [], + "source": [ + "canvas = Canvas()\n", + "canvas.plot(x, np.sin(x), \"k:\", label=\"dotted\")\n", + "canvas.plot(x[::10], np.sin(x[::10]), \"o\", ms=5, mfc=\"none\", label=\"markers only\")\n", + "canvas.plot(x[::20], np.cos(x[::20]), \"C3x--\", lw=1, label=\"crosses on a dashed line\")\n", + "canvas.legend()\n", + "canvas.show()" + ] + }, + { + "cell_type": "markdown", + "id": "16", + "metadata": {}, + "source": [ + "## Shared axes\n", + "\n", + "`sharex` and `sharey` link the axes of the subplots as in `matplotlib.pyplot.subplots`: `True` (or `\"all\"`), `\"col\"` or `\"row\"`. Shared axes have the same limits, and only the outer subplots carry tick labels. The Matplotlib, TikZ and Plotly backends share; the terminal backend draws each subplot on its own." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "17", + "metadata": {}, + "outputs": [], + "source": [ + "canvas, (top, bottom) = Canvas.subplots(nrows=2, sharex=True, hspace=0.15)\n", + "top.plot(x, np.sin(x))\n", + "bottom.plot(x[:100], np.cos(x[:100]), \"C1\")\n", + "top.set_ylabel(\"sin\")\n", + "bottom.set_ylabel(\"cos\")\n", + "bottom.set_xlabel(\"x\")\n", + "canvas.show()" + ] + }, + { + "cell_type": "markdown", + "id": "18", + "metadata": {}, + "source": [ + "## Scale options\n", + "\n", + "`set_xscale()` and `set_yscale()` pass Matplotlib's options of the scale on, for example the linear range of a symmetric logarithmic axis." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "19", + "metadata": {}, + "outputs": [], + "source": [ + "canvas, ax = Canvas.subplots()\n", + "ax.plot(x - 5, (x - 5) ** 3)\n", + "ax.set_yscale(\"symlog\", linthresh=1.0)\n", + "ax.set_title(\"symlog with a linear range of 1\")\n", + "canvas.show()" + ] + }, + { + "cell_type": "markdown", + "id": "20", + "metadata": {}, + "source": [ + "## Text in axes coordinates and `legend()`\n", + "\n", + "`text(..., transform=\"axes\")` places text at a fraction of the subplot ((0, 0) is its lower left corner) and `transform=\"figure\"` at a fraction of the figure, whatever the data limits are. `legend()` shows the legend with Matplotlib's options, as `Axes.legend` does." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "21", + "metadata": {}, + "outputs": [], + "source": [ + "canvas, ax = Canvas.subplots()\n", + "ax.plot(x, x**2, label=\"$x^2$\")\n", + "ax.text(0.05, 0.9, \"upper left of the axes\", transform=\"axes\")\n", + "ax.legend(loc=\"lower right\", fontsize=8)\n", + "canvas.show()" + ] } ], "metadata": {