figurekit 0.5.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
figkit/helpers.py ADDED
@@ -0,0 +1,404 @@
1
+ """Small building blocks that keep figures of different projects alike."""
2
+
3
+ from collections.abc import Iterable, Sequence
4
+ from typing import Any, Literal
5
+
6
+ import matplotlib.pyplot as plt
7
+ import numpy as np
8
+ from matplotlib.axes import Axes
9
+ from matplotlib.collections import PolyCollection
10
+ from matplotlib.colors import LinearSegmentedColormap
11
+ from matplotlib.container import BarContainer, ErrorbarContainer
12
+ from matplotlib.figure import Figure
13
+ from matplotlib.legend import Legend
14
+ from matplotlib.text import Annotation, Text
15
+ from matplotlib.ticker import PercentFormatter
16
+
17
+ from figkit.export import WEB_WIDTH
18
+ from figkit.language import headless, localize
19
+ from figkit.theme import DEFAULT, TYPE, Style, Theme
20
+
21
+ Axis = Literal["x", "y"]
22
+
23
+
24
+ def mono(theme: Theme | None = None) -> str:
25
+ """Family of numbers and identifiers: values, feature names, code.
26
+
27
+ Without a theme it is the family of the bundled style.
28
+ """
29
+ return (theme.type if theme is not None else TYPE).mono
30
+
31
+
32
+ def hex_colour(rgba: Sequence[float]) -> str:
33
+ """``#rrggbb`` of an RGB(A) tuple in 0..1, as a colormap returns it."""
34
+ return "#" + "".join(f"{round(v * 255):02x}" for v in rgba[:3])
35
+
36
+
37
+ def _luminance(colour: str) -> float:
38
+ r, g, b = (int(colour[i : i + 2], 16) / 255 for i in (1, 3, 5))
39
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b
40
+
41
+
42
+ def ink_on(colour: str, style: Style | None = None) -> str:
43
+ """Dark or white text, whichever reads better on a fill of ``colour``.
44
+
45
+ The dark text is the darkest ink of ``style``, by default of the bundled style.
46
+ """
47
+ if _luminance(colour) <= 0.5:
48
+ return "#ffffff"
49
+ return min(((style or DEFAULT).themes), key=lambda t: _luminance(t.ink)).ink
50
+
51
+
52
+ def title(ax: Axes, text: str, theme: Theme, subtitle: str | None = None) -> None:
53
+ """Title at the top left of the axes, with an optional line of explanation below it.
54
+
55
+ The subtitle takes the space where :func:`legend_top` would go; with a subtitle, put the
56
+ legend inside the axes. In a headless figure (see :func:`figkit.render`) both are left out,
57
+ because the page shows them.
58
+ """
59
+ if headless():
60
+ return
61
+ size = theme.type
62
+ if subtitle is None:
63
+ ax.set_title(text)
64
+ return
65
+ gap = 6
66
+ ax.set_title(text, pad=gap + size.label * 1.25 + 4)
67
+ ax.annotate(
68
+ subtitle,
69
+ xy=(0, 1),
70
+ xycoords="axes fraction",
71
+ xytext=(0, gap),
72
+ textcoords="offset points",
73
+ va="bottom",
74
+ ha="left",
75
+ fontsize=size.label,
76
+ color=theme.secondary,
77
+ )
78
+
79
+
80
+ def legend_top(ax: Axes, ncols: int | None = None, **kwargs: Any) -> Legend:
81
+ """Legend in one row at the top right, on the line of the title."""
82
+ handles, _ = ax.get_legend_handles_labels()
83
+ return ax.legend(
84
+ loc="lower right",
85
+ bbox_to_anchor=(1.0, 1.0),
86
+ ncols=ncols or len(handles),
87
+ borderaxespad=0.3,
88
+ columnspacing=1.2,
89
+ **kwargs,
90
+ )
91
+
92
+
93
+ def grid(ax: Axes, axis: Axis | Literal["both"] = "y") -> None:
94
+ """Hairline grid along one axis, behind the data."""
95
+ ax.grid(True, axis=axis)
96
+ ax.set_axisbelow(True)
97
+
98
+
99
+ def percent(ax: Axes, axis: Axis = "y", decimals: int = 0) -> None:
100
+ """Show the axis from 0 to 1 as 0 % to 100 %."""
101
+ target = ax.yaxis if axis == "y" else ax.xaxis
102
+ # PercentFormatter puts the sign right after the number; render adds the space of German.
103
+ target.set_major_formatter(PercentFormatter(xmax=1, decimals=decimals))
104
+
105
+
106
+ def category_axis(ax: Axes, axis: Axis = "y") -> None:
107
+ """Axis of category names: no spine and no tick marks, the names stand on their own."""
108
+ ax.tick_params(axis=axis, length=0, pad=6)
109
+ ax.spines["left" if axis == "y" else "bottom"].set_visible(False)
110
+
111
+
112
+ def mono_ticks(ax: Axes, axis: Axis = "y", theme: Theme | None = None) -> None:
113
+ """Set the tick labels of an axis in the mono font, for identifiers such as column names."""
114
+ labels = ax.get_yticklabels() if axis == "y" else ax.get_xticklabels()
115
+ for label in labels:
116
+ label.set_fontfamily(mono(theme))
117
+
118
+
119
+ def value(ax: Axes, x: float, y: float, text: str, theme: Theme, **kwargs: Any) -> Text:
120
+ """A number on the plot, in mono and ink."""
121
+ options: dict[str, Any] = {
122
+ "fontfamily": mono(theme),
123
+ "fontsize": theme.type.annotation,
124
+ "color": theme.ink,
125
+ }
126
+ return ax.text(x, y, text, **(options | kwargs))
127
+
128
+
129
+ def bar_labels(
130
+ ax: Axes,
131
+ bars: BarContainer,
132
+ theme: Theme,
133
+ *,
134
+ labels: Iterable[str] | None = None,
135
+ fmt: str = "{:.2f}",
136
+ padding: float = 3,
137
+ ) -> list[Annotation]:
138
+ """Values at the ends of bars, in mono and in the secondary ink.
139
+
140
+ Values formatted with ``fmt`` follow the language of the figure, ``0,93`` in German; texts
141
+ passed as ``labels`` stay as given.
142
+ """
143
+ texts = (
144
+ list(labels)
145
+ if labels is not None
146
+ else [localize(fmt.format(v)) for v in np.asarray(bars.datavalues)]
147
+ )
148
+ result: list[Annotation] = ax.bar_label(
149
+ bars,
150
+ labels=texts,
151
+ padding=padding,
152
+ fontfamily=mono(theme),
153
+ fontsize=theme.type.annotation,
154
+ color=theme.secondary,
155
+ )
156
+ return result
157
+
158
+
159
+ def reference_line(
160
+ ax: Axes,
161
+ position: float,
162
+ label: str,
163
+ theme: Theme,
164
+ *,
165
+ axis: Axis = "x",
166
+ colour: str | None = None,
167
+ where: float = 1.0,
168
+ side: Literal["left", "right"] = "right",
169
+ ) -> Text:
170
+ """A thin line at a fixed value (threshold, chance level, alert limit) with its label.
171
+
172
+ ``where`` is the position of the label along the line in axes coordinates. The label sits
173
+ above a horizontal line, and on ``side`` of a vertical one; use ``left`` near the right edge.
174
+ """
175
+ line_colour = colour or theme.muted
176
+ small: dict[str, Any] = {"fontsize": theme.type.annotation, "color": theme.secondary}
177
+ if axis == "x":
178
+ ax.axvline(position, color=line_colour, linewidth=1, zorder=1)
179
+ return ax.text(
180
+ position,
181
+ where,
182
+ f" {label}" if side == "right" else f"{label} ",
183
+ transform=ax.get_xaxis_transform(),
184
+ ha="left" if side == "right" else "right",
185
+ va="top",
186
+ **small,
187
+ )
188
+ ax.axhline(position, color=line_colour, linewidth=1, zorder=1)
189
+ return ax.text(
190
+ where,
191
+ position,
192
+ label,
193
+ transform=ax.get_yaxis_transform(),
194
+ ha="right" if where >= 0.5 else "left",
195
+ va="bottom",
196
+ **small,
197
+ )
198
+
199
+
200
+ def line_labels(
201
+ ax: Axes,
202
+ items: Sequence[tuple[float, float, str]],
203
+ theme: Theme,
204
+ *,
205
+ offset: float = 5,
206
+ ) -> list[Annotation]:
207
+ """Names at the ends of lines, pushed apart vertically so that they do not overlap.
208
+
209
+ Direct labels make a legend unnecessary and carry the identity of series whose colour has
210
+ little contrast against the page. The text is in the secondary ink; the line next to it
211
+ carries the colour. Call this after the limits and the figure size are final.
212
+
213
+ Args:
214
+ ax: Axes of the lines.
215
+ items: ``(x, y, text)`` of each line end, in data coordinates.
216
+ theme: Theme of the figure.
217
+ offset: Distance from the line end to the text, in points.
218
+ """
219
+ size = theme.type.annotation
220
+ spacing = size * 1.35
221
+ figure = ax.get_figure()
222
+ dpi = figure.dpi if figure is not None else 72
223
+ wanted = [float(ax.transData.transform((x, y))[1]) * 72 / dpi for x, y, _ in items]
224
+ placed = _spread(wanted, spacing)
225
+ return [
226
+ ax.annotate(
227
+ text,
228
+ xy=(x, y),
229
+ xytext=(offset, placed[i] - wanted[i]),
230
+ textcoords="offset points",
231
+ ha="left",
232
+ va="center",
233
+ fontsize=size,
234
+ color=theme.secondary,
235
+ annotation_clip=False,
236
+ )
237
+ for i, (x, y, text) in enumerate(items)
238
+ ]
239
+
240
+
241
+ def _spread(wanted: Sequence[float], spacing: float) -> list[float]:
242
+ """Positions at least ``spacing`` apart, each group of crowded labels centred on its targets."""
243
+ order = sorted(range(len(wanted)), key=lambda i: wanted[i])
244
+ groups: list[list[int]] = []
245
+ for i in order:
246
+ groups.append([i])
247
+ # Merge with the group below while the two overlap, and centre the merged group again.
248
+ while len(groups) > 1:
249
+ low, high = groups[-2], groups[-1]
250
+ if _start(low, wanted, spacing) + len(low) * spacing <= _start(high, wanted, spacing):
251
+ break
252
+ groups[-2:] = [low + high]
253
+ placed = [0.0] * len(wanted)
254
+ for group in groups:
255
+ start = _start(group, wanted, spacing)
256
+ for k, i in enumerate(group):
257
+ placed[i] = start + k * spacing
258
+ return placed
259
+
260
+
261
+ def _start(group: Sequence[int], wanted: Sequence[float], spacing: float) -> float:
262
+ centre = sum(wanted[i] for i in group) / len(group)
263
+ return centre - (len(group) - 1) * spacing / 2
264
+
265
+
266
+ def ramp_cmap(theme: Theme) -> LinearSegmentedColormap:
267
+ """Colormap of the sequential ramp of ``theme``, from low to high, for heatmaps.
268
+
269
+ Pair it with :func:`ink_on` and :func:`hex_colour` for values on the cells.
270
+ """
271
+ return LinearSegmentedColormap.from_list(f"ramp-{theme.name}", theme.ramp)
272
+
273
+
274
+ def band(
275
+ ax: Axes,
276
+ x: Sequence[float] | np.ndarray[Any, Any],
277
+ low: Sequence[float] | np.ndarray[Any, Any],
278
+ high: Sequence[float] | np.ndarray[Any, Any],
279
+ theme: Theme,
280
+ *,
281
+ slot: int = 0,
282
+ opacity: float = 0.2,
283
+ ) -> PolyCollection:
284
+ """Shaded interval around a line, such as a confidence band, in the colour of series ``slot``.
285
+
286
+ The band has no edge and lies behind the lines, so the line of the same series stays on top.
287
+ """
288
+ return ax.fill_between(
289
+ x, low, high, color=theme.series[slot], alpha=opacity, linewidth=0, zorder=1
290
+ )
291
+
292
+
293
+ def error_bars(
294
+ ax: Axes,
295
+ x: Sequence[float] | np.ndarray[Any, Any],
296
+ y: Sequence[float] | np.ndarray[Any, Any],
297
+ error: Any,
298
+ theme: Theme,
299
+ *,
300
+ axis: Axis = "y",
301
+ colour: str | None = None,
302
+ ) -> ErrorbarContainer:
303
+ """Thin error bars without caps at the points ``(x, y)``, without markers or a line.
304
+
305
+ ``error`` is what :meth:`~matplotlib.axes.Axes.errorbar` takes: one value, one per point or
306
+ a ``(2, n)`` pair of lower and upper distances. ``axis`` is the direction of the bars. The
307
+ colour is the secondary ink, so the bars read as a measure of the marks and not as marks.
308
+ """
309
+ spread = {"yerr" if axis == "y" else "xerr": error}
310
+ return ax.errorbar(
311
+ x,
312
+ y,
313
+ **spread,
314
+ fmt="none",
315
+ ecolor=colour or theme.secondary,
316
+ elinewidth=1,
317
+ capsize=0,
318
+ zorder=3,
319
+ )
320
+
321
+
322
+ def callout(
323
+ ax: Axes,
324
+ text: str,
325
+ xy: tuple[float, float],
326
+ offset: tuple[float, float],
327
+ theme: Theme,
328
+ **kwargs: Any,
329
+ ) -> Annotation:
330
+ """A note that points at ``xy`` with a thin arrow, for an outlier or an event.
331
+
332
+ ``offset`` places the text relative to the point in points, such as ``(30, 20)`` for up and
333
+ to the right, so the note keeps its distance whatever the axis limits are.
334
+ """
335
+ dx, dy = offset
336
+ options: dict[str, Any] = {
337
+ "xytext": offset,
338
+ "textcoords": "offset points",
339
+ "ha": "left" if dx >= 0 else "right",
340
+ "va": "bottom" if dy >= 0 else "top",
341
+ "fontsize": theme.type.annotation,
342
+ "color": theme.secondary,
343
+ "arrowprops": {
344
+ "arrowstyle": "-|>",
345
+ "color": theme.muted,
346
+ "linewidth": 0.8,
347
+ "shrinkA": 2,
348
+ "shrinkB": 3,
349
+ "mutation_scale": 7,
350
+ },
351
+ "annotation_clip": False,
352
+ }
353
+ return ax.annotate(text, xy, **(options | kwargs))
354
+
355
+
356
+ def small_multiples(
357
+ count: int,
358
+ *,
359
+ columns: int = 3,
360
+ height: float = 1.8,
361
+ sharex: bool = True,
362
+ sharey: bool = True,
363
+ ) -> tuple[Figure, list[Axes]]:
364
+ """A grid of ``count`` small charts on the full canvas width that share their axes.
365
+
366
+ Shared axes make the panels comparable at a glance. Inner panels keep their ticks but not
367
+ their tick labels, and cells beyond ``count`` are removed.
368
+
369
+ Args:
370
+ count: Number of panels.
371
+ columns: Panels per row, fewer when ``count`` is smaller.
372
+ height: Height of one row in inches.
373
+ sharex: Share the x axis between all panels.
374
+ sharey: Share the y axis between all panels.
375
+
376
+ Returns:
377
+ The figure and its ``count`` axes, row by row.
378
+
379
+ Raises:
380
+ ValueError: If ``count`` or ``columns`` is less than 1.
381
+ """
382
+ if count < 1 or columns < 1:
383
+ msg = f"small_multiples needs at least one panel and column, got {count} and {columns}"
384
+ raise ValueError(msg)
385
+ columns = min(columns, count)
386
+ rows = -(-count // columns)
387
+ figure, grid_ = plt.subplots(
388
+ rows,
389
+ columns,
390
+ figsize=(WEB_WIDTH, height * rows),
391
+ sharex=sharex,
392
+ sharey=sharey,
393
+ squeeze=False,
394
+ )
395
+ cells = list(grid_.flat)
396
+ for spare in cells[count:]:
397
+ spare.remove()
398
+ panels = cells[:count]
399
+ for index, ax in enumerate(panels):
400
+ # Set both sides explicitly: subplots hides the x labels of every row but the last,
401
+ # yet the last panel of a column keeps them when the row below it is short.
402
+ ax.tick_params(axis="x", labelbottom=not (sharex and index + columns < count))
403
+ ax.tick_params(axis="y", labelleft=not (sharey and index % columns))
404
+ return figure, panels
figkit/language.py ADDED
@@ -0,0 +1,126 @@
1
+ """Languages of figures: the language being drawn, German numbers and figures without a title.
2
+
3
+ :func:`figkit.render` sets the language and the headless mode while a figure is drawn, so the
4
+ helpers can follow them: :func:`number` writes ``0,95`` and ``1.500`` in German, tick labels are
5
+ converted the same way, and :func:`figkit.title` draws nothing in a headless figure, whose page
6
+ shows the title as text. Texts other than numbers come from the project, one table per language.
7
+ """
8
+
9
+ import re
10
+ from collections.abc import Iterator
11
+ from contextlib import contextmanager
12
+ from contextvars import ContextVar
13
+ from typing import Any
14
+
15
+ from matplotlib.category import StrCategoryFormatter
16
+ from matplotlib.figure import Figure
17
+ from matplotlib.ticker import FixedFormatter, Formatter, NullFormatter
18
+
19
+ DEFAULT = "en"
20
+ # Languages whose numbers use a decimal comma, a thousands dot and a space before the percent sign.
21
+ _COMMA = frozenset({"de"})
22
+
23
+ _LANGUAGE: ContextVar[str] = ContextVar("figkit_language", default=DEFAULT)
24
+ _HEADLESS: ContextVar[bool] = ContextVar("figkit_headless", default=False)
25
+
26
+ # A number on its own: not a part of a name such as ResNet18 or AI4I, nor of a version like v0.1.
27
+ # A full stop after it ends a sentence; only a stop followed by a digit continues a version.
28
+ _NUMBER = re.compile(r"(?<![\w.,])(\d{1,3}(?:,\d{3})+|\d+)(\.\d+)?(?!\w|\.\d)")
29
+ _PERCENT = re.compile(r"(\d)%")
30
+
31
+
32
+ def language() -> str:
33
+ """Language of the figure being drawn, ``en`` outside of :func:`figkit.render`."""
34
+ return _LANGUAGE.get()
35
+
36
+
37
+ def headless() -> bool:
38
+ """Whether the figure being drawn leaves out its title, because the page shows it."""
39
+ return _HEADLESS.get()
40
+
41
+
42
+ @contextmanager
43
+ def speaking(code: str | None, *, without_title: bool = False) -> Iterator[None]:
44
+ """Draw in ``code`` (``None`` keeps English) and, if asked, without the title."""
45
+ tokens = (_LANGUAGE.set(code or DEFAULT), _HEADLESS.set(without_title))
46
+ try:
47
+ yield
48
+ finally:
49
+ _HEADLESS.reset(tokens[1])
50
+ _LANGUAGE.reset(tokens[0])
51
+
52
+
53
+ def localize(text: str, code: str | None = None) -> str:
54
+ """The numbers in ``text`` written as in ``code``, by default the current language.
55
+
56
+ English ``1,447.5`` and ``95%`` become German ``1.447,5`` and ``95 %``. Text with mathtext
57
+ (a ``$``) stays as it is, so are digits inside words.
58
+ """
59
+ if (code or language()) not in _COMMA or "$" in text:
60
+ return text
61
+
62
+ def swap(match: re.Match[str]) -> str:
63
+ whole, fraction = match.group(1), match.group(2) or ""
64
+ return whole.replace(",", ".") + fraction.replace(".", ",")
65
+
66
+ return _PERCENT.sub(r"\1 %", _NUMBER.sub(swap, text))
67
+
68
+
69
+ def number(value: float, spec: str = "") -> str:
70
+ """``value`` formatted with ``spec`` as in :func:`format` and written in the current language.
71
+
72
+ ``number(0.781, ".3f")`` is ``0.781`` in English and ``0,781`` in German, ``number(1500, ",")``
73
+ is ``1,500`` and ``1.500``.
74
+ """
75
+ return localize(format(value, spec))
76
+
77
+
78
+ class Localized(Formatter):
79
+ """Tick labels of another formatter with their numbers in the given language."""
80
+
81
+ def __init__(self, inner: Formatter, code: str) -> None:
82
+ self.inner = inner
83
+ self.code = code
84
+
85
+ def set_axis(self, axis: Any) -> None:
86
+ """Attach both formatters to the axis."""
87
+ super().set_axis(axis)
88
+ self.inner.set_axis(axis)
89
+
90
+ def set_locs(self, locs: list[float]) -> None:
91
+ """Pass the tick positions on."""
92
+ self.inner.set_locs(locs)
93
+
94
+ def __call__(self, x: float, pos: int | None = None) -> str:
95
+ """Label of one tick."""
96
+ return localize(self.inner(x, pos), self.code)
97
+
98
+ def format_ticks(self, values: list[float]) -> list[str]:
99
+ """Labels of all ticks."""
100
+ return [localize(text, self.code) for text in self.inner.format_ticks(values)]
101
+
102
+ def get_offset(self) -> str:
103
+ """Offset text of the axis, such as 1e3."""
104
+ return localize(self.inner.get_offset(), self.code)
105
+
106
+ def __getattr__(self, name: str) -> Any:
107
+ # Settings of the inner formatter, such as ScalarFormatter.set_powerlimits.
108
+ return getattr(self.inner, name)
109
+
110
+
111
+ def localize_ticks(figure: Figure, code: str) -> None:
112
+ """Write the numeric tick labels of every axes in ``code``; category names stay as set."""
113
+ if code not in _COMMA:
114
+ return
115
+ for ax in figure.axes:
116
+ for axis in (ax.xaxis, ax.yaxis):
117
+ for get, put in (
118
+ (axis.get_major_formatter, axis.set_major_formatter),
119
+ (axis.get_minor_formatter, axis.set_minor_formatter),
120
+ ):
121
+ inner = get()
122
+ # Names of categories, whether set with labels or plotted as strings, stay as given.
123
+ if not isinstance(
124
+ inner, FixedFormatter | StrCategoryFormatter | NullFormatter | Localized
125
+ ):
126
+ put(Localized(inner, code))