Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
4 changes: 4 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ and the [Gallery](gallery.md) for runnable examples.

::: nicefigs.palettes

## `nicefigs.shapes`

::: nicefigs.shapes

## `nicefigs.colorbars`

::: nicefigs.colorbars
Expand Down
12 changes: 11 additions & 1 deletion src/nicefigs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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,
Expand Down Expand Up @@ -83,6 +84,8 @@
facet,
grid,
label_panels,
one_to_one,
outline_boxes,
panel_label,
reference_line,
row_labels,
Expand All @@ -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,
Expand Down Expand Up @@ -161,6 +165,8 @@
"clean_title",
"despine",
"reference_line",
"one_to_one",
"outline_boxes",
"facet",
"row_labels",
"col_labels",
Expand Down Expand Up @@ -221,6 +227,10 @@
# relational
"scatter",
"agreement",
"kde_contours",
"scatter_regression",
"polygon_mesh",
"histogram",
"timeseries",
"lines",
"spectrum",
Expand Down
43 changes: 43 additions & 0 deletions src/nicefigs/bars.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
36 changes: 32 additions & 4 deletions src/nicefigs/colorbars.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -30,36 +31,63 @@ 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,
thickness: float = 0.012,
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.
thickness: Bar thickness, in figure fraction.
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"):
Expand Down
132 changes: 132 additions & 0 deletions src/nicefigs/kde.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Loading
Loading