Skip to content

Commit ee4ded7

Browse files
authored
feat: line arrows with waypoints, dashed boxes, band (#4)
* feat(diagrams): line arrows with waypoints, dashed and hatched boxes - diagram_arrow(style="line"): stroked connector, filled head in pt; via= corners; linestyle - line arrow join/cap overridable through kwargs - diagram_box(linestyle=, hatch=); rounding=0 -> plain rectangle * feat(lines): band, one shaded range along x or y - lines, timeseries, profile draw their bands through it * fix(diagrams,lines): via as array or None; band takes linewidth - diagram_arrow: via=None default; numpy waypoints no longer raise - band: linewidth overridable through kwargs (was a duplicate-keyword TypeError) - tests: empty/None/array via, default box, band hatch/outline/NaN/descending, bands of lines/timeseries/profile flat and under the lines
1 parent 2a16984 commit ee4ded7

9 files changed

Lines changed: 306 additions & 23 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,18 @@ to [Semantic Versioning](https://semver.org/).
66

77
## [Unreleased]
88

9+
### Added
10+
11+
- `diagram_arrow(style="line")` draws a flowchart connector: a stroked line with a filled
12+
head, sized in points; `via` routes an arrow through corner points and `linestyle` dashes it.
13+
- `diagram_box` takes `linestyle` and `hatch`.
14+
- `band` shades a range between two bounds along x, or up y for a profile, with an optional
15+
legend label; `lines`, `timeseries` and `profile` draw their `bands` with it.
16+
17+
### Changed
18+
19+
- `diagram_box(rounding=0)` draws a plain rectangle, without zero-size corner curves.
20+
921
## [1.1.0] - 2026-11-18
1022

1123
### Added

‎docs/guide/plots.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -517,6 +517,11 @@ nf.diagram_arrow(
517517

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

520+
For the connectors of a flowchart, `style="line"` draws a stroked line with a filled head
521+
instead of a solid shape, `via=[...]` routes the arrow through corner points (only its last
522+
segment carries the head), and `linestyle` dashes it. A box takes `linestyle` too, for a
523+
dashed frame around a group of stages, and `hatch`; `rounding=0` gives it square corners.
524+
520525
## Vertical sections and profiles
521526

522527
[`cross_section()`][nicefigs.cross_section] draws a field over a horizontal
@@ -603,6 +608,10 @@ ax.legend(
603608

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

611+
A band of its own, on any axes, is [`band()`][nicefigs.band]: `nf.band(ax, x, low, high)`
612+
shades over the horizontal coordinate, `along="y"` up the vertical one, and `label=` gives
613+
it a legend entry. `lines`, `timeseries` and `profile` draw their `bands` with it.
614+
606615
## Hovmöller diagrams
607616

608617
[`hovmoller()`][nicefigs.hovmoller] draws a field over time and one spatial

‎src/nicefigs/__init__.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444
from .hovmoller import hovmoller, hovmoller_panels
4545
from .images import heatmap, image, image_grid, overlay_grid, pca_rgb
4646
from .kde import agreement, kde_contours, scatter_regression
47-
from .lines import lines
47+
from .lines import band, lines
4848
from .maps import (
4949
binned_map,
5050
categorical_map,
@@ -232,6 +232,7 @@
232232
"polygon_mesh",
233233
"histogram",
234234
"timeseries",
235+
"band",
235236
"lines",
236237
"spectrum",
237238
"model_comparison",

‎src/nicefigs/diagrams.py‎

Lines changed: 68 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222

2323
from collections.abc import Callable, Mapping, Sequence
2424
from dataclasses import dataclass, field
25-
from typing import TYPE_CHECKING, Any
25+
from typing import TYPE_CHECKING, Any, Literal
2626

2727
import matplotlib as mpl
2828
import matplotlib.colors as mcolors
@@ -162,6 +162,8 @@ def diagram_box(
162162
linewidth: float = 0.5,
163163
rounding: float = 0.05,
164164
textcolor: Any = None,
165+
linestyle: Any = "-",
166+
hatch: str | None = None,
165167
zorder: float = 2.0,
166168
**text_kw: Any,
167169
) -> FancyBboxPatch:
@@ -178,6 +180,8 @@ def diagram_box(
178180
linewidth: Outline width (pt).
179181
rounding: Corner radius, in data units; 0 gives square corners.
180182
textcolor: Text colour; by default dark or white, whichever reads on ``facecolor``.
183+
linestyle: Outline style, e.g. ``"--"`` for a dashed frame around a group.
184+
hatch: Hatch pattern of the fill, e.g. ``"//"``.
181185
zorder: Drawing order of the box; its text draws above.
182186
**text_kw: Forwarded to :meth:`~matplotlib.axes.Axes.text`, e.g. ``fontsize`` or
183187
``fontweight``.
@@ -190,10 +194,12 @@ def diagram_box(
190194
(x - width / 2, y - height / 2),
191195
width,
192196
height,
193-
boxstyle=f"round,pad=0,rounding_size={rounding}",
197+
boxstyle=f"round,pad=0,rounding_size={rounding}" if rounding > 0 else "square,pad=0",
194198
facecolor=facecolor,
195199
edgecolor=edgecolor,
196200
linewidth=linewidth,
201+
linestyle=linestyle,
202+
hatch=hatch,
197203
zorder=zorder,
198204
gid="box",
199205
)
@@ -214,49 +220,96 @@ def diagram_arrow(
214220
color: Any = None,
215221
head_width: float | None = None,
216222
head_length: float | None = None,
223+
style: Literal["filled", "line"] = "filled",
224+
via: Sequence[tuple[float, float]] | np.ndarray | None = None,
225+
linestyle: Any = "-",
217226
label: str = "",
218227
label_offset: tuple[float, float] = (0.0, 0.0),
219228
zorder: float = 3.0,
220229
label_kw: Mapping[str, Any] | None = None,
221230
**kwargs: Any,
222231
) -> FancyArrowPatch:
223-
"""Draw a filled arrow from ``tail`` to ``head``, its shaft ``width`` points wide.
232+
"""Draw an arrow from ``tail`` to ``head``, its shaft ``width`` points wide.
224233
225-
Widths are physical, so arrows keep their shape on axes of any aspect.
234+
Widths are physical, so arrows keep their shape on axes of any aspect. A ``"filled"``
235+
arrow is one solid shape, as a flux whose width carries a value; a ``"line"`` arrow is a
236+
stroked line with a filled head, the connector of a flowchart. With ``via`` the arrow
237+
runs through those points with right-angled or any other corners, and only its last
238+
segment carries the head. Either way the tip ends exactly on ``head``.
226239
227240
Args:
228241
ax: Axes to draw on.
229242
tail: Start, in data coordinates.
230243
head: Tip, in data coordinates.
231-
width: Shaft width (pt).
244+
width: Shaft width (pt); the line width of a ``"line"`` arrow.
232245
color: Fill colour; the text colour by default.
233-
head_width: Head width (pt); by default ``max(3, 2.4 * width)``.
234-
head_length: Head length (pt); by default ``max(2.6, 1.5 * width)``.
235-
label: Text at the arrow's midpoint.
246+
head_width: Head width (pt); by default ``max(3, 2.4 * width)`` for a filled arrow
247+
and ``max(2.4, 3 * width)`` for a line arrow.
248+
head_length: Head length (pt); by default ``max(2.6, 1.5 * width)`` for a filled
249+
arrow and ``max(2.4, 3 * width)`` for a line arrow.
250+
style: ``"filled"`` or ``"line"``.
251+
via: Points the arrow passes through between ``tail`` and ``head``, in data
252+
coordinates.
253+
linestyle: Line style of a ``"line"`` arrow's shaft, e.g. ``"--"``.
254+
label: Text at the midpoint of the arrow's last segment.
236255
label_offset: ``(dx, dy)`` of the label from the midpoint (pt).
237256
zorder: Drawing order; the label draws above.
238257
label_kw: Forwarded to :meth:`~matplotlib.axes.Axes.annotate` for the label,
239258
e.g. ``ha``, ``fontsize`` or ``color``.
240259
**kwargs: Forwarded to :class:`~matplotlib.patches.FancyArrowPatch`, e.g.
241-
``connectionstyle="arc3,rad=0.2"`` for a curved arrow or ``gid``.
260+
``connectionstyle="arc3,rad=0.2"`` for a curved arrow, ``gid``, or
261+
``joinstyle="round"`` and ``capstyle="round"`` for a softer line arrow
262+
(mitred and butt by default).
242263
243264
Returns:
244-
The arrow patch.
265+
The patch of the arrow's last segment, which carries the head.
266+
267+
Raises:
268+
ValueError: If ``style`` is neither ``"filled"`` nor ``"line"``.
245269
"""
246-
hw = max(3.0, 2.4 * width) if head_width is None else head_width
247-
hl = max(2.6, 1.5 * width) if head_length is None else head_length
270+
if style not in ("filled", "line"):
271+
raise ValueError(f"style must be 'filled' or 'line', got {style!r}")
248272
color = mpl.rcParams["text.color"] if color is None else color
273+
if via is not None and len(via):
274+
corners = [tail, *(tuple(p) for p in via)]
275+
xs, ys = zip(*corners, strict=True)
276+
ax.plot(
277+
xs,
278+
ys,
279+
color=color,
280+
linewidth=width,
281+
linestyle=linestyle,
282+
solid_capstyle="butt",
283+
solid_joinstyle="miter",
284+
zorder=zorder,
285+
)
286+
tail = corners[-1]
287+
if style == "filled":
288+
hw = max(3.0, 2.4 * width) if head_width is None else head_width
289+
hl = max(2.6, 1.5 * width) if head_length is None else head_length
290+
arrowstyle = ArrowStyle.Simple(head_length=hl, head_width=hw, tail_width=width)
291+
line_kw: dict[str, Any] = {"linewidth": 0.0}
292+
else:
293+
hl = max(2.4, 3.0 * width) if head_length is None else head_length
294+
hw = hl if head_width is None else head_width
295+
# Matplotlib's "-|>" head width is measured from the shaft to one side.
296+
arrowstyle = ArrowStyle("-|>", head_length=hl, head_width=hw / 2)
297+
line_kw = {
298+
"linewidth": width,
299+
"linestyle": linestyle,
300+
"joinstyle": "miter",
301+
"capstyle": "butt",
302+
}
249303
patch = FancyArrowPatch(
250304
tail,
251305
head,
252-
arrowstyle=ArrowStyle.Simple(head_length=hl, head_width=hw, tail_width=width),
306+
arrowstyle=arrowstyle,
253307
mutation_scale=1.0,
254308
shrinkA=0.0,
255309
shrinkB=0.0,
256310
color=color,
257-
linewidth=0.0,
258311
zorder=zorder,
259-
**kwargs,
312+
**{**line_kw, **kwargs},
260313
)
261314
ax.add_patch(patch)
262315
if label:

‎src/nicefigs/lines.py‎

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
"""Multi-series line plots against a numeric x (sweeps, thresholds, lead times)."""
1+
"""Multi-series line plots against a numeric x (sweeps, thresholds, lead times), and shaded ranges."""
22

33
from __future__ import annotations
44

55
from collections.abc import Mapping
6-
from typing import TYPE_CHECKING, Any
6+
from typing import TYPE_CHECKING, Any, Literal
77

88
import numpy as np
99

@@ -13,9 +13,48 @@
1313

1414
if TYPE_CHECKING:
1515
from matplotlib.axes import Axes
16+
from matplotlib.collections import PolyCollection
1617
from numpy.typing import ArrayLike
1718

1819

20+
def band(
21+
ax: Axes,
22+
x: ArrayLike,
23+
low: ArrayLike,
24+
high: ArrayLike,
25+
*,
26+
along: Literal["x", "y"] = "x",
27+
color: Any = "#888888",
28+
alpha: float = 0.16,
29+
zorder: float = 1.0,
30+
label: str | None = None,
31+
**kwargs: Any,
32+
) -> PolyCollection:
33+
"""Shade the range between ``low`` and ``high`` along a coordinate, such as a spread or an uncertainty.
34+
35+
Args:
36+
ax: Axes to draw on.
37+
x: Coordinate the band runs along: the horizontal one, or with ``along="y"`` the
38+
vertical one, as for a profile against height or pressure.
39+
low: Lower bound at each ``x``; a scalar for a constant bound.
40+
high: Upper bound at each ``x``; a scalar for a constant bound.
41+
along: ``"x"`` for a band over the horizontal coordinate, ``"y"`` for one up the
42+
vertical coordinate.
43+
color: Fill colour.
44+
alpha: Fill opacity.
45+
zorder: Drawing order; below lines by default.
46+
label: Legend label; none by default.
47+
**kwargs: Forwarded to :meth:`~matplotlib.axes.Axes.fill_between`, e.g. ``hatch``, or
48+
``linewidth`` for an outline (none by default).
49+
50+
Returns:
51+
The shaded polygon.
52+
"""
53+
fill = ax.fill_between if along == "x" else ax.fill_betweenx
54+
kw = {"linewidth": 0, **kwargs}
55+
return fill(x, low, high, color=color, alpha=alpha, zorder=zorder, label=label, **kw)
56+
57+
1958
def lines(
2059
x: ArrayLike | Mapping[str, ArrayLike],
2160
series: Mapping[str, ArrayLike],
@@ -101,7 +140,7 @@ def lines(
101140
)
102141
if bands and name in bands:
103142
lo, hi = bands[name]
104-
ax.fill_between(xs, lo, hi, color=cols[name], alpha=band_alpha, linewidth=0, zorder=1)
143+
band(ax, xs, lo, hi, color=cols[name], alpha=band_alpha)
105144

106145
if logx:
107146
ax.set_xscale("log", base=logx_base)

‎src/nicefigs/sections.py‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import numpy as np
99

1010
from .figure import subplots
11+
from .lines import band
1112
from .palettes import cmap as resolve_cmap
1213
from .palettes import qualitative, robust_limits, symmetric_limits
1314
from .style import get_theme
@@ -95,9 +96,7 @@ def profile(
9596
for nm, (low, high) in (bands or {}).items():
9697
low, high = np.asarray(low, dtype=float), np.asarray(high, dtype=float)
9798
yy = np.arange(low.size) if y is None else np.asarray(y, dtype=float)
98-
ax.fill_betweenx(
99-
yy, low, high, color=palette.get(nm, "#888888"), alpha=band_alpha, linewidth=0, zorder=1
100-
)
99+
band(ax, yy, low, high, along="y", color=palette.get(nm, "#888888"), alpha=band_alpha)
101100

102101
for nm in names:
103102
v = np.asarray(profiles[nm], dtype=float)

‎src/nicefigs/timeseries.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from matplotlib.axes import Axes
1414
from numpy.typing import ArrayLike
1515

16+
from .lines import band
1617
from .palettes import qualitative
1718
from .scatter import scatter as _scatter
1819
from .style import get_theme
@@ -155,7 +156,7 @@ def timeseries(
155156
n_bands = len(band_list)
156157
for bi, (lo, hi) in enumerate(band_list):
157158
a = band_alpha * (bi + 1) / n_bands if n_bands > 1 else band_alpha
158-
ax.fill_between(dates, lo, hi, color=cols[name], alpha=a, linewidth=0, zorder=1)
159+
band(ax, dates, lo, hi, color=cols[name], alpha=a)
159160

160161
proxy_handles = []
161162
if obs is not None:

‎tests/test_api_lines.py‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,70 @@ def test_lines_per_series_x_mapping():
1616
assert ax.get_legend() is not None
1717
finally:
1818
plt.close(ax.figure)
19+
20+
21+
def test_a_band_shades_between_its_bounds_along_x():
22+
_, ax = nf.subplots()
23+
x = np.array([0.0, 1.0, 2.0])
24+
band = nf.band(ax, x, [1.0, 1.0, 1.0], [3.0, 4.0, 5.0], label="spread")
25+
ys = band.get_paths()[0].vertices[:, 1]
26+
assert ys.min() == 1.0 and ys.max() == 5.0
27+
assert band.get_label() == "spread"
28+
29+
30+
def test_a_band_along_y_shades_a_profile_range():
31+
"""``along="y"``: the band runs up the vertical coordinate and spans the horizontal one."""
32+
_, ax = nf.subplots()
33+
levels = np.array([1000.0, 500.0, 100.0])
34+
band = nf.band(ax, levels, [0.0, -1.0, -2.0], [2.0, 3.0, 4.0], along="y")
35+
xs, ys = band.get_paths()[0].vertices.T
36+
assert (xs.min(), xs.max()) == (-2.0, 4.0)
37+
assert (ys.min(), ys.max()) == (100.0, 1000.0)
38+
39+
40+
def test_a_band_has_no_edge_and_draws_under_lines():
41+
_, ax = nf.subplots()
42+
band = nf.band(ax, [0, 1], [0, 0], [1, 1])
43+
(line,) = ax.plot([0, 1], [0.5, 0.5])
44+
assert band.get_linewidth()[0] == 0.0 and band.get_zorder() < line.get_zorder()
45+
46+
47+
def test_a_band_takes_a_hatch_and_an_outline_on_request():
48+
_, ax = nf.subplots()
49+
band = nf.band(ax, [0, 1], [0, 0], [1, 1], hatch="//", linewidth=0.8)
50+
assert band.get_hatch() == "//" and band.get_linewidth()[0] == 0.8
51+
52+
53+
def test_a_band_spans_descending_coordinates_and_leaves_gaps_at_nan():
54+
_, ax = nf.subplots()
55+
levels = np.array([1000.0, 700.0, 500.0, 300.0, 100.0])
56+
low = np.array([0.0, np.nan, 1.0, 1.0, 1.0])
57+
band = nf.band(ax, levels, low, low + 1.0, along="y")
58+
ys = np.concatenate([p.vertices[:, 1] for p in band.get_paths()])
59+
assert ys.max() == 1000.0 and ys.min() == 100.0
60+
assert not np.isnan(np.concatenate([p.vertices for p in band.get_paths()])).any()
61+
assert len(band.get_paths()) == 2 # the NaN level splits the band
62+
63+
64+
def _bands(ax):
65+
from matplotlib.collections import PolyCollection
66+
67+
return [c for c in ax.collections if isinstance(c, PolyCollection)]
68+
69+
70+
def test_lines_timeseries_and_profile_draw_their_bands_flat_and_under_the_lines():
71+
x = np.arange(5.0)
72+
drawn = [
73+
nf.lines(x, {"a": x}, bands={"a": (x - 1, x + 1)}),
74+
nf.timeseries(
75+
np.arange("2022-01-01", "2022-01-06", dtype="datetime64[D]"),
76+
{"a": x},
77+
bands={"a": (x - 1, x + 1)},
78+
),
79+
nf.profile({"a": x}, x, bands={"a": (x - 1, x + 1)}),
80+
]
81+
for ax in drawn:
82+
(band,) = _bands(ax)
83+
assert band.get_linewidth()[0] == 0.0
84+
assert band.get_zorder() == 1 and all(line.get_zorder() > 1 for line in ax.lines)
85+
plt.close(ax.figure)

0 commit comments

Comments
 (0)