diff --git a/CHANGELOG.md b/CHANGELOG.md index f7e4155..7f1f86b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,19 @@ to [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Added + +- `flux_diagram` draws a box model's budget: a grid of boxes coloured on a diverging + scale, with sign-aware arrows ∝ √|value| for vertical, horizontal, lateral and ground + fluxes, an optional split of the vertical flux, and per-box notes; `flux_legend` + explains it, and `data.box_budget` gives a closed example budget. +- `diagram_box` and `diagram_arrow`, the labelled box and the point-width arrow + `flux_diagram` is built from, for flowcharts and schematics. +- `profile(bands=...)` shades a range, such as an interquartile range, behind a + profile in its colour. +- `legend_handle` builds a line, marker or band legend entry in the `role_style` + vocabulary. + ## [1.0.0] - 2026-11-07 First public release. diff --git a/docs/api.md b/docs/api.md index 7c220f9..a78598a 100644 --- a/docs/api.md +++ b/docs/api.md @@ -84,6 +84,10 @@ and the [Gallery](gallery.md) for runnable examples. ::: nicefigs.tables +## `nicefigs.diagrams` + +::: nicefigs.diagrams + ## `nicefigs.sections` ::: nicefigs.sections diff --git a/docs/assets/guide/plots-flowchart.png b/docs/assets/guide/plots-flowchart.png new file mode 100644 index 0000000..a6b5c1f Binary files /dev/null and b/docs/assets/guide/plots-flowchart.png differ diff --git a/docs/assets/guide/plots-flux-diagram-panels.png b/docs/assets/guide/plots-flux-diagram-panels.png new file mode 100644 index 0000000..6368f92 Binary files /dev/null and b/docs/assets/guide/plots-flux-diagram-panels.png differ diff --git a/docs/assets/guide/plots-flux-diagram.png b/docs/assets/guide/plots-flux-diagram.png new file mode 100644 index 0000000..0ce511f Binary files /dev/null and b/docs/assets/guide/plots-flux-diagram.png differ diff --git a/docs/assets/guide/plots-profile-band.png b/docs/assets/guide/plots-profile-band.png new file mode 100644 index 0000000..ac68aa9 Binary files /dev/null and b/docs/assets/guide/plots-profile-band.png differ diff --git a/docs/gallery.md b/docs/gallery.md index 355ae3b..21af923 100644 --- a/docs/gallery.md +++ b/docs/gallery.md @@ -319,6 +319,21 @@ horizontal bar with the colormap's extend triangles. --8<-- "examples/30_scorecard_diverging.py" ``` +## Budgets + +### 33 — Flux diagram {#flux-diagram} + +[`nicefigs.flux_diagram`][nicefigs.flux_diagram] draws a box model's budget: boxes +coloured by their storage change, lateral inflow on both sides of each box, upward fluxes +between the layers with their convective and mixing parts, and the ground flux, every +arrow ∝ √|value| wide. [`flux_legend`][nicefigs.flux_legend] explains the encoding. + +![Flux diagram](gallery/33_flux_diagram.png) + +```python +--8<-- "examples/33_flux_diagram.py" +``` + ## Vertical structure ### 22 — Cross-section / curtain {#cross-section} diff --git a/docs/gallery/33_flux_diagram.png b/docs/gallery/33_flux_diagram.png new file mode 100644 index 0000000..31f7d3f Binary files /dev/null and b/docs/gallery/33_flux_diagram.png differ diff --git a/docs/guide/plots.md b/docs/guide/plots.md index 672c711..3105265 100644 --- a/docs/guide/plots.md +++ b/docs/guide/plots.md @@ -416,6 +416,107 @@ nf.stacked_bars( ![Grouped and stacked bars](../assets/guide/plots-bars.png) +## Box-and-arrow diagrams + +[`flux_diagram()`][nicefigs.flux_diagram] draws the budget of a box model: a grid of +boxes, rows stacked bottom first and columns side by side, each coloured and labelled by +its value on a diverging scale, with an arrow for every flux between them. Arrows point +the way the flux goes and are ∝ √|value| wide, in points, on one scale per kind of flux. + +```python +import nicefigs as nf +from nicefigs import data + +nf.set_theme("paper") +b = data.box_budget(n_rows=2, n_cols=3) +ax, diagram = nf.flux_diagram( + b["storage"], + vertical=b["vertical"], + ground=b["ground"], + row_labels=["Lower", "Upper"], + col_labels=["West", "Centre", "East"], + width="full", +) +print(len(diagram.of_kind("vertical")), "vertical and", len(diagram.of_kind("ground")), "ground arrows") +``` + +```text +3 vertical and 3 ground arrows +``` + +![Flux diagram](../assets/guide/plots-flux-diagram.png) + +`vertical` flows from row `k` up into row `k + 1`, `ground` from the hatched ground into +the bottom row, and `horizontal` from column `j` into column `j + 1`; a negative value +reverses the arrow. `lateral` is a net inflow through a box's sides, such as a +convergence: it draws an arrow on both sides, in when positive, and prints the value +inside the box. `parts` splits each vertical flux into named shares printed beside it. + +Box `(k, j)` is centred at `x = j + 0.5`, `y = k` in data coordinates, so further +annotation goes straight onto `ax`. The returned +[`FluxDiagram`][nicefigs.FluxDiagram] holds the colour `mappable` for +[`colorbar()`][nicefigs.colorbar], and [`flux_legend()`][nicefigs.flux_legend] explains +the colours: + +```python +import nicefigs as nf +from nicefigs import data + +nf.set_theme("paper") +b = data.box_budget() +fig, (top, bottom) = nf.subplots(2, 1, width="double", aspect=0.75, height_ratios=[3, 1], hspace=0.15) +reference = {"lateral": 30.0, "ground": 2.0} +norm = nf.diverging_norm(-0.6, 0.6) +_, diagram = nf.flux_diagram( + b["storage"], ax=top, lateral=b["lateral"], vertical=b["vertical"], ground=b["ground"], + parts=b["parts"], row_labels=b["row_labels"], norm=norm, reference=reference, +) +nf.flux_diagram( + b["storage"].sum(0, keepdims=True), ax=bottom, lateral=b["lateral"].sum(0, keepdims=True), + ground=b["ground"], row_labels=["Column"], col_labels=b["col_labels"], norm=norm, reference=reference, +) +nf.colorbar(diagram.mappable, bottom, location="bottom", pad=0.03, shrink=0.5, label="storage change") +nf.flux_legend( + diagram, + {"box": "storage change", "lateral": "lateral inflow", "vertical": "upward flux", "ground": "ground flux"}, + parts={"c": "convective", "m": "mixing"}, + target=fig, loc="upper center", bbox_to_anchor=(0.5, 0.02), ncol=3, +) +``` + +![Two flux diagrams sharing colours and widths](../assets/guide/plots-flux-diagram-panels.png) + +Passing one `norm` and one `reference` to both panels puts their colours and arrow widths +on the same scale; by default each diagram scales to its own largest value. + +[`diagram_box()`][nicefigs.diagram_box] and [`diagram_arrow()`][nicefigs.diagram_arrow] +are the pieces `flux_diagram` is built from; place them anywhere for a flowchart or a +schematic. Positions are data coordinates and arrow widths are points, so the drawing +keeps its shape whatever the axes' aspect: + +```python +import nicefigs as nf + +nf.set_theme("paper") +fig, ax = nf.subplots(width="full", aspect=0.3) +ax.set_xlim(0, 4) +ax.set_ylim(-0.5, 0.75) +ax.set_axis_off() +steps = ["meteorology", "transport", "observation\noperator", "scores"] +for i, step in enumerate(steps): + nf.diagram_box(ax, (i + 0.5, 0), 0.7, 0.4, text=step, facecolor="#dbe6f1") + if i: + nf.diagram_arrow(ax, (i - 0.15, 0), (i + 0.15, 0), width=1.2) +nf.diagram_arrow( + ax, (3.5, 0.22), (1.5, 0.22), width=0.8, connectionstyle="arc3,rad=0.25", + label="tune", label_offset=(0, 12), +) +``` + +![A flowchart](../assets/guide/plots-flowchart.png) + +A `connectionstyle` curves an arrow; `label` and `label_offset` place text at its midpoint. + ## Vertical sections and profiles [`cross_section()`][nicefigs.cross_section] draws a field over a horizontal @@ -470,6 +571,38 @@ ax = nf.profile( ![Vertical profiles](../assets/guide/plots-profile.png) +`bands={name: (low, high)}` shades a range behind the profile of the same name, in its +colour, e.g. the interquartile range of observations around their median. Bands add no +legend entry; [`legend_handle()`][nicefigs.legend_handle] makes one: + +```python +import nicefigs as nf +from nicefigs import data + +nf.set_theme("paper") +vp = data.vertical_profiles(names=["observed"]) +median = vp["profiles"]["observed"] +ax = nf.profile( + {"observed": median}, + vp["levels"], + bands={"observed": (median - 1.5, median + 1.0)}, + colors={"observed": "#4477AA"}, + xlabel="CO₂", + xunits="ppmv", + ylabel="pressure", + yunits="hPa", + width="half", +) +ax.legend( + handles=[ + nf.legend_handle("observed median", "both", color="#4477AA", marker="o", markersize=3), + nf.legend_handle("observed 25–75 %", "band", color="#4477AA", alpha=0.25), + ] +) +``` + +![A profile with its interquartile band](../assets/guide/plots-profile-band.png) + ## Hovmöller diagrams [`hovmoller()`][nicefigs.hovmoller] draws a field over time and one spatial diff --git a/docs/guide/styling.md b/docs/guide/styling.md index b8f1103..7e6198e 100644 --- a/docs/guide/styling.md +++ b/docs/guide/styling.md @@ -169,6 +169,10 @@ a variant of a method the open marker (`filled=False`). needed for graphics. Label null curves directly; the grey never carries meaning alone. +[`legend_handle()`][nicefigs.legend_handle] builds a legend entry in the same +vocabulary, for an entry no plotted artist carries, e.g. +`nf.legend_handle("seed range", "band", **nf.role_style("null", "band"))`. + Map your methods to roles once, e.g. `{"unet": "primary", "persistence": "contrast"}`, and every figure inherits the same colours. diff --git a/examples/33_flux_diagram.py b/examples/33_flux_diagram.py new file mode 100644 index 0000000..6212699 --- /dev/null +++ b/examples/33_flux_diagram.py @@ -0,0 +1,45 @@ +"""Flux diagram: a closed three-layer box budget with lateral, vertical and ground fluxes.""" + +import nicefigs as nf +from nicefigs import data + + +def make(): + nf.set_theme("paper") + b = data.box_budget() + fig, ax = nf.subplots(width="double", aspect=0.5) + ax, diagram = nf.flux_diagram( + b["storage"], + ax=ax, + lateral=b["lateral"], + vertical=b["vertical"], + ground=b["ground"], + parts=b["parts"], + row_labels=b["row_labels"], + col_labels=b["col_labels"], + col_title="Region", + ) + nf.colorbar( + diagram.mappable, ax, location="bottom", pad=0.04, shrink=0.5, label="storage change [Tg yr⁻¹]" + ) + nf.flux_legend( + diagram, + { + "box": "box colour, upper number: storage change", + "lateral": "lateral inflow (arrows in > 0)", + "vertical": "upward flux (up > 0)", + "ground": "ground flux (up > 0)", + }, + parts={"c": "convective part", "m": "mixing part"}, + loc="upper center", + bbox_to_anchor=(0.5, -0.2), + ncol=2, + ) + return fig + + +if __name__ == "__main__": + import matplotlib + + matplotlib.use("Agg") + nf.save(make(), "33_flux_diagram", formats=("png", "pdf")) diff --git a/src/nicefigs/__init__.py b/src/nicefigs/__init__.py index 11f456a..54ee7f1 100644 --- a/src/nicefigs/__init__.py +++ b/src/nicefigs/__init__.py @@ -30,6 +30,15 @@ hsv_legend, ) from .comparison import model_comparison +from .diagrams import ( + FLUX_COLORS, + FluxArrow, + FluxDiagram, + diagram_arrow, + diagram_box, + flux_diagram, + flux_legend, +) from .figure import TextIssue, check_text_overlaps, figure, figure_size, save, subplots from .hovmoller import hovmoller, hovmoller_panels from .images import heatmap, image, image_grid, overlay_grid, pca_rgb @@ -59,6 +68,7 @@ cmap, diverging_norm, elevation_cmap, + legend_handle, qualitative, robust_limits, role_color, @@ -172,6 +182,7 @@ "Role", "role_color", "role_style", + "legend_handle", # artist palettes "artist_palette", "artist_cmap", @@ -221,6 +232,13 @@ "stacked_bars", "scorecard", "skill_gap", + "diagram_box", + "diagram_arrow", + "flux_diagram", + "flux_legend", + "FluxDiagram", + "FluxArrow", + "FLUX_COLORS", "DIRECTIONS", "cross_section", "cross_section_panels", diff --git a/src/nicefigs/data.py b/src/nicefigs/data.py index e43ae0c..0805211 100644 --- a/src/nicefigs/data.py +++ b/src/nicefigs/data.py @@ -579,3 +579,50 @@ def eigen_spectra( x -= x.mean(axis=0) out[nm] = np.linalg.eigvalsh(x.T @ x / (n_samples - 1))[::-1] return out + + +def box_budget( + *, + seed: int = 41, + n_rows: int = 3, + n_cols: int = 5, +) -> dict[str, Any]: + """A closed budget of a grid of boxes, for :func:`nicefigs.flux_diagram`. + + Rows are stacked layers, bottom first, and columns sit side by side. Every box closes: + its storage change is its lateral inflow plus the vertical flux through its bottom + minus the one through its top, plus the ground flux for the bottom row. + + Args: + seed: Random seed. + n_rows: Number of layers. + n_cols: Number of columns. + + Returns: + ``storage`` and ``lateral`` of shape ``(n_rows, n_cols)``; ``vertical``, upward + through the top of every row but the last, of shape ``(n_rows - 1, n_cols)``; + ``ground``, upward into the bottom row, of shape ``(n_cols,)``; ``parts``, the + mixing (``"m"``) and convective (``"c"``) shares of ``vertical``; and + ``row_labels`` and ``col_labels``. + """ + rng = _rng(seed) + x = np.linspace(-1.0, 1.0, n_cols) + storage = np.round(rng.normal(0.0, 0.4, (n_rows, n_cols)), 2) + shape = np.sin(np.pi * (x[None, :] + rng.uniform(0.2, 0.6, (n_rows - 1, 1)))) + vertical = np.round(30 * shape * rng.uniform(0.3, 1.0, (n_rows - 1, 1)), 1) + ground = np.round(rng.normal(0.0, 2.0, n_cols), 2) + up_in = np.vstack([ground[None, :], vertical]) + up_out = np.vstack([vertical, np.zeros((1, n_cols))]) + lateral = storage - up_in + up_out + convective = np.round(vertical * rng.uniform(0.0, 0.05, vertical.shape), 2) + mixing = np.round(vertical * rng.uniform(0.0, 0.02, vertical.shape), 2) + return { + "storage": storage, + "lateral": lateral, + "vertical": vertical, + "ground": ground, + "parts": {"c": convective, "m": mixing}, + "row_labels": ["Boundary layer", "Free troposphere", "Stratosphere"][:n_rows] + + [f"Layer {k + 1}" for k in range(3, n_rows)], + "col_labels": [f"Column {j + 1}" for j in range(n_cols)], + } diff --git a/src/nicefigs/diagrams.py b/src/nicefigs/diagrams.py new file mode 100644 index 0000000..a7cf7b2 --- /dev/null +++ b/src/nicefigs/diagrams.py @@ -0,0 +1,591 @@ +"""Box-and-arrow diagrams: flowcharts, schematics and box-model budgets. + +:func:`diagram_box` and :func:`diagram_arrow` are the building blocks: a labelled, rounded +box and a filled arrow whose width is set in points, both placed in data coordinates, for +flowcharts and schematics of any layout. :func:`flux_diagram` composes them into a box +model's budget: boxes in rows (stacked layers, bottom first) and columns (side by side), +coloured by a value on a diverging scale, with every flux an arrow whose direction follows +its sign and whose width grows with the square root of its magnitude. :func:`flux_legend` +explains the encoding. + +Example:: + + import nicefigs as nf + from nicefigs import data + + b = data.box_budget() + ax, diagram = nf.flux_diagram(b["storage"], vertical=b["vertical"], ground=b["ground"]) + nf.flux_legend(diagram, {"box": "storage change", "vertical": "upward flux"}) +""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any + +import matplotlib as mpl +import matplotlib.colors as mcolors +import numpy as np +from matplotlib.cm import ScalarMappable +from matplotlib.patches import ArrowStyle, FancyArrowPatch, FancyBboxPatch, Rectangle + +from .palettes import cmap as resolve_cmap +from .palettes import diverging_norm, legend_handle +from .style import COLORS, get_theme + +if TYPE_CHECKING: + from matplotlib.axes import Axes + from matplotlib.figure import Figure + from matplotlib.legend import Legend + from numpy.typing import ArrayLike + +__all__ = [ + "FLUX_COLORS", + "FluxArrow", + "FluxDiagram", + "diagram_arrow", + "diagram_box", + "flux_diagram", + "flux_legend", +] + +#: Default colour of each kind of flux; ``"box"`` is not a flux and takes the colormap. +FLUX_COLORS: dict[str, str] = { + "vertical": "#b2182b", + "horizontal": COLORS["primary"], + "lateral": COLORS["primary"], + "ground": "#9a9a9a", +} + +#: Kinds of flux, in the order a legend lists them. +_KINDS = ("lateral", "horizontal", "vertical", "ground") + +# Geometry in data units: column ``j`` is centred on ``x = j + 0.5`` and row ``k`` on ``y = k``. +_GAP = 0.02 # between an arrow's end and the box edge +_LATERAL_SPAN = 0.16 # length of a lateral arrow +_GROUND_Y = -0.66 # the ground line, below row 0 +_LABEL_DROP = 0.2 # from the ground line (or the bottom boxes) down to the column labels +_MIN_WIDTH = 0.4 # pt, the width of a zero flux + + +@dataclass(frozen=True) +class FluxArrow: + """One drawn flux. + + Attributes: + kind: ``"vertical"``, ``"horizontal"``, ``"lateral"`` or ``"ground"``. + index: Index of the value in its input array; a lateral flux draws two arrows with + the same index. + value: The value drawn. + tail: ``(x, y)`` of the arrow's tail, in data coordinates. + head: ``(x, y)`` of its tip, in data coordinates. + width: Shaft width (pt). + artist: The patch drawn. + """ + + kind: str + index: tuple[int, ...] + value: float + tail: tuple[float, float] + head: tuple[float, float] + width: float + artist: FancyArrowPatch + + +@dataclass +class FluxDiagram: + """What :func:`flux_diagram` drew, for a colorbar, a legend or tests. + + Attributes: + ax: The axes drawn on. + mappable: Box colormap and norm, for :func:`nicefigs.colorbar`. + boxes: ``(n_rows, n_cols)`` object array of the box patches. + arrows: Every flux arrow, in drawing order. + colors: Colour of each kind of flux. + part_colors: Colour of each part of the vertical flux. + """ + + ax: Axes + mappable: ScalarMappable + boxes: np.ndarray + arrows: list[FluxArrow] = field(default_factory=list) + colors: dict[str, str] = field(default_factory=dict) + part_colors: dict[str, str] = field(default_factory=dict) + + def of_kind(self, kind: str) -> list[FluxArrow]: + """The arrows of one kind of flux.""" + return [a for a in self.arrows if a.kind == kind] + + +def _fmt(value: float) -> str: + """Three significant digits, at least two decimals below 1, with a true minus sign.""" + if not np.isfinite(value) or value == 0.0: + return "0.00" + digits = max(0, min(2, 2 - int(np.floor(np.log10(abs(value)))))) + text = f"{value:.{digits}f}" + return text.removeprefix("-") if float(text) == 0.0 else text.replace("-", "−") + + +def _as_grid(values: ArrayLike | None, shape: tuple[int, ...], name: str) -> np.ndarray | None: + if values is None: + return None + a = np.asarray(values, dtype=float) + if a.shape != shape: + raise ValueError(f"{name} must have shape {shape}, got {a.shape}") + return a + + +def _reference(values: np.ndarray | None, given: float | None) -> float: + if given is not None: + return float(given) + if values is None or not np.isfinite(values).any(): + return 0.0 + return float(np.nanmax(np.abs(values))) + + +def _ink(fill: Any) -> str: + """Dark or white text, whichever reads on ``fill``.""" + r, g, b, _ = mcolors.to_rgba(fill) + return "white" if 0.299 * r + 0.587 * g + 0.114 * b < 0.45 else "#1a1a1a" + + +def diagram_box( + ax: Axes, + xy: tuple[float, float], + width: float, + height: float, + *, + text: str = "", + facecolor: Any = "white", + edgecolor: Any = "0.55", + linewidth: float = 0.5, + rounding: float = 0.05, + textcolor: Any = None, + zorder: float = 2.0, + **text_kw: Any, +) -> FancyBboxPatch: + """Draw a rounded box centred on ``xy``, optionally with centred text. + + Args: + ax: Axes to draw on. + xy: Centre of the box, in data coordinates. + width: Box width, in data units. + height: Box height, in data units. + text: Text centred in the box; multi-line text is fine. + facecolor: Fill colour; ``"none"`` for an outline. + edgecolor: Outline colour. + linewidth: Outline width (pt). + rounding: Corner radius, in data units; 0 gives square corners. + textcolor: Text colour; by default dark or white, whichever reads on ``facecolor``. + zorder: Drawing order of the box; its text draws above. + **text_kw: Forwarded to :meth:`~matplotlib.axes.Axes.text`, e.g. ``fontsize`` or + ``fontweight``. + + Returns: + The box patch. + """ + x, y = xy + box = FancyBboxPatch( + (x - width / 2, y - height / 2), + width, + height, + boxstyle=f"round,pad=0,rounding_size={rounding}", + facecolor=facecolor, + edgecolor=edgecolor, + linewidth=linewidth, + zorder=zorder, + gid="box", + ) + ax.add_patch(box) + if text: + if textcolor is None: + textcolor = mpl.rcParams["text.color"] if facecolor == "none" else _ink(facecolor) + ax.text(x, y, text, ha="center", va="center", color=textcolor, zorder=zorder + 2, **text_kw) + return box + + +def diagram_arrow( + ax: Axes, + tail: tuple[float, float], + head: tuple[float, float], + *, + width: float = 1.0, + color: Any = None, + head_width: float | None = None, + head_length: float | None = None, + label: str = "", + label_offset: tuple[float, float] = (0.0, 0.0), + zorder: float = 3.0, + label_kw: Mapping[str, Any] | None = None, + **kwargs: Any, +) -> FancyArrowPatch: + """Draw a filled arrow from ``tail`` to ``head``, its shaft ``width`` points wide. + + Widths are physical, so arrows keep their shape on axes of any aspect. + + Args: + ax: Axes to draw on. + tail: Start, in data coordinates. + head: Tip, in data coordinates. + width: Shaft width (pt). + color: Fill colour; the text colour by default. + head_width: Head width (pt); by default ``max(3, 2.4 * width)``. + head_length: Head length (pt); by default ``max(2.6, 1.5 * width)``. + label: Text at the arrow's midpoint. + label_offset: ``(dx, dy)`` of the label from the midpoint (pt). + zorder: Drawing order; the label draws above. + label_kw: Forwarded to :meth:`~matplotlib.axes.Axes.annotate` for the label, + e.g. ``ha``, ``fontsize`` or ``color``. + **kwargs: Forwarded to :class:`~matplotlib.patches.FancyArrowPatch`, e.g. + ``connectionstyle="arc3,rad=0.2"`` for a curved arrow or ``gid``. + + Returns: + The arrow patch. + """ + hw = max(3.0, 2.4 * width) if head_width is None else head_width + hl = max(2.6, 1.5 * width) if head_length is None else head_length + color = mpl.rcParams["text.color"] if color is None else color + patch = FancyArrowPatch( + tail, + head, + arrowstyle=ArrowStyle.Simple(head_length=hl, head_width=hw, tail_width=width), + mutation_scale=1.0, + shrinkA=0.0, + shrinkB=0.0, + color=color, + linewidth=0.0, + zorder=zorder, + **kwargs, + ) + ax.add_patch(patch) + if label: + mid = ((tail[0] + head[0]) / 2, (tail[1] + head[1]) / 2) + kw = {"ha": "center", "va": "center", "zorder": zorder + 1, **(label_kw or {})} + ax.annotate(label, mid, xytext=label_offset, textcoords="offset points", **kw) + return patch + + +def flux_diagram( + values: ArrayLike, + *, + ax: Axes | None = None, + vertical: ArrayLike | None = None, + horizontal: ArrayLike | None = None, + lateral: ArrayLike | None = None, + ground: ArrayLike | None = None, + parts: Mapping[str, ArrayLike] | None = None, + notes: ArrayLike | None = None, + row_labels: Sequence[str] | None = None, + col_labels: Sequence[str] | None = None, + ground_label: str = "Surface", + col_title: str = "", + cmap: str | mcolors.Colormap = "BrBG_r", + norm: mcolors.Normalize | None = None, + colors: Mapping[str, str] | None = None, + part_colors: Mapping[str, str] | None = None, + reference: Mapping[str, float] | None = None, + max_width: float = 4.5, + box_size: tuple[float, float] = (0.48, 0.44), + fmt: Callable[[float], str] = _fmt, + width: float | str = "double", +) -> tuple[Axes, FluxDiagram]: + """Draw a grid of boxes coloured by ``values``, with an arrow for every flux between them. + + Row ``k`` of every array is a layer, the first at the bottom, and column ``j`` sits at + ``x = j + 0.5``, row ``k`` at ``y = k`` in data coordinates, so callers can annotate any + box. Each box is filled from ``cmap`` by its value, which it prints in bold. Every flux is + an arrow pointing the way the flux goes and labelled with its value; its width is + ∝ √|value|, the ``reference`` value of its kind drawn ``max_width`` points wide, so widths + are physical and independent of the axes' aspect. Non-finite fluxes are not drawn. + + Args: + values: Box values, shape ``(n_rows, n_cols)``, e.g. each box's storage change. + ax: Axes to draw on; a new figure is created if ``None``. The axes are turned off. + vertical: Flux from row ``k`` up into row ``k + 1``, shape ``(n_rows - 1, n_cols)``; + positive points up. + horizontal: Flux from column ``j`` into column ``j + 1``, shape + ``(n_rows, n_cols - 1)``; positive points right. + lateral: Net inflow through a box's sides, shape ``(n_rows, n_cols)``, e.g. a + convergence. Drawn on both sides of the box, pointing in when positive and out + when negative, and printed inside the box under its value. Excludes + ``horizontal``, which draws in the same gaps. + ground: Flux from the ground up into row 0, shape ``(n_cols,)``; positive points up. + Draws a hatched ground line under every column. + parts: ``{key: values}`` splitting ``vertical``, each of its shape; printed left of + every vertical arrow as ``"key value"``, one line each. + notes: Text per box, shape ``(n_rows, n_cols)``, printed small under its lower left + corner; empty strings print nothing. + row_labels: One label per row, bottom first, left of the boxes. + col_labels: One label per column, under the ground (or the bottom boxes). + ground_label: Label of the ground line, left of it. + col_title: Label of the column labels, left of them. + cmap: Box colormap; a diverging one whose ends are not the arrow hues. + norm: Box norm; by default centred on 0 and symmetric about the largest ``|values|``. + Pass one to share colours between diagrams. + colors: Colour per kind of flux, overriding :data:`FLUX_COLORS`. + part_colors: Colour per key of ``parts``; ``Dark2`` in order by default. + reference: Value drawn ``max_width`` wide, per kind of flux; by default the largest + ``|value|`` of that kind in this call. Pass it to share widths between diagrams. + max_width: Shaft width (pt) of the reference value. + box_size: Box ``(width, height)`` in data units; one column is one unit wide and one + row one unit tall. + fmt: Formats every printed number; three significant digits by default. + width: Figure width (preset name or inches) when ``ax`` is ``None``. + + Returns: + ``(ax, diagram)``; ``diagram`` holds the colour mappable, the boxes and the arrows. + + Raises: + ValueError: An array has the wrong shape, or both ``lateral`` and ``horizontal`` + are given. + """ + th = get_theme() + values = np.asarray(values, dtype=float) + if values.ndim != 2: + raise ValueError(f"values must have shape (n_rows, n_cols), got {values.shape}") + n_rows, n_cols = values.shape + vertical = _as_grid(vertical, (n_rows - 1, n_cols), "vertical") + horizontal = _as_grid(horizontal, (n_rows, n_cols - 1), "horizontal") + lateral = _as_grid(lateral, (n_rows, n_cols), "lateral") + ground = _as_grid(ground, (n_cols,), "ground") + if lateral is not None and horizontal is not None: + raise ValueError("lateral and horizontal both draw between the columns; give one") + parts = {k: _as_grid(v, (n_rows - 1, n_cols), f"parts[{k!r}]") for k, v in (parts or {}).items()} + if parts and vertical is None: + raise ValueError("parts split the vertical flux; give vertical too") + note_text = None if notes is None else np.asarray(notes, dtype=object) + if note_text is not None and note_text.shape != (n_rows, n_cols): + raise ValueError(f"notes must have shape {(n_rows, n_cols)}, got {note_text.shape}") + for name, labels, n in (("row_labels", row_labels, n_rows), ("col_labels", col_labels, n_cols)): + if labels is not None and len(labels) != n: + raise ValueError(f"{name} must have {n} entries, got {len(labels)}") + + if ax is None: + from .figure import subplots + + _, ax = subplots(width=width, aspect=min(1.2, 0.62 * (n_rows + 0.9) / n_cols)) + + kind_color = {**FLUX_COLORS, **(colors or {})} + dark2 = mpl.colormaps["Dark2"].colors + pc = {k: mcolors.to_hex(dark2[i % len(dark2)]) for i, k in enumerate(parts)} + pc.update(part_colors or {}) + cm = resolve_cmap(cmap) + if norm is None: + finite = values[np.isfinite(values)] + limit = float(np.abs(finite).max()) if finite.size else 1.0 + norm = diverging_norm(-(limit or 1.0), limit or 1.0) + refs = { + "vertical": _reference(vertical, None), + "horizontal": _reference(horizontal, None), + "lateral": _reference(lateral, None), + "ground": _reference(ground, None), + } + refs.update(reference or {}) + diagram = FluxDiagram( + ax=ax, + mappable=ScalarMappable(norm=norm, cmap=cm), + boxes=np.empty((n_rows, n_cols), dtype=object), + colors=kind_color, + part_colors=pc, + ) + bw, bh = box_size + text = mpl.rcParams["text.color"] + fs_value, fs_flux = th.fs_body, th.fs_annot + fs_small = round(0.78 * th.fs_annot, 2) + + def arrow(kind: str, index: tuple[int, ...], value: float, a: tuple, b: tuple) -> float: + """Draw ``value`` from ``a`` to ``b`` if positive, from ``b`` to ``a`` if not.""" + tail, head = (a, b) if value >= 0 else (b, a) + ref = refs[kind] + frac = np.sqrt(min(1.0, abs(value) / ref)) if ref > 0 else 0.0 + w = _MIN_WIDTH + (max_width - _MIN_WIDTH) * frac + head_width = max(3.0, 2.4 * w) + patch = diagram_arrow( + ax, tail, head, width=w, head_width=head_width, color=kind_color[kind], gid=kind + ) + diagram.arrows.append(FluxArrow(kind, index, float(value), tail, head, w, patch)) + return head_width + + def beside(x: float, y: float, label: str, clearance: float, **kw: Any) -> None: + """``label`` centred on ``y``, ``clearance`` points right of ``x`` (left if negative).""" + ax.annotate( + label, + (x, y), + xytext=(clearance, 0.0), + textcoords="offset points", + ha="left" if clearance > 0 else "right", + va="center", + zorder=4, + **kw, + ) + + def flux_label(x: float, y: float, value: float, kind: str, **kw: Any) -> None: + ax.text(x, y, fmt(value), fontsize=fs_flux, fontweight="bold", color=kind_color[kind], zorder=4, **kw) + + for k in range(n_rows): + for j in range(n_cols): + x, v = j + 0.5, values[k, j] + fill = cm(norm(v)) if np.isfinite(v) else "none" + diagram.boxes[k, j] = diagram_box(ax, (x, k), bw, bh, facecolor=fill) + two = lateral is not None + if np.isfinite(v): + ax.text( + x, + k + (0.085 if two else 0.0), + fmt(v), + ha="center", + va="center", + fontsize=fs_value, + fontweight="bold", + color=_ink(fill), + zorder=4, + ) + if note_text is not None and str(note_text[k, j] or ""): + ax.text( + x - 0.07, + k - bh / 2 - 0.11, + str(note_text[k, j]), + ha="right", + va="center", + fontsize=fs_small, + color=text, + alpha=0.75, + zorder=4, + ) + if lateral is None or not np.isfinite(lateral[k, j]): + continue + h = lateral[k, j] + ax.text( + x, + k - 0.095, + fmt(h), + ha="center", + va="center", + fontsize=fs_flux, + color=kind_color["lateral"], + zorder=4, + bbox={"boxstyle": "round,pad=0.12", "facecolor": "white", "edgecolor": "none", "alpha": 0.85}, + ) + for side in (-1.0, 1.0): + edge = x + side * (bw / 2 + 0.015) + arrow("lateral", (k, j), h, (edge + side * _LATERAL_SPAN, k), (edge, k)) + + if vertical is not None: + for k in range(n_rows - 1): + for j in range(n_cols): + value = vertical[k, j] + if not np.isfinite(value): + continue + x, y0, y1 = j + 0.5, k + bh / 2 + _GAP, k + 1 - bh / 2 - _GAP + arrow("vertical", (k, j), value, (x, y0), (x, y1)) + clearance = diagram.arrows[-1].width / 2 + 4.0 + bold = {"fontsize": fs_flux, "fontweight": "bold", "color": kind_color["vertical"]} + beside(x, (y0 + y1) / 2, fmt(value), clearance, **bold) + lines = [(key, p[k, j]) for key, p in parts.items()] + step = 0.085 + for i, (key, p) in enumerate(lines): + y = (y0 + y1) / 2 + ((len(lines) - 1) / 2 - i) * step + beside(x, y, f"{key} {fmt(p)}", -clearance, fontsize=fs_small, color=pc[key]) + + if horizontal is not None: + for k in range(n_rows): + for j in range(n_cols - 1): + value = horizontal[k, j] + if not np.isfinite(value): + continue + x0, x1 = j + 0.5 + bw / 2 + _GAP, j + 1.5 - bw / 2 - _GAP + arrow("horizontal", (k, j), value, (x0, k), (x1, k)) + flux_label((x0 + x1) / 2, k + 0.05, value, "horizontal", ha="center", va="bottom") + + floor = -bh / 2 + if ground is not None: + floor = _GROUND_Y + for j in range(n_cols): + ax.add_patch( + Rectangle( + (j + 0.06, _GROUND_Y - 0.05), + 0.88, + 0.05, + facecolor="none", + edgecolor="0.6", + hatch="//////", + linewidth=0.0, + zorder=1, + gid="ground_hatch", + ) + ) + ax.plot([j + 0.06, j + 0.94], [_GROUND_Y, _GROUND_Y], color="0.55", lw=0.5, zorder=1) + value = ground[j] + if not np.isfinite(value): + continue + x, y0, y1 = j + 0.5, _GROUND_Y + 0.03, -bh / 2 - _GAP + head_width = arrow("ground", (j,), value, (x, y0), (x, y1)) + label = {"fontsize": fs_flux, "fontweight": "bold", "color": text, "alpha": 0.7} + beside(x, (y0 + y1) / 2, fmt(value), head_width / 2 + 2.0, **label) + if ground_label: + ax.text(-0.05, _GROUND_Y + 0.02, ground_label, ha="right", va="center", fontweight="bold") + + label_y = floor - _LABEL_DROP + for j, name in enumerate(col_labels or []): + ax.text(j + 0.5, label_y, name, ha="center", va="center", fontweight="bold") + if col_labels and col_title: + ax.text(-0.05, label_y, col_title, ha="right", va="center", style="italic") + for k, name in enumerate(row_labels or []): + ax.text(-0.05, k, name, ha="right", va="center", fontweight="bold", linespacing=1.25) + + ax.set_xlim(0.0, n_cols) + ax.set_ylim(label_y - (0.1 if col_labels else 0.0), n_rows - 1 + bh / 2 + 0.03) + ax.set_axis_off() + return ax, diagram + + +def flux_legend( + diagram: FluxDiagram, + labels: Mapping[str, str], + *, + parts: Mapping[str, str] | None = None, + target: Axes | Figure | None = None, + **kwargs: Any, +) -> Legend: + """Add a legend explaining a :func:`flux_diagram`'s colours. + + Args: + diagram: The diagram to explain. + labels: ``{kind: label}`` for ``"box"`` (a swatch from the box colormap) and the + kinds of flux (a line in its colour), listed in that order. + parts: ``{key: label}`` for the parts of the vertical flux, each shown as its key + in its colour. + target: Axes or figure to put the legend on; the diagram's axes by default. + **kwargs: Forwarded to :meth:`~matplotlib.axes.Axes.legend`, e.g. ``loc``, + ``ncol`` or ``bbox_to_anchor``. + + Returns: + The legend. + + Raises: + KeyError: A label names an unknown kind, or a part has no colour. + """ + th = get_theme() + lw = 2.2 + handles: list[Any] = [] + for kind in ("box", *_KINDS): + if kind not in labels: + continue + if kind == "box": + m = diagram.mappable + fill = m.to_rgba(0.6 * m.norm.vmax) + handles.append( + legend_handle(labels[kind], "band", facecolor=fill, edgecolor="0.55", linewidth=0.5) + ) + else: + handles.append(legend_handle(labels[kind], "line", color=diagram.colors[kind], lw=lw)) + unknown = set(labels) - {"box", *_KINDS} + if unknown: + raise KeyError(f"unknown kinds {sorted(unknown)}; expected 'box' or one of {_KINDS}") + for key, label in (parts or {}).items(): + handles.append( + legend_handle(label, "marker", color=diagram.part_colors[key], marker=f"${key}$", markersize=5) + ) + kw = {"frameon": False, "fontsize": th.fs_legend, "handlelength": 1.6, **kwargs} + return (target or diagram.ax).legend(handles=handles, **kw) diff --git a/src/nicefigs/palettes.py b/src/nicefigs/palettes.py index fa48361..8138aeb 100644 --- a/src/nicefigs/palettes.py +++ b/src/nicefigs/palettes.py @@ -13,6 +13,7 @@ import matplotlib as mpl import matplotlib.colors as mcolors import numpy as np +from matplotlib.lines import Line2D from matplotlib.patches import Patch from numpy.typing import ArrayLike @@ -236,6 +237,45 @@ def role_style( return {**kw, **overrides} +def legend_handle(label: str, kind: str = "line", **style: Any) -> Line2D | Patch: + """A legend entry drawn like a line, a marker or a band, for ``ax.legend(handles=...)``. + + Use it for entries that no plotted artist carries, e.g. a band drawn without a label or + one entry standing for many panels. ``kind`` takes the vocabulary of :func:`role_style`, + whose output can be passed as ``style``. + + Args: + label: Legend text. + kind: ``"line"`` (line, no markers), ``"marker"`` (markers, no line), ``"both"``, + or ``"band"`` (a filled swatch). + **style: Matplotlib keywords of the entry, e.g. ``color``, ``linestyle``, + ``marker`` or ``alpha``; ``kind`` wins over a ``linestyle`` or ``marker`` + it switches off. + + Returns: + A :class:`~matplotlib.lines.Line2D`, or a :class:`~matplotlib.patches.Patch` for + ``"band"``. + + Raises: + ValueError: Unknown ``kind``. + + Example:: + + handles = [nf.legend_handle("observed 25–75 %", "band", color="k", alpha=0.25)] + ax.legend(handles=handles) + """ + if kind not in _ROLE_KINDS: + raise ValueError(f"Unknown kind {kind!r}. Expected one of {_ROLE_KINDS}.") + if kind == "band": + return Patch(**{"linewidth": 0, **style}, label=label) + kw: dict[str, Any] = {} + if kind == "marker": + kw["linestyle"] = "none" + if kind == "line": + kw["marker"] = "none" + return Line2D([], [], **{**style, **kw}, label=label) + + def diverging_norm(vmin: float, vmax: float, center: float = 0.0) -> mcolors.TwoSlopeNorm: """A ``TwoSlopeNorm`` mapping ``center`` to the colormap's midpoint, for anomaly maps. diff --git a/src/nicefigs/sections.py b/src/nicefigs/sections.py index 0afd013..c7d230d 100644 --- a/src/nicefigs/sections.py +++ b/src/nicefigs/sections.py @@ -33,6 +33,8 @@ def profile( marker: str = "o", baselines: Mapping[str, ArrayLike] | None = None, baseline_colors: Mapping[str, str] | None = None, + bands: Mapping[str, tuple[ArrayLike, ArrayLike]] | None = None, + band_alpha: float = 0.25, xlabel: str = "", xunits: str | None = None, ylabel: str = "level", @@ -61,6 +63,10 @@ def profile( marker: Marker used for profiles not in ``markers``. baselines: ``{name: values}`` reference profiles drawn dashed. baseline_colors: ``{name: colour}`` for ``baselines``; default grey. + bands: ``{name: (low, high)}`` ranges along ``y``, e.g. an interquartile range, + shaded behind the lines in the colour of the profile of the same name (grey + if there is none). Bands add no legend entry; see :func:`legend_handle`. + band_alpha: Opacity of the bands. xlabel: Value-axis label. xunits: Value-axis units, appended to the label. ylabel: Vertical-axis label. @@ -86,6 +92,13 @@ def profile( if ax is None: _, ax = subplots(width=width, aspect=aspect) + for nm, (low, high) in (bands or {}).items(): + low, high = np.asarray(low, dtype=float), np.asarray(high, dtype=float) + yy = np.arange(low.size) if y is None else np.asarray(y, dtype=float) + ax.fill_betweenx( + yy, low, high, color=palette.get(nm, "#888888"), alpha=band_alpha, linewidth=0, zorder=1 + ) + for nm in names: v = np.asarray(profiles[nm], dtype=float) yy = np.arange(v.size) if y is None else np.asarray(y, dtype=float) diff --git a/tests/test_api.py b/tests/test_api.py index 78fe218..c284f0a 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -44,6 +44,7 @@ def test_callables_are_callable(): "SCORECARD_DIVERGING_BOUNDARIES", "DIRECTIONS", "ROLES", + "FLUX_COLORS", } for name in nf.__all__: if name in non_callable_allowed: diff --git a/tests/test_api_sections.py b/tests/test_api_sections.py index 27fe2b6..f1ea9b2 100644 --- a/tests/test_api_sections.py +++ b/tests/test_api_sections.py @@ -46,3 +46,18 @@ def test_hovmoller_non_robust_limits_span_the_data(): assert m.get_clim() == pytest.approx((np.min(h["value"]), np.max(h["value"]))) finally: plt.close(ax.figure) + + +def test_profile_bands_shade_the_given_range_in_the_profile_colour(): + from matplotlib.colors import to_rgba + + y = np.linspace(0.0, 10.0, 11) + low, high = np.full(11, -1.0), np.full(11, 2.0) + ax = nf.profile( + {"obs": np.zeros(11)}, y, colors={"obs": "#4477AA"}, bands={"obs": (low, high)}, band_alpha=0.3 + ) + (band,) = ax.collections + xs = band.get_paths()[0].vertices[:, 0] + assert xs.min() == -1.0 and xs.max() == 2.0 + np.testing.assert_allclose(band.get_facecolor()[0], to_rgba("#4477AA", 0.3)) + assert ax.get_legend() is None or "obs" not in [t.get_text() for t in ax.get_legend().get_texts()][1:] diff --git a/tests/test_diagrams.py b/tests/test_diagrams.py new file mode 100644 index 0000000..e96971f --- /dev/null +++ b/tests/test_diagrams.py @@ -0,0 +1,173 @@ +"""Contract of `flux_diagram` and `flux_legend`: every flux an arrow pointing its way, sized by √|value|.""" + +from __future__ import annotations + +import matplotlib.pyplot as plt +import numpy as np +import pytest + +import nicefigs as nf +from nicefigs import data + + +@pytest.fixture +def budget(): + return data.box_budget() + + +def _draw(b, **kw): + return nf.flux_diagram( + b["storage"], + lateral=b["lateral"], + vertical=b["vertical"], + ground=b["ground"], + parts=b["parts"], + row_labels=b["row_labels"], + col_labels=b["col_labels"], + **kw, + ) + + +def test_the_example_budget_closes(budget): + """Storage change = lateral inflow + flux in through the bottom − flux out through the top.""" + up_in = np.vstack([budget["ground"][None, :], budget["vertical"]]) + up_out = np.vstack([budget["vertical"], np.zeros((1, budget["storage"].shape[1]))]) + np.testing.assert_allclose(budget["storage"], budget["lateral"] + up_in - up_out, atol=1e-12) + + +def test_every_finite_flux_is_one_arrow(budget): + n_rows, n_cols = budget["storage"].shape + vertical = budget["vertical"].copy() + vertical[0, 1] = np.nan + budget["parts"] = {} + _, d = _draw({**budget, "vertical": vertical}) + assert len(d.of_kind("vertical")) == (n_rows - 1) * n_cols - 1, "the NaN flux is not drawn" + assert len(d.of_kind("lateral")) == 2 * n_rows * n_cols, "both sides of every box" + assert len(d.of_kind("ground")) == n_cols + assert d.boxes.shape == (n_rows, n_cols) + + +def test_arrows_point_the_way_the_flux_goes(budget): + _, d = _draw(budget) + for a in d.of_kind("vertical") + d.of_kind("ground"): + assert np.sign(a.head[1] - a.tail[1]) == np.sign(a.value) or a.value == 0 + assert a.head[0] == a.tail[0] + for a in d.of_kind("lateral"): + k, j = a.index + centre = j + 0.5 + inward = abs(a.head[0] - centre) < abs(a.tail[0] - centre) + assert inward == (a.value >= 0), "in when converging, out when diverging" + assert a.head[1] == a.tail[1] == k + + +def test_horizontal_fluxes_point_right_when_positive(): + _, d = nf.flux_diagram(np.zeros((2, 3)), horizontal=[[1.0, -2.0], [0.5, -0.5]]) + for a in d.of_kind("horizontal"): + assert np.sign(a.head[0] - a.tail[0]) == np.sign(a.value) + k, j = a.index + assert j + 0.5 < min(a.head[0], a.tail[0]) and max(a.head[0], a.tail[0]) < j + 1.5, ( + "between the boxes" + ) + + +def test_the_drawn_tip_is_at_the_head(): + """The patch, as rendered, ends at the declared head: its farthest vertex along the flux.""" + ax, d = nf.flux_diagram(np.zeros((2, 2)), vertical=[[3.0, -3.0]]) + ax.figure.canvas.draw() + for a in d.of_kind("vertical"): + verts = a.artist.get_path().vertices # data coordinates + along = np.sign(a.value) * verts[:, 1] + np.testing.assert_allclose(verts[np.argmax(along)], a.head, atol=1e-3) + + +def test_widths_grow_as_the_square_root_of_the_value(): + values = np.array([[0.0, 1.0, 4.0, 9.0, 16.0]]) + _, d = nf.flux_diagram(np.zeros((2, 5)), vertical=values, max_width=5.0) + w = np.array([a.width for a in d.of_kind("vertical")]) + assert w[-1] == pytest.approx(5.0), "the largest value is drawn max_width wide" + np.testing.assert_allclose(np.diff(w[1:]), np.diff(w[1:])[0], err_msg="equal steps in √value") + assert w[0] > 0, "a zero flux is still visible" + + +def test_a_shared_reference_gives_shared_widths(): + _, small = nf.flux_diagram(np.zeros((1, 2)), ground=[1.0, 2.0], reference={"ground": 8.0}) + _, large = nf.flux_diagram(np.zeros((1, 2)), ground=[1.0, 8.0], reference={"ground": 8.0}) + assert small.of_kind("ground")[0].width == large.of_kind("ground")[0].width + + +def test_box_colours_are_centred_on_zero(): + from matplotlib.colors import to_rgba + + _, d = nf.flux_diagram([[0.0, -2.0, 1.0]], cmap="BrBG_r") + cm = plt.get_cmap("BrBG_r") + fills = [to_rgba(b.get_facecolor()) for b in d.boxes.ravel()] + np.testing.assert_allclose(fills[0], cm(0.5), atol=1e-6) + np.testing.assert_allclose(fills[1], cm(0.0), atol=1e-6) + np.testing.assert_allclose(fills[2], cm(0.75), atol=1e-6) + + +def test_a_given_norm_is_used(): + norm = nf.diverging_norm(-10.0, 10.0) + _, d = nf.flux_diagram([[1.0]], norm=norm) + assert d.mappable.norm is norm + + +def test_the_layout_has_no_overlapping_text(budget): + ax, _ = _draw(budget, col_title="Region") + assert nf.check_text_overlaps(ax.figure, clipped=False) == [] + + +@pytest.mark.parametrize( + "kw", + [ + {"vertical": np.zeros((3, 2))}, + {"ground": np.zeros(3)}, + {"lateral": np.zeros((2, 2)), "horizontal": np.zeros((2, 1))}, + {"parts": {"c": np.zeros((1, 2))}}, + {"row_labels": ["only one"]}, + ], +) +def test_inconsistent_inputs_are_rejected(kw): + with pytest.raises(ValueError): + nf.flux_diagram(np.zeros((2, 2)), **kw) + + +def test_the_legend_lists_what_it_is_given(budget): + _, d = _draw(budget) + labels = {"box": "storage", "vertical": "up", "ground": "ground"} + legend = nf.flux_legend(d, labels, parts={"c": "convective"}) + assert [t.get_text() for t in legend.get_texts()] == ["storage", "up", "ground", "convective"] + with pytest.raises(KeyError): + nf.flux_legend(d, {"sideways": "?"}) + + +def test_an_arrow_is_as_wide_in_points_on_any_aspect(): + """The shaft width is physical: the same on a squashed and a stretched axes.""" + widths = [] + for aspect in (0.3, 3.0): + _, ax = nf.subplots(width=3.0, aspect=aspect) + ax.set_xlim(0, 1) + ax.set_ylim(0, 1) + arrow = nf.diagram_arrow(ax, (0.1, 0.5), (0.9, 0.5), width=4.0, head_width=4.0) + ax.figure.canvas.draw() + y = ax.transData.transform(arrow.get_path().vertices)[:, 1] + widths.append((y.max() - y.min()) * 72.0 / ax.figure.dpi) + np.testing.assert_allclose(widths, 4.0, rtol=0.02) + + +def test_an_arrow_label_sits_at_the_midpoint(): + _, ax = nf.subplots() + nf.diagram_arrow(ax, (0.0, 0.0), (2.0, 4.0), label="flux") + (label,) = ax.texts + assert label.xy == (1.0, 2.0) and label.get_text() == "flux" + + +def test_box_text_reads_on_its_fill(): + from matplotlib.colors import to_rgba + + _, ax = nf.subplots() + nf.diagram_box(ax, (0.5, 0.5), 0.4, 0.2, text="dark", facecolor="#003040") + nf.diagram_box(ax, (0.5, 0.2), 0.4, 0.2, text="light", facecolor="#f0f0f0") + dark, light = ax.texts + assert to_rgba(dark.get_color()) == to_rgba("white") + assert sum(to_rgba(light.get_color())[:3]) < 0.5 diff --git a/tests/test_palettes.py b/tests/test_palettes.py index 88f96ef..21ae4de 100644 --- a/tests/test_palettes.py +++ b/tests/test_palettes.py @@ -7,6 +7,7 @@ import numpy as np import pytest +import nicefigs as nf from nicefigs.palettes import ( CATEGORICAL, DEFAULTS, @@ -228,3 +229,22 @@ def test_scorecard_diverging_cmap_extend_colors_distinct_from_bands(): def test_qualitative_unknown_palette_raises(): with pytest.raises(KeyError, match="Unknown palette"): qualitative(3, "no-such-palette") + + +@pytest.mark.parametrize( + ("kind", "drawn"), + [("line", (True, False)), ("marker", (False, True)), ("both", (True, True))], +) +def test_legend_handle_draws_what_its_kind_says(kind, drawn): + h = nf.legend_handle("x", kind, color="k", marker="o", linestyle="-") + assert (h.get_linestyle() != "None", h.get_marker() not in ("None", "none")) == drawn + assert h.get_label() == "x" + + +def test_legend_handle_band_is_a_filled_swatch(): + from matplotlib.patches import Patch + + h = nf.legend_handle("IQR", "band", **nf.role_style("null", "band"), alpha=0.25) + assert isinstance(h, Patch) and h.get_alpha() == 0.25 and h.get_label() == "IQR" + with pytest.raises(ValueError): + nf.legend_handle("x", "ribbon")