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
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,19 @@ to [Semantic Versioning](https://semver.org/).

## [Unreleased]

### Added

- `flux_diagram` draws a box model's budget: a grid of boxes coloured on a diverging
scale, with sign-aware arrows ∝ √|value| for vertical, horizontal, lateral and ground
fluxes, an optional split of the vertical flux, and per-box notes; `flux_legend`
explains it, and `data.box_budget` gives a closed example budget.
- `diagram_box` and `diagram_arrow`, the labelled box and the point-width arrow
`flux_diagram` is built from, for flowcharts and schematics.
- `profile(bands=...)` shades a range, such as an interquartile range, behind a
profile in its colour.
- `legend_handle` builds a line, marker or band legend entry in the `role_style`
vocabulary.

## [1.0.0] - 2026-11-07

First public release.
Expand Down
4 changes: 4 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ and the [Gallery](gallery.md) for runnable examples.

::: nicefigs.tables

## `nicefigs.diagrams`

::: nicefigs.diagrams

## `nicefigs.sections`

::: nicefigs.sections
Expand Down
Binary file added docs/assets/guide/plots-flowchart.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/assets/guide/plots-flux-diagram-panels.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/assets/guide/plots-flux-diagram.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/assets/guide/plots-profile-band.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
15 changes: 15 additions & 0 deletions docs/gallery.md
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,21 @@ horizontal bar with the colormap's extend triangles.
--8<-- "examples/30_scorecard_diverging.py"
```

## Budgets

### 33 — Flux diagram {#flux-diagram}

[`nicefigs.flux_diagram`][nicefigs.flux_diagram] draws a box model's budget: boxes
coloured by their storage change, lateral inflow on both sides of each box, upward fluxes
between the layers with their convective and mixing parts, and the ground flux, every
arrow ∝ √|value| wide. [`flux_legend`][nicefigs.flux_legend] explains the encoding.

![Flux diagram](gallery/33_flux_diagram.png)

```python
--8<-- "examples/33_flux_diagram.py"
```

## Vertical structure

### 22 — Cross-section / curtain {#cross-section}
Expand Down
Binary file added docs/gallery/33_flux_diagram.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
133 changes: 133 additions & 0 deletions docs/guide/plots.md
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,107 @@ nf.stacked_bars(

![Grouped and stacked bars](../assets/guide/plots-bars.png)

## Box-and-arrow diagrams

[`flux_diagram()`][nicefigs.flux_diagram] draws the budget of a box model: a grid of
boxes, rows stacked bottom first and columns side by side, each coloured and labelled by
its value on a diverging scale, with an arrow for every flux between them. Arrows point
the way the flux goes and are ∝ √|value| wide, in points, on one scale per kind of flux.

```python
import nicefigs as nf
from nicefigs import data

nf.set_theme("paper")
b = data.box_budget(n_rows=2, n_cols=3)
ax, diagram = nf.flux_diagram(
b["storage"],
vertical=b["vertical"],
ground=b["ground"],
row_labels=["Lower", "Upper"],
col_labels=["West", "Centre", "East"],
width="full",
)
print(len(diagram.of_kind("vertical")), "vertical and", len(diagram.of_kind("ground")), "ground arrows")
```

```text
3 vertical and 3 ground arrows
```

![Flux diagram](../assets/guide/plots-flux-diagram.png)

`vertical` flows from row `k` up into row `k + 1`, `ground` from the hatched ground into
the bottom row, and `horizontal` from column `j` into column `j + 1`; a negative value
reverses the arrow. `lateral` is a net inflow through a box's sides, such as a
convergence: it draws an arrow on both sides, in when positive, and prints the value
inside the box. `parts` splits each vertical flux into named shares printed beside it.

Box `(k, j)` is centred at `x = j + 0.5`, `y = k` in data coordinates, so further
annotation goes straight onto `ax`. The returned
[`FluxDiagram`][nicefigs.FluxDiagram] holds the colour `mappable` for
[`colorbar()`][nicefigs.colorbar], and [`flux_legend()`][nicefigs.flux_legend] explains
the colours:

```python
import nicefigs as nf
from nicefigs import data

nf.set_theme("paper")
b = data.box_budget()
fig, (top, bottom) = nf.subplots(2, 1, width="double", aspect=0.75, height_ratios=[3, 1], hspace=0.15)
reference = {"lateral": 30.0, "ground": 2.0}
norm = nf.diverging_norm(-0.6, 0.6)
_, diagram = nf.flux_diagram(
b["storage"], ax=top, lateral=b["lateral"], vertical=b["vertical"], ground=b["ground"],
parts=b["parts"], row_labels=b["row_labels"], norm=norm, reference=reference,
)
nf.flux_diagram(
b["storage"].sum(0, keepdims=True), ax=bottom, lateral=b["lateral"].sum(0, keepdims=True),
ground=b["ground"], row_labels=["Column"], col_labels=b["col_labels"], norm=norm, reference=reference,
)
nf.colorbar(diagram.mappable, bottom, location="bottom", pad=0.03, shrink=0.5, label="storage change")
nf.flux_legend(
diagram,
{"box": "storage change", "lateral": "lateral inflow", "vertical": "upward flux", "ground": "ground flux"},
parts={"c": "convective", "m": "mixing"},
target=fig, loc="upper center", bbox_to_anchor=(0.5, 0.02), ncol=3,
)
```

![Two flux diagrams sharing colours and widths](../assets/guide/plots-flux-diagram-panels.png)

Passing one `norm` and one `reference` to both panels puts their colours and arrow widths
on the same scale; by default each diagram scales to its own largest value.

[`diagram_box()`][nicefigs.diagram_box] and [`diagram_arrow()`][nicefigs.diagram_arrow]
are the pieces `flux_diagram` is built from; place them anywhere for a flowchart or a
schematic. Positions are data coordinates and arrow widths are points, so the drawing
keeps its shape whatever the axes' aspect:

```python
import nicefigs as nf

nf.set_theme("paper")
fig, ax = nf.subplots(width="full", aspect=0.3)
ax.set_xlim(0, 4)
ax.set_ylim(-0.5, 0.75)
ax.set_axis_off()
steps = ["meteorology", "transport", "observation\noperator", "scores"]
for i, step in enumerate(steps):
nf.diagram_box(ax, (i + 0.5, 0), 0.7, 0.4, text=step, facecolor="#dbe6f1")
if i:
nf.diagram_arrow(ax, (i - 0.15, 0), (i + 0.15, 0), width=1.2)
nf.diagram_arrow(
ax, (3.5, 0.22), (1.5, 0.22), width=0.8, connectionstyle="arc3,rad=0.25",
label="tune", label_offset=(0, 12),
)
```

![A flowchart](../assets/guide/plots-flowchart.png)

A `connectionstyle` curves an arrow; `label` and `label_offset` place text at its midpoint.

## Vertical sections and profiles

[`cross_section()`][nicefigs.cross_section] draws a field over a horizontal
Expand Down Expand Up @@ -470,6 +571,38 @@ ax = nf.profile(

![Vertical profiles](../assets/guide/plots-profile.png)

`bands={name: (low, high)}` shades a range behind the profile of the same name, in its
colour, e.g. the interquartile range of observations around their median. Bands add no
legend entry; [`legend_handle()`][nicefigs.legend_handle] makes one:

```python
import nicefigs as nf
from nicefigs import data

nf.set_theme("paper")
vp = data.vertical_profiles(names=["observed"])
median = vp["profiles"]["observed"]
ax = nf.profile(
{"observed": median},
vp["levels"],
bands={"observed": (median - 1.5, median + 1.0)},
colors={"observed": "#4477AA"},
xlabel="CO₂",
xunits="ppmv",
ylabel="pressure",
yunits="hPa",
width="half",
)
ax.legend(
handles=[
nf.legend_handle("observed median", "both", color="#4477AA", marker="o", markersize=3),
nf.legend_handle("observed 25–75 %", "band", color="#4477AA", alpha=0.25),
]
)
```

![A profile with its interquartile band](../assets/guide/plots-profile-band.png)

## Hovmöller diagrams

[`hovmoller()`][nicefigs.hovmoller] draws a field over time and one spatial
Expand Down
4 changes: 4 additions & 0 deletions docs/guide/styling.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,10 @@ a variant of a method the open marker (`filled=False`).
needed for graphics. Label null curves directly; the grey never carries
meaning alone.

[`legend_handle()`][nicefigs.legend_handle] builds a legend entry in the same
vocabulary, for an entry no plotted artist carries, e.g.
`nf.legend_handle("seed range", "band", **nf.role_style("null", "band"))`.

Map your methods to roles once, e.g. `{"unet": "primary", "persistence":
"contrast"}`, and every figure inherits the same colours.

Expand Down
45 changes: 45 additions & 0 deletions examples/33_flux_diagram.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""Flux diagram: a closed three-layer box budget with lateral, vertical and ground fluxes."""

import nicefigs as nf
from nicefigs import data


def make():
nf.set_theme("paper")
b = data.box_budget()
fig, ax = nf.subplots(width="double", aspect=0.5)
ax, diagram = nf.flux_diagram(
b["storage"],
ax=ax,
lateral=b["lateral"],
vertical=b["vertical"],
ground=b["ground"],
parts=b["parts"],
row_labels=b["row_labels"],
col_labels=b["col_labels"],
col_title="Region",
)
nf.colorbar(
diagram.mappable, ax, location="bottom", pad=0.04, shrink=0.5, label="storage change [Tg yr⁻¹]"
)
nf.flux_legend(
diagram,
{
"box": "box colour, upper number: storage change",
"lateral": "lateral inflow (arrows in > 0)",
"vertical": "upward flux (up > 0)",
"ground": "ground flux (up > 0)",
},
parts={"c": "convective part", "m": "mixing part"},
loc="upper center",
bbox_to_anchor=(0.5, -0.2),
ncol=2,
)
return fig


if __name__ == "__main__":
import matplotlib

matplotlib.use("Agg")
nf.save(make(), "33_flux_diagram", formats=("png", "pdf"))
18 changes: 18 additions & 0 deletions src/nicefigs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,15 @@
hsv_legend,
)
from .comparison import model_comparison
from .diagrams import (
FLUX_COLORS,
FluxArrow,
FluxDiagram,
diagram_arrow,
diagram_box,
flux_diagram,
flux_legend,
)
from .figure import TextIssue, check_text_overlaps, figure, figure_size, save, subplots
from .hovmoller import hovmoller, hovmoller_panels
from .images import heatmap, image, image_grid, overlay_grid, pca_rgb
Expand Down Expand Up @@ -59,6 +68,7 @@
cmap,
diverging_norm,
elevation_cmap,
legend_handle,
qualitative,
robust_limits,
role_color,
Expand Down Expand Up @@ -172,6 +182,7 @@
"Role",
"role_color",
"role_style",
"legend_handle",
# artist palettes
"artist_palette",
"artist_cmap",
Expand Down Expand Up @@ -221,6 +232,13 @@
"stacked_bars",
"scorecard",
"skill_gap",
"diagram_box",
"diagram_arrow",
"flux_diagram",
"flux_legend",
"FluxDiagram",
"FluxArrow",
"FLUX_COLORS",
"DIRECTIONS",
"cross_section",
"cross_section_panels",
Expand Down
47 changes: 47 additions & 0 deletions src/nicefigs/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -579,3 +579,50 @@ def eigen_spectra(
x -= x.mean(axis=0)
out[nm] = np.linalg.eigvalsh(x.T @ x / (n_samples - 1))[::-1]
return out


def box_budget(
*,
seed: int = 41,
n_rows: int = 3,
n_cols: int = 5,
) -> dict[str, Any]:
"""A closed budget of a grid of boxes, for :func:`nicefigs.flux_diagram`.

Rows are stacked layers, bottom first, and columns sit side by side. Every box closes:
its storage change is its lateral inflow plus the vertical flux through its bottom
minus the one through its top, plus the ground flux for the bottom row.

Args:
seed: Random seed.
n_rows: Number of layers.
n_cols: Number of columns.

Returns:
``storage`` and ``lateral`` of shape ``(n_rows, n_cols)``; ``vertical``, upward
through the top of every row but the last, of shape ``(n_rows - 1, n_cols)``;
``ground``, upward into the bottom row, of shape ``(n_cols,)``; ``parts``, the
mixing (``"m"``) and convective (``"c"``) shares of ``vertical``; and
``row_labels`` and ``col_labels``.
"""
rng = _rng(seed)
x = np.linspace(-1.0, 1.0, n_cols)
storage = np.round(rng.normal(0.0, 0.4, (n_rows, n_cols)), 2)
shape = np.sin(np.pi * (x[None, :] + rng.uniform(0.2, 0.6, (n_rows - 1, 1))))
vertical = np.round(30 * shape * rng.uniform(0.3, 1.0, (n_rows - 1, 1)), 1)
ground = np.round(rng.normal(0.0, 2.0, n_cols), 2)
up_in = np.vstack([ground[None, :], vertical])
up_out = np.vstack([vertical, np.zeros((1, n_cols))])
lateral = storage - up_in + up_out
convective = np.round(vertical * rng.uniform(0.0, 0.05, vertical.shape), 2)
mixing = np.round(vertical * rng.uniform(0.0, 0.02, vertical.shape), 2)
return {
"storage": storage,
"lateral": lateral,
"vertical": vertical,
"ground": ground,
"parts": {"c": convective, "m": mixing},
"row_labels": ["Boundary layer", "Free troposphere", "Stratosphere"][:n_rows]
+ [f"Layer {k + 1}" for k in range(3, n_rows)],
"col_labels": [f"Column {j + 1}" for j in range(n_cols)],
}
Loading
Loading