From 2f6c6b37548b932166c51a151e56f34356379f06 Mon Sep 17 00:00:00 2001 From: FridrichMethod Date: Mon, 16 Nov 2026 18:06:16 -0800 Subject: [PATCH] feat(utils): add_axes_inches, legend_inches and suptitle_inches Public helpers for Prism-style layouts in inches: - add_axes_inches(fig, left, bottom, width, height) places axes whose x- and y-axis lengths are given in inches. An axes locator keeps the position and size when the figure is resized and at any dpi. - legend_inches(ax, x, y, loc) puts the legend's loc point at (x, y) inches. - suptitle_inches(fig, t, top) puts a centered figure title's top edge top inches below the figure's top edge. The example scripts use them instead of their own copies; examples/_common.py keeps only the Arial check and save(). README documents the feature and AGENTS.md points the rendering rules at mplplots.utils. The regenerated example images are byte-identical. --- AGENTS.md | 4 +- README.md | 46 +++++++++++++ examples/_common.py | 81 +++-------------------- examples/palettes_demo.py | 26 ++++---- examples/styles_demo.py | 22 +++---- src/mplplots/utils.py | 132 +++++++++++++++++++++++++++++++++++++- tests/test_utils.py | 100 ++++++++++++++++++++++++++++- 7 files changed, 311 insertions(+), 100 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 22ab492..6bb20e7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,8 +50,8 @@ Do not commit or push if either fails. Fix issues first. them use the GraphPadPrism style except `default_style`, which shows Matplotlib's defaults. - Lay figures out in round inches: the figure size, each axes' position and size (the axis lengths), and the anchors of legends and figure titles are multiples of 0.1, 0.25, 0.5 or 1 in. - Place them with `add_axes`, `legend` and `suptitle` from `examples/_common.py`, not with - `tight_layout`, `subplots_adjust` or a tight bounding box. + Place them with `add_axes_inches`, `legend_inches` and `suptitle_inches` from + `mplplots.utils`, not with `tight_layout`, `subplots_adjust` or a tight bounding box. - Keep the style's text: pass no `fontsize` or `fontweight`. - Render every figure in three formats with `save()` from `examples/_common.py`: PNG at 600 dpi, SVG and PDF, side by side in `examples/`, uncropped and without timestamps, so rerunning an diff --git a/README.md b/README.md index fafd5ef..467cc69 100644 --- a/README.md +++ b/README.md @@ -275,6 +275,52 @@ replaces the major tick locators of linear numeric axes. If you set custom tick labels on such an axis (for example, the group labels of a grouped bar chart with numeric bar positions), set them after calling `auto_ticks`. +## Axis lengths in inches + +GraphPad Prism sets the length of each axis directly, instead of deriving it from the figure size +and margins. `add_axes_inches` does the same: it places axes at a position and size given in +inches from the figure's lower-left corner, so the x- and y-axes are exactly as long as you ask. +`legend_inches` and `suptitle_inches` place a legend and a figure title in inches too. All three +keep their place when the figure is resized and at any dpi, and because the style does not crop +saved figures, the saved file has exactly the figure's size. + +```python +import matplotlib.pyplot as plt +import numpy as np + +from mplplots.utils import add_axes_inches, auto_ticks, legend_inches + +plt.style.use("mplplots.styles.GraphPadPrism") + +x = np.linspace(0, 10, 50) +fig = plt.figure(figsize=(3, 2.25)) # the saved file is 3 × 2.25 in +ax = add_axes_inches(fig, left=0.5, bottom=0.4, width=2.25, height=1.5) # 2.25 in by 1.5 in axes +ax.plot(x, np.sin(x), label="sin(x)") +ax.plot(x, np.cos(x), label="cos(x)") +auto_ticks(ax, left=0, right=10) +ax.set_xlabel("x") +ax.set_ylabel("y") +legend_inches(ax, 2.75, 1.9, loc="upper right", ncols=2) # upper-right corner at (2.75, 1.9) in +fig.savefig("figure.pdf") +``` + +- `add_axes_inches(fig, left, bottom, width, height, **kwargs)` adds axes whose x-axis is + `width` and y-axis `height` inches long, meeting at (`left`, `bottom`). Other keyword arguments + go to `fig.add_axes`. +- `legend_inches(ax, x, y, loc="upper left", **kwargs)` places the point of the legend box that + `loc` names at (`x`, `y`): a corner (`"upper left"`), the middle of an edge (`"center left"`), + or `"center"`. Other keyword arguments, such as `ncols` or `title`, go to `ax.legend`. +- `suptitle_inches(fig, t, top=0.1, **kwargs)` adds a centered figure title whose top edge is + `top` inches below the figure's top edge. + +With the style's 8 pt text, about 0.5 in to the left of the axes fits the tick labels and a y-axis +label, 0.4 in below fits the tick labels and an x-axis label, and 0.35 in above fits an axes +title. The GraphPadPrism image at the top of this README uses the layout above, plus a title. + +The axes keep their position through an axes locator, so `tight_layout`, constrained layout, +`ax.set_position`, and the space `fig.colorbar(..., ax=ax)` takes do not move them. For a +colorbar, add its axes with `add_axes_inches` and pass them as `cax`. + ## Gallery Generated by [`examples/styles_demo.py`](examples/styles_demo.py): diff --git a/examples/_common.py b/examples/_common.py index 5b930cd..36ab412 100644 --- a/examples/_common.py +++ b/examples/_common.py @@ -1,25 +1,23 @@ -"""Shared setup for the example scripts: Arial check, round-inch layout and saving. +"""Shared setup for the example scripts: the Arial check and saving in three formats. -Every figure is laid out in inches from its lower-left corner. The figure size, the -position and size of each axes, and the anchors of legends and figure titles are round -values: multiples of 0.1, 0.25, 0.5 or 1 in. Figures are saved uncropped, so the files -keep that size, as PNG (600 dpi), SVG and PDF. +Every figure is laid out in round inches with ``mplplots.utils.add_axes_inches``, +``legend_inches`` and ``suptitle_inches``: the figure size, the position and size of +each axes, and the anchors of legends and figure titles are multiples of 0.1, 0.25, 0.5 +or 1 in. ``save`` writes each figure uncropped, so the files keep that size, as PNG +(600 dpi), SVG and PDF. """ from __future__ import annotations import sys from pathlib import Path -from typing import TYPE_CHECKING, Any, Literal +from typing import TYPE_CHECKING, Any import matplotlib.pyplot as plt from matplotlib import font_manager if TYPE_CHECKING: - from matplotlib.axes import Axes from matplotlib.figure import Figure - from matplotlib.legend import Legend - from matplotlib.text import Text from matplotlib.typing import RcKeyType # Matplotlib 3.10+ STYLE = "mplplots.styles.GraphPadPrism" @@ -28,7 +26,8 @@ DPI = 600 # Without a fixed date and SVG id salt, every run would write different SVG and PDF files -# for the same figure. +# for the same figure. "standard" keeps the files uncropped even if a matplotlibrc asks +# for a tight bounding box. _METADATA: dict[str, dict[str, Any]] = {"svg": {"Date": None}, "pdf": {"CreationDate": None}} _SAVE_RC: dict[RcKeyType, Any] = {"savefig.bbox": "standard", "svg.hashsalt": "mplplots"} @@ -44,68 +43,6 @@ def require_arial() -> None: sys.exit("Arial is not installed; install it to regenerate the images.") -def add_axes(fig: Figure, left: float, bottom: float, width: float, height: float) -> Axes: - """Add axes of width x height inches whose lower-left corner is at (left, bottom). - - Args: - fig: The figure to add the axes to. - left: Distance from the figure's left edge to the axes, in inches. - bottom: Distance from the figure's bottom edge to the axes, in inches. - width: Width of the axes (the x-axis length), in inches. - height: Height of the axes (the y-axis length), in inches. - - Returns: - The new axes. - """ - fig_width, fig_height = fig.get_size_inches() - rect = (left / fig_width, bottom / fig_height, width / fig_width, height / fig_height) - return fig.add_axes(rect) - - -def legend( - fig: Figure, - ax: Axes, - x: float, - y: float, - loc: Literal["upper left", "upper right", "lower left", "lower right"] = "upper left", - **kwargs: Any, -) -> Legend: - """Add a legend for ax with its loc corner at (x, y) inches on the figure. - - Args: - fig: The figure that holds ax. - ax: The axes whose labelled artists the legend lists. - x: Distance from the figure's left edge to the legend's loc corner, in inches. - y: Distance from the figure's bottom edge to the legend's loc corner, in inches. - loc: Which corner of the legend sits at (x, y). - **kwargs: Passed on to ``ax.legend``, e.g. ``ncols``. - - Returns: - The new legend. - """ - return ax.legend( - loc=loc, - bbox_to_anchor=(x, y), - bbox_transform=fig.dpi_scale_trans, - borderaxespad=0, - **kwargs, - ) - - -def suptitle(fig: Figure, text: str, top: float = 0.1) -> Text: - """Center a figure title with its top edge top inches below the figure's top edge. - - Args: - fig: The figure to title. - text: The title. - top: Distance from the figure's top edge to the title's top edge, in inches. - - Returns: - The title text. - """ - return fig.suptitle(text, y=1 - top / fig.get_size_inches()[1], va="top") - - def save(fig: Figure, name: str) -> None: """Save fig uncropped as ``examples/.png`` (600 dpi), ``.svg`` and ``.pdf``. diff --git a/examples/palettes_demo.py b/examples/palettes_demo.py index 6486243..2e16adc 100644 --- a/examples/palettes_demo.py +++ b/examples/palettes_demo.py @@ -4,7 +4,7 @@ import matplotlib.pyplot as plt import numpy as np -from _common import STYLE, add_axes, legend, require_arial, save, suptitle +from _common import STYLE, require_arial, save from matplotlib.figure import Figure import mplplots.palettes as palettes @@ -17,7 +17,7 @@ REDS, get_colors, ) -from mplplots.utils import auto_ticks +from mplplots.utils import add_axes_inches, auto_ticks, legend_inches, suptitle_inches require_arial() plt.style.use(STYLE) @@ -43,7 +43,7 @@ def swatches( """ cell_width, cell_height = cell for row, (name, colors) in enumerate(reversed(list(rows.items()))): - ax = add_axes( + ax = add_axes_inches( fig, left, bottom + row * (cell_height + gap), len(colors) * cell_width, cell_height ) for i, c in enumerate(colors): @@ -61,12 +61,12 @@ def swatches( # --------------------------------------------------------------------------- x = np.linspace(0, 2 * np.pi, 100) fig = plt.figure(figsize=(4.5, 2.75)) -ax = add_axes(fig, 0.5, 0.4, 3, 2) +ax = add_axes_inches(fig, 0.5, 0.4, 3, 2) for i, color in enumerate(CUSTOM): ax.plot(x, np.sin(x + i * 0.3), color=color, label=f"Line {i}") auto_ticks(ax, left=0) ax.set_title("CUSTOM palette — multi-line plot") -legend(fig, ax, 3.6, 2.4) +legend_inches(ax, 3.6, 2.4) save(fig, "custom_multiline") # --------------------------------------------------------------------------- @@ -75,7 +75,7 @@ def swatches( families = {"BLUES": BLUES, "GREENS": GREENS, "REDS": REDS, "PURPLES": PURPLES, "ORANGES": ORANGES} fig = plt.figure(figsize=(4, 1.9)) swatches(fig, families, left=0.75, bottom=0.1, cell=(0.4, 0.2), gap=0.1) -suptitle(fig, "Colormap-derived families") +suptitle_inches(fig, "Colormap-derived families") save(fig, "color_families") # --------------------------------------------------------------------------- @@ -83,7 +83,7 @@ def swatches( # --------------------------------------------------------------------------- fig = plt.figure(figsize=(6, 1.8)) for i, cmap_name in enumerate(["coolwarm", "viridis", "YlGnBu"]): - ax = add_axes(fig, 0.4 + i * 2, 0.2, 1.5, 1.25) + ax = add_axes_inches(fig, 0.4 + i * 2, 0.2, 1.5, 1.25) colors = get_colors(cmap_name, 6, 0.15, 0.85) ax.bar(range(len(colors)), [3 + i * 0.5 for i in range(len(colors))], color=colors) ax.set_title(f'get_colors("{cmap_name}", 6)') @@ -130,7 +130,7 @@ def swatches( cell=(0.3, 0.15), gap=0.05, ) -suptitle(fig, "All 25 custom-style palettes") +suptitle_inches(fig, "All 25 custom-style palettes") save(fig, "all_palettes") # --------------------------------------------------------------------------- @@ -139,7 +139,7 @@ def swatches( rng = np.random.default_rng(42) fig = plt.figure(figsize=(5.5, 1.7)) for i, name in enumerate(["OCEAN", "ROSE", "FOREST"]): - ax = add_axes(fig, 0.25 + i * 1.75, 0.1, 1.5, 1.25) + ax = add_axes_inches(fig, 0.25 + i * 1.75, 0.1, 1.5, 1.25) pal = getattr(palettes, name) for j, c in enumerate(pal): xs = rng.normal(j, 0.3, 20) @@ -155,7 +155,7 @@ def swatches( # --------------------------------------------------------------------------- x = np.linspace(0, 4, 80) fig = plt.figure(figsize=(4.5, 2.5)) -ax = add_axes(fig, 0.5, 0.4, 3, 1.75) +ax = add_axes_inches(fig, 0.5, 0.4, 3, 1.75) spring = palettes.SPRING base = np.zeros_like(x) for i in range(6): @@ -164,14 +164,14 @@ def swatches( base += y auto_ticks(ax, left=0, right=4, bottom=0) ax.set_title("SPRING palette — stacked area chart") -legend(fig, ax, 3.6, 2.15) +legend_inches(ax, 3.6, 2.15) save(fig, "spring_area") # --------------------------------------------------------------------------- # 7. Pie chart with CANDY palette # --------------------------------------------------------------------------- fig = plt.figure(figsize=(2.5, 2.5)) -ax = add_axes(fig, 0.25, 0.1, 2, 2) +ax = add_axes_inches(fig, 0.25, 0.1, 2, 2) candy = palettes.CANDY sizes = [22, 18, 15, 13, 10, 8, 7, 4, 2, 1] ax.pie(sizes, colors=candy[:10], startangle=90, wedgeprops={"edgecolor": "white", "linewidth": 1.5}) @@ -182,7 +182,7 @@ def swatches( # 8. Horizontal bar chart with DUSK palette # --------------------------------------------------------------------------- fig = plt.figure(figsize=(3.5, 3)) -ax = add_axes(fig, 0.6, 0.4, 2.6, 2.25) +ax = add_axes_inches(fig, 0.6, 0.4, 2.6, 2.25) dusk = palettes.DUSK categories = [f"Item {chr(65 + i)}" for i in range(11)] values = [45, 38, 35, 30, 28, 24, 20, 18, 14, 10, 6] diff --git a/examples/styles_demo.py b/examples/styles_demo.py index bf86bc7..b31f291 100644 --- a/examples/styles_demo.py +++ b/examples/styles_demo.py @@ -2,12 +2,12 @@ import matplotlib.pyplot as plt import numpy as np -from _common import STYLE, add_axes, legend, require_arial, save +from _common import STYLE, require_arial, save from matplotlib import ticker import mplplots.palettes as palettes from mplplots.palettes import BLUES, REDS -from mplplots.utils import auto_ticks +from mplplots.utils import add_axes_inches, auto_ticks, legend_inches require_arial() @@ -28,21 +28,21 @@ plt.style.use(STYLE) fig = plt.figure(figsize=(3, 2.25)) -ax = add_axes(fig, 0.5, 0.4, 2.25, 1.5) +ax = add_axes_inches(fig, 0.5, 0.4, 2.25, 1.5) ax.plot(x, np.sin(x), color=BLUES[4], label="sin(x)") ax.plot(x, np.cos(x), color=REDS[4], label="cos(x)") auto_ticks(ax, left=0, right=10) ax.set_title("GraphPadPrism + auto_ticks") ax.set_xlabel("x") ax.set_ylabel("y") -legend(fig, ax, 2.75, 1.9, loc="upper right", ncols=2) +legend_inches(ax, 2.75, 1.9, loc="upper right", ncols=2) save(fig, "graphpadprism_style") # --------------------------------------------------------------------------- # 2. Bar chart with GraphPadPrism # --------------------------------------------------------------------------- fig = plt.figure(figsize=(2.75, 2.25)) -ax = add_axes(fig, 0.5, 0.4, 2, 1.5) +ax = add_axes_inches(fig, 0.5, 0.4, 2, 1.5) categories = ["A", "B", "C", "D", "E"] values = [23, 45, 12, 67, 34] ax.bar(categories, values, color=BLUES[:5]) @@ -56,7 +56,7 @@ # 3. Multi-line with GraphPadPrism + OCEAN palette # --------------------------------------------------------------------------- fig = plt.figure(figsize=(4, 2.25)) -ax = add_axes(fig, 0.5, 0.4, 2.5, 1.5) +ax = add_axes_inches(fig, 0.5, 0.4, 2.5, 1.5) ocean = palettes.OCEAN for i in range(6): ax.plot(x, np.sin(x + i * 0.4) * (1 - i * 0.1), color=ocean[i], label=f"Wave {i}") @@ -64,14 +64,14 @@ ax.set_xlabel("Time") ax.set_ylabel("Amplitude") ax.set_title("OCEAN palette + GraphPadPrism") -legend(fig, ax, 3.1, 1.9) +legend_inches(ax, 3.1, 1.9) save(fig, "graphpadprism_ocean") # --------------------------------------------------------------------------- # 4. Grouped bar chart with GraphPadPrism + AUTUMN palette # --------------------------------------------------------------------------- fig = plt.figure(figsize=(4, 2.25)) -ax = add_axes(fig, 0.5, 0.4, 2.5, 1.5) +ax = add_axes_inches(fig, 0.5, 0.4, 2.5, 1.5) autumn = palettes.AUTUMN groups = ["Q1", "Q2", "Q3", "Q4"] x_pos = np.arange(len(groups)) @@ -87,14 +87,14 @@ ax.set_xlim(x_pos[0] + width - 0.5, x_pos[-1] + width + 0.5) ax.set_ylabel("Value") ax.set_title("AUTUMN palette — grouped bar chart") -legend(fig, ax, 3.1, 1.9) +legend_inches(ax, 3.1, 1.9) save(fig, "graphpadprism_grouped_bar") # --------------------------------------------------------------------------- # 5. Scatter with error bars + GraphPadPrism + CORAL palette # --------------------------------------------------------------------------- fig = plt.figure(figsize=(4, 2.25)) -ax = add_axes(fig, 0.5, 0.4, 2.5, 1.5) +ax = add_axes_inches(fig, 0.5, 0.4, 2.5, 1.5) coral = palettes.CORAL rng = np.random.default_rng(7) for i in range(5): @@ -115,7 +115,7 @@ ax.set_xlabel("X measure") ax.set_ylabel("Y measure") ax.set_title("CORAL palette — error bars") -legend(fig, ax, 3.1, 1.9) +legend_inches(ax, 3.1, 1.9) save(fig, "graphpadprism_errorbar") print("All style examples saved to examples/") diff --git a/src/mplplots/utils.py b/src/mplplots/utils.py index 7cf98e6..0e11833 100644 --- a/src/mplplots/utils.py +++ b/src/mplplots/utils.py @@ -3,6 +3,7 @@ import math import os from collections.abc import Callable, MutableMapping +from typing import Any, Literal import matplotlib.font_manager as fm import matplotlib.text as mtext @@ -12,8 +13,11 @@ from matplotlib.axes import Axes from matplotlib.axis import Axis from matplotlib.category import StrCategoryConverter +from matplotlib.figure import Figure +from matplotlib.legend import Legend from matplotlib.mathtext import MathTextParser -from matplotlib.transforms import Transform +from matplotlib.text import Text +from matplotlib.transforms import Bbox, ScaledTranslation, Transform type StrPath = str | os.PathLike[str] @@ -68,6 +72,132 @@ def _clear_font_caches() -> None: default.clear() +# Where a legend's anchor point sits on the legend: a corner, the middle of an edge, or the center. +type LegendCorner = Literal[ + "upper left", + "upper center", + "upper right", + "center left", + "center", + "center right", + "lower left", + "lower center", + "lower right", +] + + +def add_axes_inches( + fig: Figure, left: float, bottom: float, width: float, height: float, **kwargs: Any +) -> Axes: + """Add axes whose position and axis lengths are given in inches, as in GraphPad Prism. + + Prism sets the length of each axis directly instead of deriving it from the figure + size and margins. Here ``width`` is the length of the x-axis and ``height`` the length + of the y-axis, and ``(left, bottom)`` is where they meet, measured from the figure's + lower-left corner. The axes keep this position and size when the figure is resized and + at any dpi, so a figure saved without cropping has exactly these dimensions. + + Args: + fig: The figure to add the axes to. + left: Distance from the figure's left edge to the y-axis, in inches. + bottom: Distance from the figure's bottom edge to the x-axis, in inches. + width: Length of the x-axis (the width of the axes), in inches. + height: Length of the y-axis (the height of the axes), in inches. + **kwargs: Passed on to ``fig.add_axes``, e.g. ``projection`` or ``sharex``. + + Returns: + The new axes. + + Raises: + ValueError: If ``width`` or ``height`` is not positive. + + Notes: + An axes locator keeps the position, so it overrides anything that moves the axes + later: ``ax.set_position``, ``tight_layout``, constrained layout, and the space + ``fig.colorbar(..., ax=ax)`` would take. For a colorbar, add its axes with + ``add_axes_inches`` and pass them as ``cax``. Axes with a fixed aspect ratio + (``ax.set_aspect("equal")``, pie charts) shrink to fit inside the box. + + Examples: + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure(figsize=(3, 2.25)) + >>> ax = add_axes_inches(fig, left=0.5, bottom=0.4, width=2.25, height=1.5) + """ + if not (width > 0 and height > 0): + raise ValueError(f"width and height must be positive, got {width} and {height}") + + def locate(_ax: object, _renderer: object) -> Bbox: + """Return the axes' box in figure coordinates for the figure's current size.""" + fig_width, fig_height = fig.get_size_inches() + return Bbox.from_bounds( + left / fig_width, bottom / fig_height, width / fig_width, height / fig_height + ) + + ax = fig.add_axes(locate(None, None).bounds, **kwargs) + ax.set_axes_locator(locate) + return ax + + +def legend_inches( + ax: Axes, x: float, y: float, loc: LegendCorner = "upper left", **kwargs: Any +) -> Legend: + """Add a legend for ax whose ``loc`` point is at (x, y) inches on the figure. + + ``loc`` names the point of the legend box that is placed at (x, y), measured from the + figure's lower-left corner: ``"upper left"`` puts the legend's upper-left corner there, + so the legend extends right and down from it. The legend stays at that point when the + figure is resized and at any dpi. + + Args: + ax: The axes whose labelled artists the legend lists. + x: Distance from the figure's left edge to the ``loc`` point, in inches. + y: Distance from the figure's bottom edge to the ``loc`` point, in inches. + loc: The corner, edge midpoint, or center of the legend box that sits at (x, y). + **kwargs: Passed on to ``ax.legend``, e.g. ``ncols`` or ``title``. + + Returns: + The new legend. + + Raises: + ValueError: If ``ax`` is not in a figure. + + Examples: + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure(figsize=(4, 2.25)) + >>> ax = add_axes_inches(fig, 0.5, 0.4, 2.5, 1.5) + >>> _ = ax.plot([0, 1], [0, 1], label="data") + >>> legend = legend_inches(ax, 3.1, 1.9) # to the right of the axes, top-aligned + """ + fig = ax.get_figure() + if fig is None: + raise ValueError("ax is not in a figure") + options: dict[str, Any] = {"borderaxespad": 0, **kwargs} + return ax.legend(loc=loc, bbox_to_anchor=(x, y), bbox_transform=fig.dpi_scale_trans, **options) + + +def suptitle_inches(fig: Figure, t: str, top: float = 0.1, **kwargs: Any) -> Text: + """Add a centered figure title whose top edge is ``top`` inches below the figure's top. + + The title stays that far below the top edge when the figure is resized and at any dpi. + + Args: + fig: The figure to title. + t: The title text. + top: Distance from the figure's top edge to the title's top edge, in inches. + **kwargs: Passed on to ``fig.suptitle``, e.g. ``color``. + + Returns: + The title. + + Examples: + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure(figsize=(4, 2)) + >>> title = suptitle_inches(fig, "All palettes") + """ + transform = fig.transFigure + ScaledTranslation(0, -top, fig.dpi_scale_trans) + return fig.suptitle(t, x=0.5, y=1, va="top", transform=transform, **kwargs) + + def auto_ticks( ax: Axes, *, diff --git a/tests/test_utils.py b/tests/test_utils.py index 9ed0512..25bac4c 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -2,6 +2,7 @@ from __future__ import annotations +import io import uuid from collections.abc import Callable, Iterator from pathlib import Path @@ -16,12 +17,23 @@ from fontTools.ttLib import TTFont from matplotlib import ticker from matplotlib.font_manager import FontProperties +from matplotlib.patches import Rectangle from matplotlib.text import Text import mplplots -from mplplots.utils import _clear_font_caches, add_custom_fonts, auto_ticks +from mplplots.utils import ( + LegendCorner, + _clear_font_caches, + add_axes_inches, + add_custom_fonts, + auto_ticks, + legend_inches, + suptitle_inches, +) if TYPE_CHECKING: + from matplotlib.artist import Artist + from matplotlib.figure import Figure from matplotlib.typing import RcKeyType # Matplotlib 3.10+ STYLE_PATH = str(mplplots.STYLE_PATH) @@ -311,6 +323,92 @@ def test_fixed_whole_number_limit_always_on_a_tick(self) -> None: plt.close(fig) +def _inches(fig: Figure, artist: Artist) -> tuple[float, float, float, float]: + """Return an artist's drawn (x0, y0, x1, y1) in inches from the figure's lower-left corner.""" + fig.canvas.draw() + x0, y0, x1, y1 = np.asarray(artist.get_window_extent().extents) / fig.dpi + return float(x0), float(y0), float(x1), float(y1) + + +# One pixel at the default 100 dpi; text extents are rounded to whole pixels. +PIXEL = 0.01 + + +class TestInchLayout: + @pytest.mark.parametrize("style", ["default", STYLE_PATH]) + def test_add_axes_inches_sets_position_and_axis_lengths(self, style: str) -> None: + with plt.style.context(style): + fig = plt.figure(figsize=(3, 2.25)) + ax = add_axes_inches(fig, 0.5, 0.4, 2.25, 1.5) + assert _inches(fig, ax) == pytest.approx((0.5, 0.4, 2.75, 1.9)) + + def test_axis_lengths_stay_when_the_figure_is_resized(self) -> None: + fig = plt.figure(figsize=(3, 2.25)) + ax = add_axes_inches(fig, 0.5, 0.4, 2.25, 1.5) + fig.set_size_inches(5, 4) + assert _inches(fig, ax) == pytest.approx((0.5, 0.4, 2.75, 1.9)) + + def test_saved_file_keeps_axis_lengths(self) -> None: + with plt.style.context(STYLE_PATH): + fig = plt.figure(figsize=(2, 1.5)) + ax = add_axes_inches(fig, 0.5, 0.25, 1.25, 1) + ax.set_axis_off() + # Fill exactly the axes box, so its pixels show where the axes ended up. + ax.add_patch(Rectangle((0, 0), 1, 1, transform=ax.transAxes, color="black", lw=0)) + buffer = io.BytesIO() + fig.savefig(buffer, format="png", dpi=100) + buffer.seek(0) + image = plt.imread(buffer) + assert image.shape[:2] == (150, 200) + black = np.argwhere((image[..., 3] > 0.5) & (image[..., :3].sum(axis=-1) < 0.5)) + (top, left), (bottom, right) = black.min(axis=0), black.max(axis=0) + # Rows count from the top of the 150 px image; the axes span 50-175 px x 25-125 px. + assert (left, right + 1, 150 - (bottom + 1), 150 - top) == (50, 175, 25, 125) + + @pytest.mark.parametrize(("width", "height"), [(0, 1), (1, -0.5)]) + def test_add_axes_inches_rejects_empty_axes(self, width: float, height: float) -> None: + fig = plt.figure(figsize=(3, 2)) + with pytest.raises(ValueError, match="positive"): + add_axes_inches(fig, 0.5, 0.5, width, height) + + @pytest.mark.parametrize( + ("loc", "corner"), + [("upper left", (0, 3)), ("lower right", (2, 1)), ("upper right", (2, 3))], + ) + def test_legend_inches_puts_its_corner_on_the_point( + self, loc: LegendCorner, corner: tuple[int, int] + ) -> None: + fig = plt.figure(figsize=(4, 2.25)) + ax = add_axes_inches(fig, 0.5, 0.4, 2.5, 1.5) + ax.plot([0, 1], [0, 1], label="data") + legend = legend_inches(ax, 3.1, 1.9, loc=loc) + for size in ((4, 2.25), (6, 3)): + fig.set_size_inches(*size) + extents = _inches(fig, legend) + assert (extents[corner[0]], extents[corner[1]]) == pytest.approx((3.1, 1.9)) + + def test_legend_inches_passes_options_on(self) -> None: + fig = plt.figure(figsize=(4, 2)) + ax = add_axes_inches(fig, 0.5, 0.4, 2.5, 1.25) + ax.plot([0, 1], [0, 1], label="a") + ax.plot([0, 1], [1, 0], label="b") + legend = legend_inches(ax, 2.75, 1.9, loc="upper right", ncols=2, title="Series") + assert legend.get_title().get_text() == "Series" + # Two columns: both entries share one row. + first, second = (_inches(fig, text) for text in legend.get_texts()) + assert first[1] == pytest.approx(second[1]) + assert first[2] < second[0] + + def test_suptitle_inches_sets_the_top_edge(self) -> None: + fig = plt.figure(figsize=(4, 2)) + title = suptitle_inches(fig, "Figure title", top=0.1) + for width, height in ((4, 2), (5, 3)): + fig.set_size_inches(width, height) + x0, _, x1, y1 = _inches(fig, title) + assert y1 == pytest.approx(height - 0.1, abs=PIXEL) + assert (x0 + x1) / 2 == pytest.approx(width / 2, abs=PIXEL) + + @pytest.fixture def make_font(tmp_path: Path) -> Iterator[FontFactory]: """Copy a font bundled with Matplotlib under a new family name.