diff --git a/CHANGELOG.md b/CHANGELOG.md index 06ecde1..018f33e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,38 @@ to [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Added + +- `scorecard` draws the PhD-defense-deck look: text is the raw value, colour the percent better + than a baseline on the fixed 11-band `scorecard_skill_cmap` (blue better, red worse). + New arguments: `color_values` and `text` (colour numbers apart from printed ones), + `reference_row` (outlined, grey, labelled `baseline_suffix`) and `reference_cells` (one outlined + cell per column), both also supplying `reference`; `unresolved` (grey cell with grey value), + `na_text`, `row_groups` and `row_group_gap`, `group_rule`, `cell_in`, `font_scale` and `floor`. +- `scorecard_skill_cmap()` returns the reversed `scorecard_diverging_cmap` pair (higher is better). +- `skill_gap(mode="percent", floor=...)` gives the percent better than the reference. +- Gallery example `34_scorecard_baseline`. + +### Changed + +- **Behaviour change** of `scorecard` defaults: `highlight_best=False`; with no baseline cells are + ranked per column on the skill palette (blue best) instead of `RdYlGn`; `reference=` colours by + percent better (with `uncertainty=` as before, in standard errors, on the same palette); `cmap=None`; + `group_gap=0.35` (was 0.6); `na_color="#e8e8e8"`; `colorbar_label=None` gives + "% better than the baseline" (pass `""` for none). +- **Behaviour change**: a new figure is sized from its cells (`cell_in`, 0.42 in) rather than from + `width="half"`; `width=` still fixes the figure width and solves the cell size. `square` only + acts on a given `ax`. +- **Behaviour change**: column headings are horizontal and wrapped, units are a grey second line, + group titles are regular weight above a 1.6 pt rule, row and column labels are text rather than + ticks, and the colourbar is half the grid width with ticks at the band edges and pointed ends. +- `outline_boxes` draws unfilled rectangles (`fill=False`). + +### Notes + +- `nicefigs.cmap("RdBu")` returns `RdBu_r` (red high), so `scorecard(reference=..., cmap="RdBu")` + colours better cells red. Pass `matplotlib.colormaps["RdBu"]` or use the default scale. + ## [1.2.0] - 2026-11-20 ### Added diff --git a/docs/assets/20_scorecard.png b/docs/assets/20_scorecard.png index b190c4a..92959ee 100644 Binary files a/docs/assets/20_scorecard.png and b/docs/assets/20_scorecard.png differ diff --git a/docs/assets/guide/plots-scorecard-diverging.png b/docs/assets/guide/plots-scorecard-diverging.png index ee4a76c..349cc64 100644 Binary files a/docs/assets/guide/plots-scorecard-diverging.png and b/docs/assets/guide/plots-scorecard-diverging.png differ diff --git a/docs/assets/guide/plots-scorecard.png b/docs/assets/guide/plots-scorecard.png index c563150..9cf89b2 100644 Binary files a/docs/assets/guide/plots-scorecard.png and b/docs/assets/guide/plots-scorecard.png differ diff --git a/docs/gallery.md b/docs/gallery.md index 21af923..fce9b72 100644 --- a/docs/gallery.md +++ b/docs/gallery.md @@ -280,9 +280,8 @@ each item, a reference line at the null, and a headline `summary` annotation. ### 20 — Scorecard {#scorecard} [`nicefigs.scorecard`][nicefigs.scorecard] renders a model×metric table as -coloured cells — normalised independently per column and respecting each -metric's `direction` (lower/higher better) — with the best model per metric -outlined. +coloured cells. With no baseline, cells are ranked independently per column, +respecting each metric's `direction` (lower/higher better), on the skill palette. ![Scorecard](gallery/20_scorecard.png) @@ -319,6 +318,21 @@ horizontal bar with the colormap's extend triangles. --8<-- "examples/30_scorecard_diverging.py" ``` +### 34 — Scorecard against a baseline {#scorecard-baseline} + +The default look of [`nicefigs.scorecard`][nicefigs.scorecard]: cell text is the +raw value and colour is the percent better than the baseline row, on the fixed +11-band scale [`scorecard_skill_cmap`][nicefigs.scorecard_skill_cmap] (blue better, +red worse). The baseline row is outlined and labelled, cells within the noise floor +stay grey, columns are grouped under titled rules, and the colourbar carries the +band edges with pointed ends. + +![Scorecard against a baseline](gallery/34_scorecard_baseline.png) + +```python +--8<-- "examples/34_scorecard_baseline.py" +``` + ## Budgets ### 33 — Flux diagram {#flux-diagram} diff --git a/docs/gallery/20_scorecard.png b/docs/gallery/20_scorecard.png index b190c4a..92959ee 100644 Binary files a/docs/gallery/20_scorecard.png and b/docs/gallery/20_scorecard.png differ diff --git a/docs/gallery/30_scorecard_diverging.png b/docs/gallery/30_scorecard_diverging.png index 97e8d97..534ed53 100644 Binary files a/docs/gallery/30_scorecard_diverging.png and b/docs/gallery/30_scorecard_diverging.png differ diff --git a/docs/gallery/34_scorecard_baseline.png b/docs/gallery/34_scorecard_baseline.png new file mode 100644 index 0000000..e4f8729 Binary files /dev/null and b/docs/gallery/34_scorecard_baseline.png differ diff --git a/docs/guide/plots.md b/docs/guide/plots.md index c015d38..33b895a 100644 --- a/docs/guide/plots.md +++ b/docs/guide/plots.md @@ -304,39 +304,60 @@ value offset beside each. ## Scorecards -[`scorecard()`][nicefigs.scorecard] renders a model × metric table as -coloured cells. By default each column is ranked on its own, using each -metric's `direction` from [`DIRECTIONS`][nicefigs.DIRECTIONS], and the best -cell per column is outlined. +[`scorecard()`][nicefigs.scorecard] renders a model × metric table as coloured +cells. The text of a cell is the raw value; its colour is the percent it is +better than a baseline, on one fixed 11-band scale +([`scorecard_skill_cmap()`][nicefigs.scorecard_skill_cmap]): blue is better, red +worse, light grey within about 1 %. The baseline is a row (`reference_row`), drawn +grey inside one outline and labelled "(baseline)", or one outlined cell per column +(`reference_cells`). Missing values print "n/a"; cells whose difference is below +the noise (`unresolved`) stay grey and print their value in grey. `col_groups` and +`row_groups` separate groups with a gap, and column groups get a title with a rule. +The figure is sized from its cells (`cell_in`, 0.42 in by default) with fonts at their +printed point sizes. ```python import numpy as np import nicefigs as nf -from nicefigs import data nf.set_theme("paper") -ms = data.model_scores() -values = np.array( - [[np.mean(ms["scores"][m][model]["daily"]) for m in ms["metrics"]] for model in ms["models"]] +rmse = np.array( + [ + [2.10, 4.56, 6.42, 0.765, 0.908, 1.03], + [1.60, 4.78, 6.72, 0.926, 0.694, 0.866], + [1.55, 4.53, 6.66, 0.788, 0.693, 0.841], + ] ) +cols = ["surface SH", "surface NH", "tower", "gradient", "OCO-2", "OCO-3"] +percent = nf.skill_gap(rmse, rmse[0], direction="lower_better", mode="percent") ax = nf.scorecard( - values, - row_labels=ms["models"], - col_labels=ms["metrics"], - direction={"RMSE": "lower_better", "Bias": "target", "R$^2$": "higher_better"}, - col_units={"RMSE": "mm"}, + rmse, + row_labels=["CT2026", "model A", "model B"], + col_labels=cols, + direction=dict.fromkeys(cols, "lower_better"), + reference_row="CT2026", + unresolved=np.abs(percent) < 2.0, + col_groups=["In situ"] * 3 + ["Gradient"] + ["Column"] * 2, + col_units=dict.fromkeys(cols, "ppm"), + cell_format="{:#.3g}", + colorbar=True, ) ``` ![Scorecard](../assets/guide/plots-scorecard.png) -Bias is ranked by closeness to zero, the default `target`. +The colours can also come from numbers other than the printed ones: `color_values=` +takes the percent directly and `text=` the printed entries. `reference=` measures +against any array, and with `uncertainty=` in standard errors instead of percent. +Without any baseline, cells are coloured by the rank within their column on a +continuous version of the palette, using each metric's `direction` from +[`DIRECTIONS`][nicefigs.DIRECTIONS]; `highlight_best=True` outlines the best cell +per column. -To colour cells by their value instead, pass a `norm`, for example from -[`scorecard_diverging_cmap()`][nicefigs.scorecard_diverging_cmap]. -`col_groups` gaps and titles groups of columns, `square=True` forces square -cells and `colorbar=True` adds a colorbar. +To colour cells by their printed value instead, pass a `norm`, for example from +[`scorecard_diverging_cmap()`][nicefigs.scorecard_diverging_cmap], together with its +`cmap`. ```python import numpy as np @@ -368,9 +389,10 @@ Negative differences, an improvement over the baseline, are blue; the outline marks the lowest value per column. [`skill_gap()`][nicefigs.skill_gap] computes the signed distance of each value -from a reference, positive where the value is better. Passing `reference=` to -`scorecard` colours cells by this gap, so metrics in different units share one -scale. +from a reference, positive where the value is better; `mode="percent"` gives the +percent better than the reference, with an optional `floor` for references near zero. +Passing `reference=` to `scorecard` colours cells by this gap, so metrics in different +units share one scale. ```python import nicefigs as nf diff --git a/examples/34_scorecard_baseline.py b/examples/34_scorecard_baseline.py new file mode 100644 index 0000000..0d89194 --- /dev/null +++ b/examples/34_scorecard_baseline.py @@ -0,0 +1,44 @@ +"""Scorecard of three models against a baseline row: text is the raw value, colour is percent better.""" + +import numpy as np + +import nicefigs as nf + + +def make(): + nf.set_theme("paper") + rows = ["CT2026", "model A", "model B", "model C"] + cols = ["surface SH", "surface NH", "tower", "aircraft", "ship", "gradient", "OCO-2", "OCO-3", "TCCON"] + groups = ["In situ"] * 5 + ["Gradient"] + ["Column"] * 3 + # Synthetic RMSE (ppm); smaller is better. + rmse = np.array( + [ + [2.10, 4.56, 6.42, 1.92, 2.97, 0.765, 0.908, 1.03, 0.898], + [1.60, 4.78, 6.72, 2.11, 3.21, 0.926, 0.694, 0.866, 0.916], + [1.62, 4.78, 6.75, 2.03, 2.86, 0.800, 0.691, 0.839, 0.911], + [1.55, 4.53, 6.66, 2.05, 2.73, 0.788, 0.693, 0.841, 1.05], + ] + ) + # Cells whose difference to the baseline is below the noise floor of their column stay grey. + noise = np.array([2, 1, 2, 2, 2, 6, 2, 2, 2.5]) + percent = nf.skill_gap(rmse, rmse[0], direction="lower_better", mode="percent") + ax = nf.scorecard( + rmse, + row_labels=rows, + col_labels=cols, + direction=dict.fromkeys(cols, "lower_better"), + reference_row="CT2026", + unresolved=np.abs(percent) < noise, + col_groups=groups, + col_units=dict.fromkeys(cols, "ppm"), + cell_format="{:#.3g}", + colorbar=True, + ) + return ax.figure + + +if __name__ == "__main__": + import matplotlib + + matplotlib.use("Agg") + nf.save(make(), "34_scorecard_baseline", formats=("png", "pdf")) diff --git a/src/nicefigs/__init__.py b/src/nicefigs/__init__.py index 46c30fc..4185d05 100644 --- a/src/nicefigs/__init__.py +++ b/src/nicefigs/__init__.py @@ -75,6 +75,7 @@ role_color, role_style, scorecard_diverging_cmap, + scorecard_skill_cmap, symmetric_limits, ) from .panels import ( @@ -182,6 +183,7 @@ "robust_limits", "symmetric_limits", "scorecard_diverging_cmap", + "scorecard_skill_cmap", "SCORECARD_DIVERGING_BOUNDARIES", # role palette "ROLES", diff --git a/src/nicefigs/_scorecard.py b/src/nicefigs/_scorecard.py new file mode 100644 index 0000000..cc8700f --- /dev/null +++ b/src/nicefigs/_scorecard.py @@ -0,0 +1,214 @@ +"""Text measurement, header drawing and colourbar placement for :func:`nicefigs.scorecard`.""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import matplotlib.colors as mcolors +import numpy as np +from matplotlib.font_manager import FontProperties +from matplotlib.lines import Line2D +from matplotlib.textpath import text_to_path +from matplotlib.ticker import FuncFormatter +from matplotlib.transforms import Bbox, ScaledTranslation + +if TYPE_CHECKING: + from matplotlib.axes import Axes + from matplotlib.colorbar import Colorbar + from matplotlib.colors import Colormap, Normalize + +INK = "#222222" +MUTED = "#666666" # unit lines, 0.4 grey +NA_TEXT = "#8c8c8c" # "n/a" and unresolved values, 0.55 grey +GREY_CELL = "#e8e8e8" + +# Base font sizes (pt) of a card drawn at its printed size. +FS_VALUE = 7.5 +FS_ROW = 8.0 +FS_HEAD = 7.0 +FS_UNIT = 6.0 +FS_GROUP = 9.5 +FS_CBAR = 8.0 +FS_CBAR_TICK = 7.0 + +_LINE = 1.25 # line height as a multiple of the font size + + +def text_width_pt(text: str, size: float) -> float: + """Width of a single line of ``text`` in points at font size ``size``.""" + if not text: + return 0.0 + w, _, _ = text_to_path.get_text_width_height_descent(text, FontProperties(size=size), False) + return float(w) + + +def wrap_heading(label: str, size: float, width_pt: float) -> str: + """Break ``label`` at spaces so each line fits ``width_pt``; existing newlines are kept.""" + lines = [] + for part in str(label).split("\n"): + line = "" + for word in part.split(): + trial = f"{line} {word}".strip() + if line and text_width_pt(trial, size) > width_pt: + lines.append(line) + line = word + else: + line = trial + lines.append(line) + return "\n".join(lines) + + +def header_heights( + headings: Sequence[str], has_units: bool, has_groups: bool, scale: float +) -> dict[str, float]: + """Vertical positions (pt above the top of the grid) of the stacked header elements. + + Returns: + ``units`` and ``heading`` (bottoms of those texts), ``rule`` and ``group`` (the group rule + and the bottom of the group titles) and ``top`` (upper edge of the whole header). + """ + n_lines = max((h.count("\n") + 1 for h in headings), default=1) + units = 3.0 * scale + heading = units + (FS_UNIT * _LINE * scale + 1.0 * scale if has_units else 0.0) + top = heading + n_lines * FS_HEAD * _LINE * 0.95 * scale + 1.0 * scale + rule = group = top + if has_groups: + rule = top + 3.0 * scale + group = rule + 2.5 * scale + top = group + FS_GROUP * _LINE * scale + return {"units": units, "heading": heading, "rule": rule, "group": group, "top": top} + + +def draw_header( + ax: Axes, + lefts: np.ndarray, + headings: Sequence[str], + units: Sequence[str], + groups: Sequence[str] | None, + heights: dict[str, float], + *, + group_rule: bool, + cell_pt: float, + scale: float, +) -> None: + """Draw column headings, units, group titles and group rules above the grid.""" + for x, head, unit in zip(lefts, headings, units): + if unit: + ax.annotate( + unit, + (x + 0.5, 0), + xytext=(0, heights["units"]), + textcoords="offset points", + ha="center", + va="bottom", + fontsize=FS_UNIT * scale, + color=MUTED, + annotation_clip=False, + ) + ax.annotate( + head, + (x + 0.5, 0), + xytext=(0, heights["heading"]), + textcoords="offset points", + ha="center", + va="bottom", + fontsize=FS_HEAD * scale, + color=INK, + linespacing=0.95, + annotation_clip=False, + ) + if groups is None: + return + shift = ScaledTranslation(0, heights["rule"] / 72.0, ax.figure.dpi_scale_trans) + j = 0 + while j < len(groups): + k = j + while k + 1 < len(groups) and groups[k + 1] == groups[j]: + k += 1 + centre = 0.5 * (lefts[j] + lefts[k] + 1) + half = max( + 0.5 * (lefts[k] + 1 - lefts[j]) - 0.04, 0.5 * text_width_pt(groups[j], FS_GROUP * scale) / cell_pt + ) + ax.annotate( + groups[j], + (centre, 0), + xytext=(0, heights["group"]), + textcoords="offset points", + ha="center", + va="bottom", + fontsize=FS_GROUP * scale, + color=INK, + annotation_clip=False, + ) + if group_rule: + ax.add_line( + Line2D( + [centre - half, centre + half], + [0, 0], + transform=ax.transData + shift, + color=INK, + linewidth=1.6, + solid_capstyle="butt", + clip_on=False, + ) + ) + j = k + 1 + + +def draw_colorbar( + ax: Axes, + cmap: Colormap, + norm: Normalize, + *, + label: str, + extend: str, + width_in: float, + drop_in: float, + thickness_in: float, + scale: float, +) -> Colorbar: + """Draw a slim horizontal colourbar centred under ``ax``, with ticks at band edges. + + Args: + ax: The grid axes. + cmap: Colormap of the bar. + norm: Norm of the bar; a ``BoundaryNorm`` puts ticks at its band edges. + label: Bar label. + extend: Matplotlib ``extend`` mode. + width_in: Bar length in inches. + drop_in: Distance from the bottom of the grid to the bar, in inches. + thickness_in: Bar thickness in inches. + scale: Font-size factor. + + Returns: + The colourbar. + """ + from matplotlib.cm import ScalarMappable + + fig = ax.figure + cax = fig.add_axes([0, 0, 1, 1]) + + def _place(_ax, renderer): + box = ax.get_window_extent(renderer) + w, h, d = (v * fig.dpi for v in (width_in, thickness_in, drop_in)) + x0 = 0.5 * (box.x0 + box.x1) - 0.5 * w + y0 = box.y0 - d - h + return Bbox.from_bounds(x0, y0, w, h).transformed(fig.transFigure.inverted()) + + cax.set_axes_locator(_place) + sm = ScalarMappable(norm=norm, cmap=cmap) + sm.set_array([]) + kwargs = {} + if isinstance(norm, mcolors.BoundaryNorm): + kwargs = {"ticks": norm.boundaries, "spacing": "uniform", "format": FuncFormatter(_tick_text)} + cb = fig.colorbar(sm, cax=cax, orientation="horizontal", extend=extend, extendfrac=0.05, **kwargs) + cb.outline.set_visible(False) + cb.set_label(label, fontsize=FS_CBAR * scale, color=INK) + cb.ax.tick_params(length=2, width=0.5, labelsize=FS_CBAR_TICK * scale, color=INK, labelcolor=INK) + return cb + + +def _tick_text(value: float, _pos=None) -> str: + """Band-edge tick label with a true minus sign.""" + return f"{value:g}".replace("-", "−") diff --git a/src/nicefigs/palettes.py b/src/nicefigs/palettes.py index 8138aeb..b422e99 100644 --- a/src/nicefigs/palettes.py +++ b/src/nicefigs/palettes.py @@ -424,6 +424,36 @@ def scorecard_diverging_cmap( return cm, norm +def scorecard_skill_cmap( + boundaries: list[float] | None = None, +) -> tuple[mcolors.ListedColormap, mcolors.BoundaryNorm]: + """Discrete ``(cmap, norm)`` for *percent better than a baseline*: blue is better, red worse. + + The same bands, colours and edges as :func:`scorecard_diverging_cmap`, reversed so that + positive values (better) are blue; the pointed ends are dark red below the first edge + and dark blue above the last. This is the default scale of :func:`nicefigs.scorecard`. + + Args: + boundaries: 12 band edges (11 bands), most negative first. Defaults to + :data:`SCORECARD_DIVERGING_BOUNDARIES`. + + Returns: + ``(cmap, norm)`` with under/over colours set, for ``extend="both"``. + + Raises: + ValueError: ``boundaries`` does not have 12 edges. + """ + boundaries = list(boundaries) if boundaries is not None else list(SCORECARD_DIVERGING_BOUNDARIES) + n = len(_SCORECARD_DIVERGING_COLORS) + if len(boundaries) != n + 1: + raise ValueError(f"boundaries must have {n + 1} edges for {n} bands, got {len(boundaries)}") + cm = mcolors.ListedColormap(_SCORECARD_DIVERGING_COLORS[::-1], name="scorecard_skill").with_extremes( + under=_SCORECARD_DIVERGING_OVER, over=_SCORECARD_DIVERGING_UNDER + ) + cm.name = "scorecard_skill" + return cm, mcolors.BoundaryNorm(boundaries, cm.N) + + # --------------------------------------------------------------------------- # # Categorical palettes (land-cover products) # --------------------------------------------------------------------------- # diff --git a/src/nicefigs/panels.py b/src/nicefigs/panels.py index 5083dad..dc10cef 100644 --- a/src/nicefigs/panels.py +++ b/src/nicefigs/panels.py @@ -496,9 +496,7 @@ def outline_boxes( 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) - ) + ax.add_patch(Rectangle((x, y), w, h, fill=False, edgecolor=color, linewidth=linewidth, zorder=zorder)) def facet( diff --git a/src/nicefigs/tables.py b/src/nicefigs/tables.py index 77f3842..3bb651f 100644 --- a/src/nicefigs/tables.py +++ b/src/nicefigs/tables.py @@ -9,7 +9,23 @@ import matplotlib.patches as mpatches import numpy as np +from ._scorecard import ( + FS_CBAR, + FS_CBAR_TICK, + FS_HEAD, + FS_ROW, + FS_VALUE, + NA_TEXT, + draw_colorbar, + draw_header, + header_heights, + text_width_pt, + wrap_heading, +) +from .figure import figure_size from .palettes import cmap as resolve_cmap +from .palettes import scorecard_skill_cmap as resolve_skill_cmap +from .panels import outline_boxes from .style import get_theme from .units import DIRECTIONS, check_direction, prettify_unit @@ -17,9 +33,8 @@ from matplotlib.axes import Axes from matplotlib.colors import Colormap, Normalize from numpy.typing import ArrayLike - -#: Cell side length (inches) used to size the figure when ``square=True``. -_SQUARE_CELL_INCH = 0.34 +#: Cell side (inches) of a scorecard figure created without ``width`` or ``cell_in``. +_DEFAULT_CELL_IN = 0.42 def skill_gap( @@ -29,15 +44,19 @@ def skill_gap( uncertainty: ArrayLike | None = None, direction: str | Sequence[str] = "higher_better", target: ArrayLike = 0.0, + mode: str = "gap", + floor: float = 0.0, ) -> np.ndarray: - """Signed distance of ``values`` from a reference, optionally in units of its uncertainty. + """Signed distance of ``values`` from a reference: raw, in units of its uncertainty, or in percent. Positive is always better, whichever way a metric is read, so one diverging colour scale can carry metrics in different units (see :func:`scorecard`). A ``"target"`` metric is scored by closeness to ``target``: ``|reference - target| - |values - target|``. Dividing by ``uncertainty`` turns each gap into a signal-to-noise ratio: ``-3`` is three error bars - worse than the reference, ``0`` indistinguishable from it. + worse than the reference, ``0`` indistinguishable from it. With ``mode="percent"`` + the gap is ``100 * gap / max(|reference|, floor)`` (``|reference - target|`` for a + ``"target"`` metric): the percent a value is better than its reference. Args: values: ``(n_rows, n_cols)`` metric table; a 1-D input is one row. @@ -48,6 +67,10 @@ def skill_gap( direction: ``"higher_better"``, ``"lower_better"`` or ``"target"``, for the whole table or one per column. target: Value a ``"target"`` metric is best at, broadcast against ``values``. + mode: ``"gap"`` for the raw (or standardised) gap, ``"percent"`` for the gap relative + to the reference. + floor: With ``mode="percent"``, smallest denominator, in the metric's units, so a + reference near zero does not blow the percent up. Zero denominators give ``nan``. Returns: ``(n_rows, n_cols)`` signed gaps, positive where ``values`` beat @@ -55,9 +78,14 @@ def skill_gap( Raises: ValueError: ``values`` and ``reference`` do not broadcast, a per-column - ``direction`` does not label every column, or a direction is not in - :data:`DIRECTIONS`. + ``direction`` does not label every column, a direction is not in + :data:`DIRECTIONS`, ``mode`` is unknown, or ``mode="percent"`` is combined + with ``uncertainty``. """ + if mode not in ("gap", "percent"): + raise ValueError(f"unknown mode {mode!r}; known: ['gap', 'percent']") + if mode == "percent" and uncertainty is not None: + raise ValueError("mode='percent' cannot be combined with an uncertainty") values = np.atleast_2d(np.asarray(values, dtype=float)) try: reference = np.broadcast_to(np.asarray(reference, dtype=float), values.shape) @@ -73,6 +101,7 @@ def skill_gap( raise ValueError(f"unknown direction(s) {unknown}; known: {list(DIRECTIONS)}") gap = np.full(values.shape, np.nan) + scale = np.abs(reference).copy() for j, how in enumerate(directions): if how == "higher_better": gap[:, j] = values[:, j] - reference[:, j] @@ -80,11 +109,16 @@ def skill_gap( gap[:, j] = reference[:, j] - values[:, j] else: # closeness to the target, so positive is still better gap[:, j] = np.abs(reference[:, j] - target[:, j]) - np.abs(values[:, j] - target[:, j]) + scale[:, j] = np.abs(reference[:, j] - target[:, j]) + if mode == "percent": + denom = np.maximum(scale, floor) + with np.errstate(divide="ignore", invalid="ignore"): + return np.where(denom > 0, 100.0 * gap / denom, np.nan) if uncertainty is not None: - scale = np.broadcast_to(np.asarray(uncertainty, dtype=float), values.shape) + unc = np.broadcast_to(np.asarray(uncertainty, dtype=float), values.shape) with np.errstate(divide="ignore", invalid="ignore"): - gap = np.where(np.isfinite(scale) & (scale > 0), gap / scale, np.nan) + gap = np.where(np.isfinite(unc) & (unc > 0), gap / unc, np.nan) return gap @@ -101,6 +135,37 @@ def _cmap_extend(cm: Colormap) -> str: return "neither" +def _group_offsets(groups: Sequence[str] | None, n: int, gap: float) -> tuple[np.ndarray, float]: + """Start of each of ``n`` unit cells along an axis, with ``gap`` before each new group.""" + starts = np.zeros(n) + cur = 0.0 + for k in range(n): + if groups is not None and k > 0 and groups[k] != groups[k - 1]: + cur += gap + starts[k] = cur + cur += 1.0 + return starts, cur + + +def _as_mask(mask: ArrayLike | None, shape: tuple[int, int], name: str) -> np.ndarray: + """Boolean ``shape`` mask from an optional array-like.""" + if mask is None: + return np.zeros(shape, dtype=bool) + out = np.asarray(mask, dtype=bool) + if out.shape != shape: + raise ValueError(f"{name} must have shape {shape}, got {out.shape}") + return out + + +def _is_missing(entry: Any) -> bool: + """Whether a printed entry is absent (a ``nan`` or ``None``).""" + if entry is None: + return True + if isinstance(entry, str): + return False + return not np.isfinite(float(entry)) + + def scorecard( values: ArrayLike, *, @@ -109,100 +174,187 @@ def scorecard( ax: Axes | None = None, direction: Mapping[str, str] | None = None, per_column_norm: bool = True, - highlight_best: bool = True, + highlight_best: bool = False, reference: ArrayLike | None = None, uncertainty: ArrayLike | None = None, target: ArrayLike = 0.0, gap_limit: float = 3.0, + floor: float = 0.0, + color_values: ArrayLike | None = None, + text: ArrayLike | None = None, + reference_row: str | int | None = None, + reference_cells: ArrayLike | None = None, + unresolved: ArrayLike | None = None, + baseline_suffix: str = " (baseline)", cell_format: str = "{:.3g}", + na_text: str = "n/a", col_units: Mapping[str, str] | None = None, - cmap: str | Colormap = "RdYlGn", - na_color: Any = "#eeeeee", - width: float | str = "half", + cmap: str | Colormap | None = None, + na_color: Any = "#e8e8e8", + width: float | str | None = None, + cell_in: float | None = None, + font_scale: float = 1.0, title: str = "", norm: Normalize | None = None, square: bool = False, col_groups: Sequence[str] | None = None, - group_gap: float = 0.6, + group_gap: float = 0.35, + group_rule: bool = True, + row_groups: Sequence[str] | None = None, + row_group_gap: float = 0.35, colorbar: bool = False, - colorbar_label: str = "", + colorbar_label: str | None = None, colorbar_extend: str | None = None, ) -> Axes: - """Render a ``(n_rows, n_cols)`` metric table as a coloured-cell figure. + """Render a ``(n_rows, n_cols)`` metric table as a coloured-cell scorecard. - By default each cell is coloured by its per-column goodness rank (green is - best) and the best cell per column is outlined. ``reference`` colours cells - by :func:`skill_gap` instead, and ``norm`` by their raw value. + Cell text is the raw value; cell colour is the *percent better than a baseline* on the + fixed 11-band scale of :func:`~nicefigs.scorecard_skill_cmap` (blue better, red worse). The + baseline is given as a row (``reference_row``), as one outlined cell per column + (``reference_cells``), as an array (``reference``) or as ready colour values + (``color_values``). Missing values print ``na_text``; ``unresolved`` cells print their + value in grey. Without any baseline, cells are coloured by per-column goodness rank on a + continuous version of the same palette. Columns and rows can be grouped with a gap; + column groups get a title and a rule. + + A ``cmap`` given by name resolves through :func:`~nicefigs.cmap`, where ``"RdBu"`` is + ``RdBu_r`` (red high), so with ``reference`` the better cells come out red; pass + ``matplotlib.colormaps["RdBu"]`` for blue better. Args: - values: Table of shape ``(len(row_labels), len(col_labels))``; ``nan`` - cells are drawn blank in ``na_color``. + values: Raw table of shape ``(len(row_labels), len(col_labels))``; printed unless + ``text`` is given. ``nan`` prints ``na_text`` on a grey cell. row_labels: Row (model) names. - col_labels: Column (metric) names. - ax: Axes to draw on; a new figure is created if ``None``. + col_labels: Column (metric) names; wrapped at spaces to the cell width, or at your + own ``"\\n"``. + ax: Axes to draw on; a new figure sized from the cells is created if ``None``. direction: ``{col_label: direction}`` with values from - :data:`~nicefigs.units.DIRECTIONS`; unlisted columns are - ``"higher_better"``. ``"target"`` ranks by closeness to ``target``. - per_column_norm: Rank each column on its own min→max (else one global - range). Ignored for colour when ``norm`` or ``reference`` is given. - highlight_best: Outline the best cell in each column by the goodness rank. - reference: Values to measure against, broadcast against ``values``. - Cell colour becomes the signed :func:`skill_gap` on one diverging - scale; cell text stays the raw value. - uncertainty: With ``reference``, the scale each gap is divided by. - target: The value a ``"target"`` metric is best at, broadcast against - ``values``. - gap_limit: Gap at which the ``reference`` colour scale saturates. - cell_format: Format string for the cell text. - col_units: ``{col_label: unit}`` shown below the column name. - cmap: Colormap name or object. - na_color: Colour of missing cells. - width: Figure width (preset name or inches) when ``ax`` is ``None``. - title: Left-aligned title. - norm: Normalisation mapping raw ``values`` straight to ``cmap`` (e.g. from - :func:`nicefigs.scorecard_diverging_cmap`). - square: Size the figure from the cell count and force square cells; - only sizes the figure when ``ax`` is ``None``. - col_groups: One group name per column; consecutive equal names form a - group with a gap before it and a bold title above it. - group_gap: Gap before each group, in cell widths. - colorbar: Add a horizontal colorbar below the table. - colorbar_label: Colorbar label. - colorbar_extend: ``"neither"``, ``"min"``, ``"max"`` or ``"both"``; - inferred from ``cmap``'s under/over colours if ``None``. + :data:`~nicefigs.units.DIRECTIONS`; unlisted columns are ``"higher_better"``. + per_column_norm: Rank each column on its own min to max (else one global range); + only for the rank colouring. + highlight_best: Outline the best cell of each column by goodness rank. + reference: Values to measure against, broadcast against ``values``. Colour becomes + :func:`skill_gap` in percent, or in units of ``uncertainty`` if that is given. + uncertainty: With ``reference``, the scale each gap is divided by; the colour scale + is then ``(-gap_limit, gap_limit)`` on the same palette. + target: Value a ``"target"`` metric is best at, broadcast against ``values``. + gap_limit: Standardised gap at which the colour scale saturates. + floor: Smallest percent denominator, see :func:`skill_gap`. + color_values: ``(n_rows, n_cols)`` numbers that colour the cells, normally percent + better than the baseline; ``nan`` gives a grey cell. Overrides ``reference``. + text: ``(n_rows, n_cols)`` printed entries (strings or numbers) instead of ``values``. + reference_row: Row label or index of the baseline row. It is drawn grey with its + raw values inside one outline, gets ``baseline_suffix`` on its label, and + supplies ``reference`` when none is given. Without ``row_groups`` it forms its + own row group. + reference_cells: Boolean mask of per-column reference cells, each outlined and drawn + grey; with one cell per column it also supplies ``reference``. + unresolved: Boolean mask of cells too close to the baseline to resolve; drawn grey with + the value in grey. + baseline_suffix: Appended to the label of ``reference_row``. + cell_format: Format string for numeric cell text. + na_text: Text of a missing cell. + col_units: ``{col_label: unit}`` shown as a second heading line in grey. + cmap: Colormap name or object; default the scale of :func:`~nicefigs.scorecard_skill_cmap`. + na_color: Colour of baseline, missing and unresolved cells. + width: Figure width (preset name or inches) when ``ax`` is ``None``; the cell size is + solved from it. Default: size from ``cell_in``. + cell_in: Cell side in inches when ``ax`` is ``None`` and ``width`` is not given; + default 0.42. + font_scale: Factor on every font size of the card (cell text 7.5 pt, row labels 8 pt, + headings 7 pt, units 6 pt, group titles 9.5 pt, colourbar label 8 pt). + title: Left-aligned title above the header. + norm: Normalisation of the colour numbers. Given alone it maps ``values`` straight to + ``cmap``. + square: Force square cells on a given ``ax``; a new figure has square cells anyway. + col_groups: One group name per column; consecutive equal names form a group with a + gap before it and a title with a rule above it. + group_gap: Gap before each column group, in cell widths. + group_rule: Draw the rule under column group titles. + row_groups: One group name per row; consecutive equal names form a group with a gap + before it. + row_group_gap: Gap before each row group, in cell heights. + colorbar: Add a horizontal colourbar below the grid, about half its width, with ticks at + the band edges and pointed ends. + colorbar_label: Colourbar label; default "% better than the baseline" (or "... than the + outlined reference of the column" with ``reference_cells`` alone). + colorbar_extend: ``"neither"``, ``"min"``, ``"max"`` or ``"both"``; inferred from + ``cmap``'s under/over colours if ``None``. Returns: - The axes. + The axes; one unit is one cell, y grows downwards, and cells are the filled patches. + + Raises: + ValueError: A table or mask has the wrong shape, ``reference_row`` is not a row, the + reference cells do not give one per column, or both ``width`` and ``cell_in`` are + given. """ th = get_theme() values = np.asarray(values, dtype=float) nr, nc = values.shape + if width is not None and cell_in is not None: + raise ValueError("give either width or cell_in, not both") directions = [check_direction((direction or {}).get(c, "higher_better")) for c in col_labels] targets = np.broadcast_to(np.asarray(target, dtype=float), values.shape) - cm = resolve_cmap(cmap) - - lefts = np.zeros(nc) - cur = 0.0 - for j in range(nc): - if col_groups is not None and j > 0 and col_groups[j] != col_groups[j - 1]: - cur += group_gap - lefts[j] = cur - cur += 1.0 - total_w = cur - - if ax is None: - from .figure import subplots - - if square: - fig_w = max(total_w * _SQUARE_CELL_INCH, 1.0) - fig_h = max(nr * _SQUARE_CELL_INCH, 1.0) - _, ax = subplots(width=fig_w, height=fig_h) + labels = [str(r) for r in row_labels] + + ridx = None + if reference_row is not None: + ridx = labels.index(str(reference_row)) if isinstance(reference_row, str) else int(reference_row) + if not 0 <= ridx < nr: + raise ValueError(f"reference_row {reference_row!r} is not one of the {nr} rows") + labels[ridx] += baseline_suffix + ref_cells = _as_mask(reference_cells, values.shape, "reference_cells") + is_ref = ref_cells.copy() + if ridx is not None: + is_ref[ridx, :] = True + unres = _as_mask(unresolved, values.shape, "unresolved") + + # Where the colour numbers come from, and what they mean. + kind = "rank" + cvals = None + if color_values is not None: + cvals = np.asarray(color_values, dtype=float) + if cvals.shape != values.shape: + raise ValueError(f"color_values must have shape {values.shape}, got {cvals.shape}") + kind = "percent" + else: + if reference is None and ridx is not None: + reference = np.broadcast_to(values[ridx], values.shape) + elif reference is None and ref_cells.any(): + if not (ref_cells.sum(axis=0) == 1).all(): + raise ValueError("reference_cells must mark exactly one cell per column") + reference = np.broadcast_to(np.where(ref_cells, values, 0.0).sum(axis=0), values.shape) + if reference is not None: + cvals = skill_gap( + values, + reference, + uncertainty=uncertainty, + direction=directions, + target=target, + mode="gap" if uncertainty is not None else "percent", + floor=floor, + ) + kind = "standardised" if uncertainty is not None else "percent" + elif norm is not None: + cvals, kind = values, "raw" + + skill_cm, skill_norm = resolve_skill_cmap() + if cmap is not None: + cm = resolve_cmap(cmap) + elif kind == "rank": + cm = mcolors.LinearSegmentedColormap.from_list("scorecard_skill_continuous", skill_cm.colors) + else: + cm = skill_cm + if norm is None and cvals is not None: + if kind == "standardised": + norm = mcolors.TwoSlopeNorm(vcenter=0.0, vmin=-gap_limit, vmax=gap_limit) + elif cmap is None: + norm = skill_norm else: - _, ax = subplots(width=width, aspect=max(0.3, 0.12 * nr + 0.12)) - if square: - ax.set_aspect("equal") + norm = mcolors.TwoSlopeNorm(vcenter=0.0, vmin=-50.0, vmax=50.0) - # Goodness in [0, 1] (1 = best); drives `highlight_best` whatever colours the cells. + # Goodness in [0, 1] (1 = best); colours the rank mode and drives `highlight_best`. good = np.full_like(values, 0.5) if per_column_norm: for j in range(nc): @@ -222,49 +374,124 @@ def scorecard( lo, hi = (finite.min(), finite.max()) if finite.size else (0, 1) good = np.zeros_like(values) if hi <= lo else (values - lo) / (hi - lo) - gap = None - if reference is not None: - gap = skill_gap( - values, - reference, - uncertainty=uncertainty, - direction=directions, - target=target, - ) - norm = ( - norm if norm is not None else mcolors.TwoSlopeNorm(vcenter=0.0, vmin=-gap_limit, vmax=gap_limit) + printed = None + if text is not None: + printed = np.empty(values.shape, dtype=object) + printed[...] = np.asarray(text, dtype=object).reshape(values.shape) + + lefts, total_w = _group_offsets(col_groups, nc, group_gap) + row_keys = row_groups + if row_keys is None and ridx is not None: + row_keys = ["ref" if i == ridx else "rest" for i in range(nr)] + tops, total_h = _group_offsets(row_keys, nr, row_group_gap) + + s = font_scale + heads_raw = [str(c) for c in col_labels] + units = [prettify_unit((col_units or {}).get(c)) for c in col_labels] + barlabel = colorbar_label + if barlabel is None: + barlabel = ( + "% better than the outlined reference of the column" + if ridx is None and ref_cells.any() + else "% better than the baseline" + if kind == "percent" + else "" ) + if ax is None: + from .figure import figure + + row_w_pt = max((text_width_pt(lab, FS_ROW * s) for lab in labels), default=0.0) + left_in = (row_w_pt + 6.0 * s) / 72.0 + 0.06 + right_in = 0.12 + cell_for_wrap = cell_in if cell_in is not None else _DEFAULT_CELL_IN + cbar_w = 0.0 + if colorbar: + cbar_w = 2.7 + + def _plan(cell: float): + heads = [wrap_heading(h, FS_HEAD * s, cell * 72.0 * 1.04) for h in heads_raw] + hh = header_heights(heads, any(units), col_groups is not None, s) + top_in = (hh["top"] + 4.0 * s) / 72.0 + (th.fs_title * 1.6 / 72.0 if title else 0.0) + grid_w, grid_h = total_w * cell, total_h * cell + extra = max(0.0, 0.5 * (cbar_w - grid_w)) + 0.06 + l_in, r_in = max(left_in, extra), max(right_in, extra) + bottom_in = (0.22 + 0.11 + (FS_CBAR_TICK + FS_CBAR) * s * 1.4 / 72.0 + 0.1) if colorbar else 0.08 + return heads, hh, grid_w, grid_h, l_in, r_in, top_in, bottom_in + + if width is not None: + w_in = figure_size(width)[0] + cell_for_wrap = _DEFAULT_CELL_IN + for _ in range(3): # wrapping depends on the cell, the margins on the wrapping + _, _, _, _, l_in, r_in, _, _ = _plan(cell_for_wrap) + cell_for_wrap = max((w_in - l_in - r_in) / total_w, 0.05) + heads, hh, grid_w, grid_h, l_in, r_in, top_in, bottom_in = _plan(cell_for_wrap) + fig_w, fig_h = l_in + grid_w + r_in, top_in + grid_h + bottom_in + fig = figure(width=fig_w, height=fig_h) + ax = fig.add_axes([l_in / fig_w, bottom_in / fig_h, grid_w / fig_w, grid_h / fig_h]) + cell_pt = cell_for_wrap * 72.0 + else: + if square: + ax.set_aspect("equal") + fig = ax.figure + box = ax.get_position() + cell_pt = max(fig.get_figwidth() * box.width * 72.0 / total_w, 1.0) + heads = [wrap_heading(h, FS_HEAD * s, cell_pt * 1.04) for h in heads_raw] + hh = header_heights(heads, any(units), col_groups is not None, s) + ax.set_xlim(0, total_w) - ax.set_ylim(0, nr) - ax.invert_yaxis() + ax.set_ylim(total_h, 0) + ax.set_xticks([]) + ax.set_yticks([]) + for sp in ax.spines.values(): + sp.set_visible(False) + face_of = {} for i in range(nr): for j in range(nc): v = values[i, j] - if not np.isfinite(v): - face = na_color - elif gap is not None: - face = na_color if not np.isfinite(gap[i, j]) else cm(norm(gap[i, j])) - elif norm is not None: - face = cm(norm(v)) + entry = printed[i, j] if printed is not None else v + missing = _is_missing(entry) + grey_state = missing or (unres[i, j] and not is_ref[i, j]) + if is_ref[i, j]: + face, ink = na_color, th.spine_color + elif grey_state or (cvals is not None and not np.isfinite(cvals[i, j])): + face, ink = na_color, NA_TEXT + elif cvals is not None: + face, ink = cm(norm(cvals[i, j])), None else: - face = cm(float(np.clip(good[i, j], 0, 1))) + face, ink = cm(float(np.clip(good[i, j], 0, 1))), None + if ink is None: + r, g, b = mcolors.to_rgb(face) + ink = "white" if (0.299 * r + 0.587 * g + 0.114 * b) < 0.5 else th.spine_color + face_of[i, j] = face ax.add_patch( - mpatches.Rectangle((lefts[j], i), 1, 1, facecolor=face, edgecolor="white", linewidth=1.0) - ) - if np.isfinite(v): - r, g, b = face[:3] if isinstance(face, tuple) else (0.5, 0.5, 0.5) - txtcol = "white" if (0.299 * r + 0.587 * g + 0.114 * b) < 0.5 else "#222222" - ax.text( - lefts[j] + 0.5, - i + 0.5, - cell_format.format(v), - ha="center", - va="center", - fontsize=th.fs_annot, - color=txtcol, + mpatches.Rectangle( + (lefts[j], tops[i]), 1, 1, facecolor=face, edgecolor="white", linewidth=1.0 ) + ) + if missing: + label = na_text + elif isinstance(entry, str): + label = entry + else: + label = cell_format.format(float(entry)) + ax.text( + lefts[j] + 0.5, + tops[i] + 0.5, + label, + ha="center", + va="center", + fontsize=FS_VALUE * s, + color=ink, + ) + + boxes = [ + (lefts[j], tops[i], 1.0, 1.0) for i, j in zip(*np.nonzero(ref_cells)) if ridx is None or i != ridx + ] + if ridx is not None: + boxes.append((0.0, tops[ridx], total_w, 1.0)) + outline_boxes(ax, boxes, color="#222222", linewidth=2.0, zorder=6) if highlight_best: for j in range(nc): @@ -274,57 +501,48 @@ def scorecard( bi = int(np.argmax(col_good)) ax.add_patch( mpatches.Rectangle( - (lefts[j], bi), 1, 1, fill=False, edgecolor=th.spine_color, linewidth=1.6, zorder=5 + (lefts[j], tops[bi]), + 1, + 1, + fill=False, + edgecolor=th.spine_color, + linewidth=1.6, + zorder=5, ) ) - ax.set_xticks(lefts + 0.5) - heads = [] - for c in col_labels: - u = (col_units or {}).get(c) - heads.append(f"{c}\n[{prettify_unit(u)}]" if u else c) - ax.set_xticklabels(heads, fontsize=th.fs_tick) - ax.xaxis.set_ticks_position("top") - ax.set_yticks(np.arange(nr) + 0.5) - ax.set_yticklabels(row_labels, fontsize=th.fs_tick) - ax.tick_params(length=0) - for sp in ax.spines.values(): - sp.set_visible(False) - - if col_groups is not None: - import matplotlib.transforms as mtransforms + for i, lab in enumerate(labels): + ax.annotate( + lab, + (0, tops[i] + 0.5), + xytext=(-5.0 * s, 0), + textcoords="offset points", + ha="right", + va="center", + fontsize=FS_ROW * s, + color=th.spine_color, + annotation_clip=False, + ) - blend = mtransforms.blended_transform_factory(ax.transData, ax.transAxes) - j = 0 - while j < nc: - k = j - while k + 1 < nc and col_groups[k + 1] == col_groups[j]: - k += 1 - cx = 0.5 * (lefts[j] + lefts[k] + 1) - ax.text( - cx, - 1.22, - col_groups[j], - transform=blend, - ha="center", - va="bottom", - fontsize=th.fs_tick, - fontweight="bold", - ) - j = k + 1 + draw_header(ax, lefts, heads, units, col_groups, hh, group_rule=group_rule, cell_pt=cell_pt, scale=s) if title: - ax.set_title(title, fontsize=th.fs_title, pad=28 if col_groups is not None else 14, loc="left") + ax.set_title(title, fontsize=th.fs_title, pad=hh["top"] + 4.0 * s, loc="left") if colorbar: - from matplotlib.cm import ScalarMappable - - from .colorbars import colorbar as _draw_colorbar - cb_norm = norm if norm is not None else mcolors.Normalize(vmin=0.0, vmax=1.0) extend = colorbar_extend if colorbar_extend is not None else _cmap_extend(cm) - sm = ScalarMappable(norm=cb_norm, cmap=cm) - sm.set_array([]) - _draw_colorbar(sm, ax, location="bottom", extend=extend, label=colorbar_label) + grid_in = ax.get_position().width * ax.figure.get_figwidth() + draw_colorbar( + ax, + cm, + cb_norm, + label=barlabel, + extend=extend, + width_in=max(0.5 * grid_in, 2.7), + drop_in=0.22, + thickness_in=0.11, + scale=s, + ) return ax diff --git a/tests/test_plots.py b/tests/test_plots.py index 4d4df50..4978711 100644 --- a/tests/test_plots.py +++ b/tests/test_plots.py @@ -137,9 +137,8 @@ def test_scorecard_handles_nan(): plt.close(ax.figure) -def test_scorecard_default_output_unchanged_when_new_kwargs_omitted(): - # Regression contract: the new opt-in kwargs must not move a single cell - # or tick when left at their defaults. +def test_scorecard_default_layout_is_unit_cells_without_gaps_or_colorbar(): + # Without groups the grid is unit cells; the headings are text, not ticks. vals = np.array([[1.0, 0.3], [0.5, 0.8]]) ax = nf.scorecard( vals, row_labels=["m1", "m2"], col_labels=["RMSE", "R2"], direction={"RMSE": "lower_better"} @@ -147,13 +146,11 @@ def test_scorecard_default_output_unchanged_when_new_kwargs_omitted(): try: assert ax.get_xlim() == (0.0, 2.0) # no group gaps, nc == 2 assert ax.get_ylim() == (2.0, 0.0) # inverted - assert ax.get_aspect() not in ("equal", 1.0) # square=False (default) → not forced equal cell_patches = [p for p in ax.patches if p.get_fill()] assert len(cell_patches) == 4 xs = sorted({round(p.get_xy()[0], 6) for p in cell_patches}) assert xs == [0.0, 1.0] # unit-width cells, no gaps - assert [round(t, 3) for t in ax.get_xticks()] == [0.5, 1.5] - assert not any(t.get_fontweight() == "bold" for t in ax.texts) # no group-title row + assert len(ax.lines) == 0 # no group rules assert len(ax.figure.axes) == 1 # no colorbar axes added finally: plt.close(ax.figure) @@ -191,8 +188,9 @@ def test_scorecard_grouped_columns_gap_and_titles(): assert lefts[1] == 1.0 assert lefts[2] == pytest.approx(2.0 + 0.6) assert ax.get_xlim()[1] == pytest.approx(3.0 + 0.6) - titles = sorted(t.get_text() for t in ax.texts if t.get_fontweight() == "bold") + titles = sorted(t.get_text() for t in ax.texts if t.get_text() in ("G1", "G2")) assert titles == ["G1", "G2"] + assert len(ax.lines) == 2 # one rule under each group title finally: plt.close(ax.figure) diff --git a/tests/test_scorecard.py b/tests/test_scorecard.py new file mode 100644 index 0000000..4dcfb79 --- /dev/null +++ b/tests/test_scorecard.py @@ -0,0 +1,343 @@ +"""Contract of the default scorecard: text is the raw value, colour is percent better than a baseline.""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import matplotlib as mpl +import matplotlib.colors as mcolors +import matplotlib.pyplot as plt +import numpy as np +import pytest + +import nicefigs as nf + +BAND_COLORS = [ + "#C4372D", + "#E25C45", + "#EC8869", + "#F1B398", + "#F9DDCE", + "#F2F2F2", + "#DEE9F5", + "#C0D5E9", + "#94BDD9", + "#669CC9", + "#437AB5", +] +EDGES = [-50, -20, -10, -5, -2, -1, 1, 2, 5, 10, 20, 50] + + +def _cells(ax): + """Filled cell patches in reading order.""" + return sorted((p for p in ax.patches if p.get_fill()), key=lambda p: (p.get_xy()[1], p.get_xy()[0])) + + +def _outlines(ax): + return [p for p in ax.patches if not p.get_fill()] + + +def _card(rmse, **kw): + rmse = np.asarray(rmse, dtype=float) + ncol = rmse.shape[1] + cols = [f"c{j}" for j in range(ncol)] + return nf.scorecard( + rmse, + row_labels=["ref"] + [f"m{i}" for i in range(1, rmse.shape[0])], + col_labels=cols, + direction=dict.fromkeys(cols, "lower_better"), + **kw, + ) + + +# ----------------------------------------------------------------- skill_gap percent +def test_percent_gap_is_relative_to_the_reference_and_positive_when_better(): + # lower_better: 90 against a reference of 100 is 10 % better, 120 is 20 % worse + gap = nf.skill_gap([[90.0, 120.0]], [[100.0, 100.0]], direction="lower_better", mode="percent") + assert gap[0] == pytest.approx([10.0, -20.0]) + up = nf.skill_gap([[1.1]], [[1.0]], direction="higher_better", mode="percent") + assert up[0, 0] == pytest.approx(10.0) + + +def test_percent_gap_floor_caps_the_denominator_and_zero_reference_is_nan(): + assert nf.skill_gap([[0.05]], [[0.1]], mode="percent", direction="lower_better", floor=1.0)[0, 0] == ( + pytest.approx(5.0) + ) + assert np.isnan(nf.skill_gap([[1.0]], [[0.0]], mode="percent", direction="lower_better")[0, 0]) + + +def test_percent_gap_of_a_target_metric_is_relative_to_the_reference_distance(): + gap = nf.skill_gap([[1.1]], [[1.4]], mode="percent", direction="target", target=1.0) + assert gap[0, 0] == pytest.approx(100 * (0.4 - 0.1) / 0.4) + + +def test_percent_gap_rejects_uncertainty_and_unknown_modes(): + with pytest.raises(ValueError, match="uncertainty"): + nf.skill_gap([[1.0]], [[1.0]], uncertainty=[[1.0]], mode="percent") + with pytest.raises(ValueError, match="mode"): + nf.skill_gap([[1.0]], [[1.0]], mode="relative") + + +# ------------------------------------------------------------------ the colour scale +@pytest.mark.parametrize( + "percent, band", + [ + (-30, 0), + (-20, 1), + (-7, 2), + (-5, 3), + (-1.5, 4), + (-0.5, 5), + (0, 5), + (1.0, 6), + (3, 7), + (7, 8), + (15, 9), + (30, 10), + ], +) +def test_skill_cmap_maps_percent_to_its_band_with_blue_better(percent, band): + cm, norm = nf.scorecard_skill_cmap() + assert list(norm.boundaries) == EDGES + assert cm(norm(percent)) == pytest.approx(mcolors.to_rgba(BAND_COLORS[band])) + + +def test_skill_cmap_pointed_ends_are_dark_red_worse_and_dark_blue_better(): + cm, norm = nf.scorecard_skill_cmap() + assert cm(norm(-80)) == pytest.approx(mcolors.to_rgba("#9C2520")) + assert cm(norm(80)) == pytest.approx(mcolors.to_rgba("#26549A")) + + +def test_a_cell_is_coloured_by_the_band_of_its_percent_better_than_the_baseline(): + # references 100: values give +30, +7, -0.5, -15, -60 percent (lower is better) + ax = _card([[100.0] * 5, [70.0, 93.0, 100.5, 115.0, 160.0]], reference_row="ref") + faces = [p.get_facecolor() for p in _cells(ax)[5:]] + wanted = ["#437AB5", "#94BDD9", "#F2F2F2", "#E25C45", "#9C2520"] + for got, want in zip(faces, wanted): + assert got == pytest.approx(mcolors.to_rgba(want)) + + +def test_better_cells_are_blue_for_both_directions_of_a_metric(): + vals = np.array([[1.0, 1.0], [0.5, 2.0]]) + ax = nf.scorecard( + vals, + row_labels=["ref", "m"], + col_labels=["err", "score"], + direction={"err": "lower_better", "score": "higher_better"}, + reference_row="ref", + ) + for patch in _cells(ax)[2:]: # +50 % and +100 % better: the pointed-end blue + assert patch.get_facecolor() == pytest.approx(mcolors.to_rgba("#26549A")) + + +def test_a_named_cmap_of_the_registry_flips_rdbu_so_the_object_must_be_passed(): + # nicefigs.cmap("RdBu") is RdBu_r (red = high): with reference= the better cells come out red. + assert nf.cmap("RdBu")(0.99)[0] > nf.cmap("RdBu")(0.99)[2] + vals = np.array([[100.0], [70.0]]) + kw = { + "row_labels": ["ref", "m"], + "col_labels": ["e"], + "direction": {"e": "lower_better"}, + "reference": [[100.0]], + } + by_name = _cells(nf.scorecard(vals, cmap="RdBu", **kw))[1].get_facecolor() + by_object = _cells(nf.scorecard(vals, cmap=mpl.colormaps["RdBu"], **kw))[1].get_facecolor() + assert by_name[0] > by_name[2] # red + assert by_object[2] > by_object[0] # blue: better + + +# --------------------------------------------------------------- baseline and states +def test_reference_row_is_one_outline_around_the_row_and_labelled_baseline(): + ax = _card( + [[1.0, 2.0, 3.0], [0.9, 2.1, 3.0], [1.2, 2.0, 2.0]], reference_row="ref", col_groups=["a", "a", "b"] + ) + boxes = _outlines(ax) + assert len(boxes) == 1 + box = boxes[0] + assert box.get_edgecolor() == pytest.approx(mcolors.to_rgba("#222222")) + assert box.get_linewidth() == pytest.approx(2.0) + assert box.get_xy() == (0.0, 0.0) + assert box.get_width() == pytest.approx(ax.get_xlim()[1]) + assert box.get_height() == pytest.approx(1.0) + labels = [t.get_text() for t in ax.texts] + assert "ref (baseline)" in labels + assert _cells(ax)[0].get_facecolor() == pytest.approx(mcolors.to_rgba("#e8e8e8")) + + +def test_reference_cells_are_outlined_one_by_one_and_supply_the_reference_per_column(): + vals = np.array([[1.0, 2.0], [0.5, 2.5], [1.5, 1.0]]) + mask = np.array([[True, False], [False, False], [False, True]]) + ax = nf.scorecard( + vals, + row_labels=list("abc"), + col_labels=["x", "y"], + direction={"x": "lower_better", "y": "lower_better"}, + reference_cells=mask, + ) + assert len(_outlines(ax)) == 2 + cells = _cells(ax) + # column x is measured against 1.0, column y against 1.0: 0.5 is +50 % -> pointed-end colour + assert cells[2].get_facecolor() == pytest.approx(mcolors.to_rgba("#26549A")) + assert cells[3].get_facecolor() == pytest.approx(mcolors.to_rgba("#9C2520")) + assert cells[0].get_facecolor() == pytest.approx(mcolors.to_rgba("#e8e8e8")) + + +def test_reference_cells_need_exactly_one_cell_per_column(): + with pytest.raises(ValueError, match="one cell per column"): + nf.scorecard( + np.ones((2, 2)), + row_labels=["a", "b"], + col_labels=["x", "y"], + reference_cells=[[True, False], [False, False]], + ) + + +def test_missing_values_print_na_on_grey_and_unresolved_print_their_value_in_grey(): + vals = np.array([[1.0, 1.0, 1.0], [0.5, np.nan, 0.995]]) + ax = _card(vals, reference_row="ref", unresolved=[[False] * 3, [False, False, True]]) + cells = _cells(ax) + texts = [t for t in ax.texts if t.get_text() in ("n/a", "0.995")] + assert sorted(t.get_text() for t in texts) == ["0.995", "n/a"] + for t in texts: + assert t.get_color() == "#8c8c8c" + assert cells[4].get_facecolor() == pytest.approx(mcolors.to_rgba("#e8e8e8")) + assert cells[5].get_facecolor() == pytest.approx(mcolors.to_rgba("#e8e8e8")) + + +def test_text_and_colour_are_separate_tables(): + vals = np.array([[10.0, 10.0], [20.0, 5.0]]) + ax = nf.scorecard( + vals, + row_labels=["a", "b"], + col_labels=["x", "y"], + color_values=[[0.0, 0.0], [-30.0, 30.0]], + text=[["one", "two"], ["red", "blue"]], + ) + cells = _cells(ax) + assert cells[2].get_facecolor() == pytest.approx(mcolors.to_rgba("#C4372D")) + assert cells[3].get_facecolor() == pytest.approx(mcolors.to_rgba("#437AB5")) + printed = {t.get_text() for t in ax.texts} + assert {"one", "two", "red", "blue"} <= printed + assert "20" not in printed + + +def test_a_cell_with_nan_colour_is_grey_even_if_it_has_a_value(): + ax = nf.scorecard(np.array([[3.0]]), row_labels=["a"], col_labels=["x"], color_values=[[np.nan]]) + assert _cells(ax)[0].get_facecolor() == pytest.approx(mcolors.to_rgba("#e8e8e8")) + assert "3" in {t.get_text() for t in ax.texts} + + +# ------------------------------------------------------------------ layout +def test_row_groups_are_separated_by_a_gap_and_the_baseline_is_its_own_group(): + ax = _card([[1.0], [0.9], [0.8]], reference_row="ref") + ys = [p.get_xy()[1] for p in _cells(ax)] + assert ys == pytest.approx([0.0, 1.35, 2.35]) + ax2 = _card([[1.0], [0.9], [0.8], [0.7]], row_groups=["g", "g", "h", "h"], row_group_gap=0.5) + assert [p.get_xy()[1] for p in _cells(ax2)] == pytest.approx([0.0, 1.0, 2.5, 3.5]) + + +def test_column_groups_get_a_title_and_a_1p6pt_rule(): + ax = _card([[1.0, 2.0, 3.0]], col_groups=["G1", "G1", "G2"]) + assert sorted(t.get_text() for t in ax.texts if t.get_text() in ("G1", "G2")) == ["G1", "G2"] + assert [ln.get_linewidth() for ln in ax.lines] == [1.6, 1.6] + ax2 = _card([[1.0, 2.0, 3.0]], col_groups=["G1", "G1", "G2"], group_rule=False) + assert len(ax2.lines) == 0 + + +def test_cells_are_square_at_cell_in_and_default_to_0p42_inches(): + ax = _card([[1.0, 2.0], [1.0, 2.0]]) + fig = ax.figure + fig.canvas.draw() + box = ax.get_window_extent() + assert box.width / fig.dpi == pytest.approx(2 * 0.42) + assert box.height / fig.dpi == pytest.approx(2 * 0.42) + ax3 = _card([[1.0, 2.0]], cell_in=0.6) + ax3.figure.canvas.draw() + assert ax3.get_window_extent().width / ax3.figure.dpi == pytest.approx(1.2) + + +def test_width_solves_the_cell_size_and_conflicts_with_cell_in(): + ax = _card([[1.0, 2.0, 3.0, 4.0]], width=4.0) + assert ax.figure.get_figwidth() == pytest.approx(4.0) + with pytest.raises(ValueError, match="width or cell_in"): + _card([[1.0]], width=4.0, cell_in=0.4) + + +def test_column_headings_wrap_horizontally_with_the_unit_below(): + ax = nf.scorecard( + np.ones((1, 2)), + row_labels=["a"], + col_labels=["surface humidity", "ship"], + col_units={"surface humidity": "ppm", "ship": "ppm"}, + ) + heads = {t.get_text(): t for t in ax.texts} + assert "surface\nhumidity" in heads + assert heads["ship"].get_rotation() == 0 + assert [t.get_text() for t in ax.texts].count("ppm") == 2 + + +def test_text_overlaps_are_clean_for_a_grouped_card_with_colourbar(): + ax = _card( + [[1.0, 2.0, 3.0, 4.0], [0.9, 2.2, 2.0, np.nan], [1.1, 1.9, 3.1, 4.4]], + reference_row="ref", + col_groups=["In situ", "In situ", "Gradient", "Column"], + col_units={"c0": "ppm", "c1": "ppm", "c2": "ppm", "c3": "ppm"}, + colorbar=True, + title="Skill", + ) + assert nf.check_text_overlaps(ax.figure) == [] + + +def test_the_baseline_example_renders_without_text_problems_and_has_the_deck_look(): + path = Path(__file__).parent.parent / "examples" / "34_scorecard_baseline.py" + spec = importlib.util.spec_from_file_location("ex34", path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + fig = mod.make() + assert nf.check_text_overlaps(fig) == [] + ax = fig.axes[0] + assert sum(1 for p in ax.patches if p.get_fill()) == 36 + assert len(_outlines(ax)) == 1 + assert "n/a" not in {t.get_text() for t in ax.texts} + assert [a.get_xlabel() for a in fig.axes[1:]] == ["% better than the baseline"] + + +# ------------------------------------------------------------------ colourbar +def test_colorbar_has_band_edge_ticks_pointed_ends_and_default_label(): + ax = _card([[1.0, 2.0], [0.8, 2.5]], reference_row="ref", colorbar=True) + cax = [a for a in ax.figure.axes if a is not ax][0] + ax.figure.canvas.draw() + labels = [t.get_text() for t in cax.get_xticklabels()] + assert labels == [f"{e:g}".replace("-", "−") for e in EDGES] + assert cax.get_xlabel() == "% better than the baseline" + + +# ---------------------------------------------------------------- compatibility +def test_reference_with_uncertainty_still_scores_in_standard_errors(): + vals = np.array([[1.0], [0.0]]) + ax = nf.scorecard( + vals, + row_labels=["a", "b"], + col_labels=["x"], + direction={"x": "lower_better"}, + reference=[[1.0]], + uncertainty=[[0.25]], # gap of 4 sigma saturates the scale at the pointed-end colour + ) + assert _cells(ax)[1].get_facecolor() == pytest.approx(mcolors.to_rgba("#26549A")) + + +def test_explicit_norm_still_colours_the_raw_values_and_rank_mode_remains_the_fallback(): + cm, norm = nf.scorecard_diverging_cmap() + ax = nf.scorecard(np.array([[-35.0, 60.0]]), row_labels=["m"], col_labels=["a", "b"], cmap=cm, norm=norm) + got = [p.get_facecolor() for p in _cells(ax)] + assert got == [pytest.approx(cm(norm(-35.0))), pytest.approx(cm(norm(60.0)))] + ranked = nf.scorecard(np.array([[1.0], [3.0]]), row_labels=["lo", "hi"], col_labels=["s"]) + lo, hi = (p.get_facecolor() for p in _cells(ranked)) + assert hi[2] > hi[0] # best (highest) cell is blue + assert lo[0] > lo[2] # worst is red + assert _outlines(ranked) == [] # highlight_best defaults to False + + +def test_all_figures_close(): + plt.close("all")