diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f1f86b..f1cd2ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,14 @@ to [Semantic Versioning](https://semver.org/). ### Added +- `polygon_mesh` draws cells of any shape (hexagons and pentagons of a grid) from their + corners, filled by value, by class, by a given colour or not at all. +- `outline_boxes` outlines rectangles in data coordinates, to highlight cells, rows or + columns of a grid. +- `one_to_one`, `kde_contours`, `scatter_regression` and `histogram`: the 1:1 line, Gaussian-KDE + contours over paired samples, the target-against-model panel with a regression per model, and a + histogram that overlays on one axes. +- `colorbar(cax=...)` draws a bar into axes of your own, with the same styling. - `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` diff --git a/docs/api.md b/docs/api.md index a78598a..828bf12 100644 --- a/docs/api.md +++ b/docs/api.md @@ -20,6 +20,10 @@ and the [Gallery](gallery.md) for runnable examples. ::: nicefigs.palettes +## `nicefigs.shapes` + +::: nicefigs.shapes + ## `nicefigs.colorbars` ::: nicefigs.colorbars diff --git a/src/nicefigs/__init__.py b/src/nicefigs/__init__.py index 54ee7f1..32cc5d3 100644 --- a/src/nicefigs/__init__.py +++ b/src/nicefigs/__init__.py @@ -19,6 +19,7 @@ from .animation import animate_maps, render_animation, save_animation, stitch_frames from .artists import ARTIST_PALETTES, HOCKNEY_CANYON, NICE, artist_cmap, artist_palette from .bars import grouped as grouped_bars +from .bars import histogram from .bars import stacked as stacked_bars from .colorbars import colorbar, inset_histogram_colorbar, make_mappable from .colormaps2d import ( @@ -42,7 +43,7 @@ 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 -from .kde import agreement +from .kde import agreement, kde_contours, scatter_regression from .lines import lines from .maps import ( binned_map, @@ -83,6 +84,8 @@ facet, grid, label_panels, + one_to_one, + outline_boxes, panel_label, reference_line, row_labels, @@ -91,6 +94,7 @@ from .ranking import caterpillar from .scatter import scatter from .sections import cross_section, cross_section_panels, profile +from .shapes import polygon_mesh from .spectra import spectrum from .style import ( COLORS, @@ -161,6 +165,8 @@ "clean_title", "despine", "reference_line", + "one_to_one", + "outline_boxes", "facet", "row_labels", "col_labels", @@ -221,6 +227,10 @@ # relational "scatter", "agreement", + "kde_contours", + "scatter_regression", + "polygon_mesh", + "histogram", "timeseries", "lines", "spectrum", diff --git a/src/nicefigs/bars.py b/src/nicefigs/bars.py index 9030526..0269aad 100644 --- a/src/nicefigs/bars.py +++ b/src/nicefigs/bars.py @@ -178,3 +178,46 @@ def stacked( if legend: ax.legend(loc="center left", bbox_to_anchor=(1.01, 0.5), fontsize=th.fs_legend, frameon=False) return ax + + +def histogram( + values: ArrayLike, + *, + ax: Axes | None = None, + bins: int | ArrayLike = 50, + density: bool = False, + color: Any = None, + label: str | None = None, + xlabel: str = "", + ylabel: str = "", + **kwargs: Any, +) -> Axes: + """Draw a one-dimensional histogram, on an existing axes to overlay several. + + Non-finite values are dropped. Call it again on the same axes with another colour to + compare distributions; give ``bins`` as the same edges to make them comparable. + + Args: + values: The data. + ax: Target axes; a new half-width figure if omitted. + bins: Number of bins, or their edges. + density: Normalise to unit area. + color: Bar colour; the next colour of the axes cycle if omitted. + label: Legend label. + xlabel: x label. + ylabel: y label. + **kwargs: Passed to :meth:`~matplotlib.axes.Axes.hist` (e.g. ``alpha``, ``histtype``). + + Returns: + The axes. + """ + if ax is None: + _, ax = subplots(width="half", aspect=0.72) + th = get_theme() + v = np.asarray(values, dtype=float).ravel() + ax.hist(v[np.isfinite(v)], bins=bins, density=density, color=color, label=label, **kwargs) + if xlabel: + ax.set_xlabel(xlabel, fontsize=th.fs_axis_label) + if ylabel: + ax.set_ylabel(ylabel, fontsize=th.fs_axis_label) + return ax diff --git a/src/nicefigs/colorbars.py b/src/nicefigs/colorbars.py index 248cf34..1f75689 100644 --- a/src/nicefigs/colorbars.py +++ b/src/nicefigs/colorbars.py @@ -3,6 +3,7 @@ from __future__ import annotations from collections.abc import Sequence +from typing import Any import matplotlib.ticker as mticker import numpy as np @@ -30,8 +31,10 @@ def _bbox_union(axes: Sequence[Axes]) -> tuple[float, float, float, float]: def colorbar( mappable: ScalarMappable, - ax: Axes | Sequence[Axes], + ax: Axes | Sequence[Axes] | None = None, *, + cax: Axes | None = None, + orientation: str = "vertical", label: str = "", location: str = "right", pad: float = 0.012, @@ -39,13 +42,19 @@ def colorbar( shrink: float = 1.0, extend: str = "neither", ticks: ArrayLike | None = None, + **kwargs: Any, ) -> Colorbar: - """Draw a slim colorbar flush to one axes, or spanning several. + """Draw a slim colorbar flush to one axes, or spanning several, or into axes of your own. Args: mappable: E.g. the return of ``imshow``, ``scatter`` or ``pcolormesh``, or one from :func:`make_mappable`. - ax: One axes, or a sequence of axes the bar should span. + ax: One axes, or a sequence of axes the bar should span. Omitted when ``cax`` is given. + cax: Axes the bar is drawn into, for a figure that lays its own bar out; the + placement arguments (``location``, ``pad``, ``thickness``, ``shrink``) then do + not apply, and the bar is styled like any other. + orientation: ``"vertical"`` or ``"horizontal"``; only read with ``cax`` (otherwise + ``location`` decides). label: Colorbar label. location: ``"right"``, ``"left"``, ``"bottom"`` or ``"top"``. pad: Gap between plot and bar, in figure fraction. @@ -53,13 +62,32 @@ def colorbar( shrink: Fraction of the spanned length the bar occupies (centred). extend: ``"neither"``, ``"both"``, ``"min"`` or ``"max"``. ticks: Explicit tick locations. + **kwargs: With ``cax``, passed to :meth:`~matplotlib.figure.Figure.colorbar` (e.g. + ``spacing``, ``boundaries``, ``format``); not accepted otherwise. Returns: The colorbar. + + Raises: + TypeError: If ``kwargs`` are given without ``cax``. + ValueError: If neither or both of ``ax`` and ``cax`` are given. """ + if (ax is None) == (cax is None): + raise ValueError("colorbar takes exactly one of ax (the axes it spans) or cax (its own axes)") + if kwargs and cax is None: + raise TypeError(f"colorbar() got unexpected keyword argument(s) {sorted(kwargs)} without cax") + th = get_theme() + if cax is not None: + cb = cax.figure.colorbar( + mappable, cax=cax, orientation=orientation, extend=extend, ticks=ticks, **kwargs + ) + cb.outline.set_linewidth(0.4) + cb.ax.tick_params(labelsize=th.fs_tick, length=1.6, width=0.35, pad=1.2) + if label: + cb.set_label(label, fontsize=th.fs_annot, labelpad=2.0) + return cb axes = list(ax) if isinstance(ax, (list, tuple, np.ndarray)) else [ax] fig = axes[0].figure - th = get_theme() x0, y0, x1, y1 = _bbox_union(axes) if location in ("right", "left"): diff --git a/src/nicefigs/kde.py b/src/nicefigs/kde.py index e36a946..b3f1a62 100644 --- a/src/nicefigs/kde.py +++ b/src/nicefigs/kde.py @@ -7,6 +7,8 @@ import numpy as np if TYPE_CHECKING: + from collections.abc import Callable, Mapping + from matplotlib.axes import Axes from numpy.typing import ArrayLike @@ -185,3 +187,133 @@ def agreement( bbox=dict(boxstyle="round,pad=0.35", fc="white", ec="#cccccc", lw=0.4, alpha=0.85), ) return ax, stats + + +def _finite_stride(x: ArrayLike, y: ArrayLike, n: int) -> tuple[np.ndarray, np.ndarray]: + """Finite pairs of ``(x, y)``, thinned by an even stride to at most ``n`` (deterministic).""" + x = np.asarray(x, dtype=float).ravel() + y = np.asarray(y, dtype=float).ravel() + ok = np.isfinite(x) & np.isfinite(y) + x, y = x[ok], y[ok] + if x.size > n: + idx = np.linspace(0, x.size - 1, n).astype(int) + x, y = x[idx], y[idx] + return x, y + + +def kde_contours( + ax: Axes, + x: ArrayLike, + y: ArrayLike, + color: Any, + *, + max_points: int = 4000, + levels: int = 4, + linewidth: float = 0.7, + alpha: float = 0.9, +) -> None: + """Overlay Gaussian-KDE density contour lines of paired samples. + + The density is evaluated over the 1st to 99th percentile of each variable, so sparse + outliers do not drag a low contour across the panel. Too few points, no spread or a + singular covariance draw nothing. + + Args: + ax: Target axes. + x: Samples; non-finite pairs are dropped. + y: Paired samples, same length as ``x``. + color: Contour colour. + max_points: Pairs the density is estimated from, thinned by an even stride. + levels: Number of contour levels. + linewidth: Contour line width (pt). + alpha: Contour opacity. + """ + from scipy.stats import gaussian_kde + + x, y = _finite_stride(x, y, max_points) + if x.size < 10 or np.allclose(x.std(), 0) or np.allclose(y.std(), 0): + return + try: + kde = gaussian_kde(np.vstack([x, y])) + except np.linalg.LinAlgError: + return + xs = np.linspace(*np.percentile(x, [1, 99]), 70) + ys = np.linspace(*np.percentile(y, [1, 99]), 70) + gx, gy = np.meshgrid(xs, ys) + z = kde(np.vstack([gx.ravel(), gy.ravel()])).reshape(gx.shape) + ax.contour(gx, gy, z, levels=levels, colors=color, linewidths=linewidth, alpha=alpha) + + +def scatter_regression( + x: ArrayLike, + models: Mapping[str, ArrayLike], + *, + ax: Axes | None = None, + colors: Mapping[str, Any], + xlabel: str = "", + ylabel: str = "", + regress: Callable[[np.ndarray, np.ndarray], tuple[float, float, float, float]] | None = None, + max_points: int = 4000, + legend: bool = True, +) -> Axes: + """Target-against-model panel: 1:1 line, faint scatter, density contours and a regression per model. + + Each model's legend entry carries its slope, R² and RMSE to the 1:1 line (what a model + against a target reports is how far it is from the target, not how well a free line fits). + Both axes span the 1st to 99th percentile of all values and are equal. + + Args: + x: The target values. + models: Name to values of each model against ``x``, in legend order. + ax: Target axes; a new half-width figure if omitted. + colors: Colour per model name. + xlabel: x label. + ylabel: y label. + regress: ``(x, y) -> (slope, intercept, r2, rmse)``; ordinary least squares and the RMSE to the 1:1 line if omitted. + max_points: Points scattered per model, thinned by an even stride. + legend: Draw the legend. + + Returns: + The axes. + """ + if ax is None: + from .figure import subplots + + _, ax = subplots(width="half", aspect=1.0) + th = get_theme() + regress = regress or _regress_to_identity + x = np.asarray(x, dtype=float) + thinned = {name: _finite_stride(x, y, max_points) for name, y in models.items()} + finite = np.concatenate([a for pair in thinned.values() for a in pair]) + lo, hi = np.nanpercentile(finite, [1, 99]) + ax.plot([lo, hi], [lo, hi], "k--", lw=0.8, zorder=1) + for name, (xs, ys) in thinned.items(): + ax.scatter(xs, ys, s=3, alpha=0.12, color=colors[name], edgecolors="none", zorder=2) + for name, y in models.items(): + kde_contours(ax, x, y, colors[name], max_points=max_points) + xx = np.array([lo, hi]) + for name, y in models.items(): + slope, intercept, r2, rmse = regress(x, np.asarray(y, dtype=float)) + ax.plot( + xx, + slope * xx + intercept, + color=colors[name], + lw=1.4, + zorder=4, + label=f"{name}: slope {slope:.2f}, R² {r2:.2f}, RMSE {rmse:.2f}", + ) + ax.set_xlim(lo, hi) + ax.set_ylim(lo, hi) + ax.set_aspect("equal", "box") + ax.set_xlabel(xlabel, fontsize=th.fs_axis_label) + ax.set_ylabel(ylabel, fontsize=th.fs_axis_label) + if legend: + ax.legend(fontsize=th.fs_legend, loc="upper left", framealpha=0.85) + return ax + + +def _regress_to_identity(x: np.ndarray, y: np.ndarray) -> tuple[float, float, float, float]: + """``(slope, intercept, r2, rmse)`` of ``y`` on ``x``; the RMSE is to the 1:1 line.""" + ok = np.isfinite(x) & np.isfinite(y) + a, b, r2, rmse, _ = _linfit(x[ok], y[ok]) + return float(a), float(b), float(r2), rmse diff --git a/src/nicefigs/panels.py b/src/nicefigs/panels.py index 2c3c588..5083dad 100644 --- a/src/nicefigs/panels.py +++ b/src/nicefigs/panels.py @@ -436,6 +436,71 @@ def reference_line( ) +def one_to_one( + ax: Axes, + lo: float, + hi: float, + *, + margin: float = 0.05, + color: str = "#333333", + linestyle: str = "--", + linewidth: float = 0.8, + label: str | None = "1:1", + zorder: float = 1, +) -> None: + """Draw the 1:1 line over a data range, extended by a margin so it clears the data. + + Args: + ax: Target axes. + lo: Low end of the data range the line spans. + hi: High end of the data range the line spans. + margin: Extension at each end, as a fraction of ``hi - lo``; a degenerate range + extends by 0.1. + color: Line colour. + linestyle: Line style. + linewidth: Line width (pt). + label: Legend label; ``None`` leaves the line out of legends. + zorder: Line drawing order. + """ + pad = (hi - lo) * margin or 0.1 + ax.plot( + [lo - pad, hi + pad], + [lo - pad, hi + pad], + color=color, + linestyle=linestyle, + linewidth=linewidth, + label=label, + zorder=zorder, + ) + + +def outline_boxes( + ax: Axes, + boxes: Iterable[tuple[float, float, float, float]], + *, + color: str = "#222222", + linewidth: float = 2.0, + zorder: float = 5, +) -> None: + """Outline rectangles in data coordinates, to highlight cells of a grid, a row or a column. + + The outline is unfilled, so it sits on top of whatever the boxes surround. + + Args: + ax: Target axes. + boxes: ``(x, y, width, height)`` of each rectangle, with ``(x, y)`` its lower-left corner. + color: Edge colour. + linewidth: Edge width (pt). + zorder: Drawing order. + """ + from matplotlib.patches import Rectangle + + for x, y, w, h in boxes: + ax.add_patch( + Rectangle((x, y), w, h, facecolor="none", edgecolor=color, linewidth=linewidth, zorder=zorder) + ) + + def facet( items: Iterable[Any], draw: Callable[[Axes, Any, int], object], diff --git a/src/nicefigs/shapes.py b/src/nicefigs/shapes.py new file mode 100644 index 0000000..3cbb748 --- /dev/null +++ b/src/nicefigs/shapes.py @@ -0,0 +1,110 @@ +"""Polygon meshes: cells of any shape drawn from their corners, filled by value or by category.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from typing import TYPE_CHECKING, Any + +import numpy as np +from matplotlib.collections import PolyCollection + +if TYPE_CHECKING: + from matplotlib.axes import Axes + from matplotlib.colors import Normalize + from numpy.typing import ArrayLike + +from .palettes import cmap as resolve_cmap + + +def polygon_mesh( + ax: Axes, + polygons: Sequence[ArrayLike], + values: ArrayLike | None = None, + *, + categories: Sequence[Any] | None = None, + colors: Mapping[Any, Any] | None = None, + facecolors: Sequence[Any] | None = None, + cmap: str = "viridis", + vmin: float | None = None, + vmax: float | None = None, + norm: Normalize | None = None, + facecolor: Any = "none", + edgecolor: Any = None, + linewidth: float = 0.4, + rasterized: bool = False, + **kwargs: Any, +) -> PolyCollection: + """Draw polygons, such as hexagonal and pentagonal grid cells, filled by value or by category. + + Cells may have different corner counts. Fill them with a colour scale (``values``), + with a colour per class (``categories`` and ``colors``), with a colour given per cell + (``facecolors``), or leave them unfilled (outlines only). The collection is added to ``ax`` and the data limits are updated; on a + map the caller sets the extent and passes ``transform=``. + + Args: + ax: Target axes. + polygons: One ``(corners, 2)`` array of ``(x, y)`` per cell, corners in order around the cell. + values: One value per cell, mapped through ``cmap`` and the limits. + categories: One class per cell; needs ``colors``. + colors: Class to colour, for ``categories``. + facecolors: One fill colour per cell, for a colouring the caller already computed. + cmap: Colormap name or object, for ``values``. + vmin: Lower colour limit; the data minimum if omitted. + vmax: Upper colour limit; the data maximum if omitted. + norm: Normalisation; overrides ``vmin`` and ``vmax``. + facecolor: Fill of every cell when neither ``values`` nor ``categories`` is given. + edgecolor: Edge colour; ``"face"`` draws each edge in its cell's fill, which hides seams; + the default is ``"face"`` for filled cells and black for unfilled ones. + linewidth: Edge width (pt). + rasterized: Rasterise the collection, to keep a vector figure small. + **kwargs: Passed to :class:`~matplotlib.collections.PolyCollection` (e.g. ``transform``). + + Returns: + The collection; for ``values`` it is also the mappable of a colorbar. + + Raises: + ValueError: If more than one of ``values``, ``categories`` and ``facecolors`` is given, ``categories`` lacks + ``colors`` or a class has no colour, or a length differs from ``polygons``. + """ + if sum(arg is not None for arg in (values, categories, facecolors)) > 1: + raise ValueError("give values, categories or facecolors, not several") + n = len(polygons) + if edgecolor is None: + unfilled = values is None and categories is None and facecolors is None + edgecolor = "black" if unfilled else "face" + kw: dict[str, Any] = { + "edgecolors": edgecolor, + "linewidths": linewidth, + "rasterized": rasterized, + **kwargs, + } + if values is not None: + values = np.asarray(values, dtype=float) + if values.shape != (n,): + raise ValueError(f"values has shape {values.shape}, expected ({n},)") + finite = values[np.isfinite(values)] + if norm is None and finite.size: + from matplotlib.colors import Normalize + + norm = Normalize( + vmin=finite.min() if vmin is None else vmin, vmax=finite.max() if vmax is None else vmax + ) + coll = PolyCollection(polygons, array=values, cmap=resolve_cmap(cmap), norm=norm, **kw) + elif facecolors is not None: + if len(facecolors) != n: + raise ValueError(f"facecolors has {len(facecolors)} entries, expected {n}") + coll = PolyCollection(polygons, facecolors=list(facecolors), **kw) + elif categories is not None: + if colors is None: + raise ValueError("categories need colors, a mapping from class to colour") + if len(categories) != n: + raise ValueError(f"categories has {len(categories)} entries, expected {n}") + missing = {c for c in categories if c not in colors} + if missing: + raise ValueError(f"no colour for class(es) {sorted(map(str, missing))}") + coll = PolyCollection(polygons, facecolors=[colors[c] for c in categories], **kw) + else: + coll = PolyCollection(polygons, facecolors=facecolor, **kw) + ax.add_collection(coll) + ax.autoscale_view() + return coll diff --git a/tests/test_shapes_and_primitives.py b/tests/test_shapes_and_primitives.py new file mode 100644 index 0000000..ec9ae1c --- /dev/null +++ b/tests/test_shapes_and_primitives.py @@ -0,0 +1,139 @@ +"""polygon_mesh, outline_boxes, one_to_one, kde_contours, scatter_regression, histogram and colorbar(cax=).""" + +from __future__ import annotations + +import matplotlib.pyplot as plt +import numpy as np +import pytest + +import nicefigs as nf + + +def _hexagon(cx: float, cy: float) -> np.ndarray: + a = np.linspace(0, 2 * np.pi, 7)[:-1] + return np.stack([cx + np.cos(a), cy + np.sin(a)], axis=-1) + + +def _triangle(cx: float, cy: float) -> np.ndarray: + return np.array([[cx, cy], [cx + 1, cy], [cx, cy + 1]]) + + +def test_polygon_mesh_by_value_maps_through_the_limits_and_mixes_corner_counts(): + fig, ax = plt.subplots() + cells = [_hexagon(0, 0), _triangle(3, 0)] + coll = nf.polygon_mesh(ax, cells, [0.0, 1.0], cmap="viridis", vmin=0.0, vmax=2.0) + assert np.allclose(coll.get_array(), [0.0, 1.0]) + assert (coll.norm.vmin, coll.norm.vmax) == (0.0, 2.0) + assert ax.get_xlim()[1] > 4.0 # the view grew to hold the second cell + assert len(coll.get_paths()[0].vertices) != len(coll.get_paths()[1].vertices) + + +def test_polygon_mesh_by_category_fills_each_cell_with_its_class_colour(): + fig, ax = plt.subplots() + coll = nf.polygon_mesh( + ax, [_hexagon(0, 0), _hexagon(3, 0)], categories=["a", "b"], colors={"a": "red", "b": "blue"} + ) + assert [tuple(c[:3]) for c in coll.get_facecolor()] == [(1.0, 0.0, 0.0), (0.0, 0.0, 1.0)] + + +def test_polygon_mesh_takes_a_colour_per_cell_as_given(): + fig, ax = plt.subplots() + coll = nf.polygon_mesh(ax, [_hexagon(0, 0), _hexagon(3, 0)], facecolors=["red", (0.0, 0.0, 1.0, 1.0)]) + assert [tuple(c[:3]) for c in coll.get_facecolor()] == [(1.0, 0.0, 0.0), (0.0, 0.0, 1.0)] + + +def test_polygon_mesh_rejects_ambiguous_or_incomplete_fills(): + fig, ax = plt.subplots() + cells = [_hexagon(0, 0)] + with pytest.raises(ValueError, match="not several"): + nf.polygon_mesh(ax, cells, [1.0], categories=["a"], colors={"a": "r"}) + with pytest.raises(ValueError, match="need colors"): + nf.polygon_mesh(ax, cells, categories=["a"]) + with pytest.raises(ValueError, match="no colour"): + nf.polygon_mesh(ax, cells, categories=["a"], colors={"b": "r"}) + with pytest.raises(ValueError, match="expected"): + nf.polygon_mesh(ax, cells, [1.0, 2.0]) + + +def test_outline_boxes_draws_unfilled_rectangles_at_the_given_cells(): + fig, ax = plt.subplots() + nf.outline_boxes(ax, [(0, 1, 2, 1), (3, 0, 1, 1)], color="k", linewidth=2.0) + assert len(ax.patches) == 2 + first = ax.patches[0] + assert first.get_facecolor()[3] == 0.0 + assert (first.get_x(), first.get_y(), first.get_width(), first.get_height()) == (0, 1, 2, 1) + + +def test_one_to_one_spans_the_range_plus_its_margin_on_the_diagonal(): + fig, ax = plt.subplots() + nf.one_to_one(ax, 0.0, 10.0) + (line,) = ax.lines + assert line.get_xdata().tolist() == pytest.approx([-0.5, 10.5]) + assert line.get_ydata().tolist() == line.get_xdata().tolist() + nf.one_to_one(ax, 2.0, 2.0) + assert ax.lines[1].get_xdata().tolist() == pytest.approx([1.9, 2.1]) + + +def test_kde_contours_draw_for_a_cloud_and_nothing_for_a_constant(): + rng = np.random.default_rng(0) + fig, ax = plt.subplots() + x = rng.normal(size=500) + nf.kde_contours(ax, x, x + rng.normal(size=500) * 0.5, "k") + assert len(ax.collections) >= 1 + fig2, ax2 = plt.subplots() + nf.kde_contours(ax2, np.ones(100), rng.normal(size=100), "k") + assert len(ax2.collections) == 0 + + +def test_scatter_regression_reports_slope_r2_and_rmse_to_one_to_one_per_model(): + rng = np.random.default_rng(1) + x = rng.normal(size=400) + ax = nf.scatter_regression(x, {"good": x, "biased": 2.0 * x}, colors={"good": "b", "biased": "r"}) + labels = [t.get_text() for t in ax.get_legend().get_texts()] + assert labels[0].startswith("good: slope 1.00, R² 1.00, RMSE 0.00") + assert labels[1].startswith("biased: slope 2.00, R² 1.00") + assert ax.get_xlim() == ax.get_ylim() + + +def test_scatter_regression_takes_the_callers_statistic(): + x = np.linspace(0, 1, 50) + ax = nf.scatter_regression(x, {"m": x}, colors={"m": "b"}, regress=lambda a, b: (9.0, 0.0, 0.5, 0.25)) + assert "slope 9.00, R² 0.50, RMSE 0.25" in ax.get_legend().get_texts()[0].get_text() + + +def test_histogram_overlays_on_one_axes_and_drops_non_finite_values(): + ax = nf.histogram([1.0, 2.0, np.nan, 3.0], bins=np.array([0.0, 2.0, 4.0]), label="a") + nf.histogram([1.0, 1.5], ax=ax, bins=np.array([0.0, 2.0, 4.0]), label="b") + heights = [[p.get_height() for p in c] for c in ax.containers] + assert heights == [[1.0, 2.0], [2.0, 0.0]] + + +def test_colorbar_in_own_axes_is_styled_and_exclusive_with_ax(): + fig, ax = plt.subplots() + im = ax.imshow(np.arange(4.0).reshape(2, 2)) + cax = fig.add_axes((0.1, 0.01, 0.8, 0.03)) + cb = nf.colorbar(im, cax=cax, orientation="horizontal", label="v") + assert cb.ax is cax + assert cb.orientation == "horizontal" + assert cax.get_xlabel() == "v" + assert cb.outline.get_linewidth() == 0.4 + with pytest.raises(ValueError, match="exactly one"): + nf.colorbar(im, ax, cax=cax) + with pytest.raises(ValueError, match="exactly one"): + nf.colorbar(im) + with pytest.raises(TypeError, match="without cax"): + nf.colorbar(im, ax, spacing="proportional") + bounded = nf.colorbar(im, cax=fig.add_axes((0.1, 0.1, 0.03, 0.5)), spacing="proportional") + assert bounded.ax.get_ylabel() == "" + + +def test_legend_handle_band_carries_a_hatch(): + handle = nf.legend_handle("pending", "band", facecolor="none", edgecolor="k", hatch="///") + assert handle.get_hatch() == "///" + + +def test_polygon_mesh_without_a_fill_draws_visible_outlines(): + fig, ax = plt.subplots() + coll = nf.polygon_mesh(ax, [_hexagon(0, 0)]) + assert tuple(coll.get_edgecolor()[0][:3]) == (0.0, 0.0, 0.0) + assert len(coll.get_facecolor()) == 0 # "none"