Coverage for app / documents / visuals / chart.py: 98%
176 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""A ```chart fence: bar, grouped, line, area and pie charts.
3Read as fe-core's ``ChartContent`` reads it (``RichMarkdown.tsx``): the x key
4is ``xKey``, else ``x_key``, else ``name``; the series are ``series``, else
5the ``yKey`` shorthand, else every field of the first row but x; each series'
6key is ``key``, ``field`` or ``y_key``, its colour the palette's by position.
7``multibar`` is ``grouped``, and any other type is drawn as bars. Drawn as
8recharts draws it: a dashed grid, bars with their far corners rounded,
9lines without dots, areas at 15% fill, and pie slices labelled
10"name (N%)" with a legend below.
11"""
13from __future__ import annotations
15import math
16from dataclasses import dataclass
17from typing import Any
19from reportlab.graphics.shapes import Drawing, Group, PolyLine, Polygon, Wedge
20from reportlab.lib.colors import Color
22from . import axes
23from .colors import parse_color
24from .fence import VisualError, number, read_object, text
25from .primitives import LegendEntry, label, legend, rounded_bar, rule
26from .registry import Layout, Visual, register_visual
27from .scales import BandScale, LinearScale, nice_ticks
28from .text import ellipsize, js_to_fixed, measure
29from .theme import MUTED, PX, TICK_SIZE, WHITE, Theme, palette
31#: The types fe-core draws (registry ``ChartType``, pinned by the tests).
32CHART_TYPES: tuple[str, ...] = ("bar", "grouped", "line", "area", "pie")
33#: recharts' gap between categories: its default 10%, and 20% for grouped.
34_CATEGORY_GAP = {"grouped": 0.2}
35_BAR_GAP = 2 * PX
36_BAR_RADIUS = 3 * PX
37_LINE_WIDTH = 2 * PX
40@dataclass(frozen=True)
41class Series:
42 key: str
43 label: str
44 color: Color
47@dataclass(frozen=True)
48class ChartSpec:
49 type: str
50 title: str | None
51 rows: list[dict[str, Any]]
52 x_key: str
53 series: list[Series]
56def _first_set(*values: Any) -> Any:
57 """JavaScript's ``a ?? b``: the first that is not null or absent."""
58 return next((v for v in values if v is not None), None)
61@register_visual
62class ChartVisual(Visual):
63 kind = "chart"
64 noun = "Chart"
66 def read(self, source: str) -> ChartSpec:
67 spec = read_object(source)
68 data = spec.get("data")
69 rows = (
70 [r for r in data if isinstance(r, dict)] if isinstance(data, list) else []
71 )
72 if not rows:
73 raise VisualError("it has no data")
74 kind = spec.get("type") or "bar"
75 kind = "grouped" if kind == "multibar" else kind
76 if kind not in CHART_TYPES:
77 kind = "bar"
78 x_key = text(_first_set(spec.get("xKey"), spec.get("x_key"), "name"))
79 shorthand = _first_set(spec.get("yKey"), spec.get("y_key"))
80 raw = spec.get("series")
81 if not isinstance(raw, list):
82 raw = (
83 [{"key": shorthand}]
84 if shorthand
85 else [{"key": k} for k in rows[0] if k != x_key]
86 )
87 series = [
88 Series(
89 key=(
90 key := text(
91 _first_set(
92 s.get("key"), s.get("field"), s.get("y_key"), "value"
93 )
94 )
95 ),
96 label=text(_first_set(s.get("label"), key)) or key,
97 color=parse_color(s.get("color"), palette(i)),
98 )
99 for i, s in enumerate(raw)
100 if isinstance(s, dict)
101 ]
102 title = spec.get("title")
103 out = ChartSpec(
104 kind,
105 text(title) or None if isinstance(title, str) else None,
106 rows,
107 x_key,
108 series,
109 )
110 if kind != "pie":
111 # A field with no number in any row draws nothing in fe-core;
112 # here it is left out of the legend too.
113 drawn = [
114 s for s in series if any(number(r.get(s.key)) is not None for r in rows)
115 ]
116 if not drawn:
117 raise VisualError("it has no numbers to plot")
118 out = ChartSpec(kind, out.title, rows, x_key, drawn)
119 return out
121 def title(self, spec: ChartSpec) -> str | None:
122 return spec.title
124 def layout(
125 self, spec: ChartSpec, width: float, max_height: float, theme: Theme
126 ) -> Layout:
127 if spec.type == "pie":
128 return _pie(spec, width, max_height, theme)
129 return _cartesian(spec, width, max_height, theme)
132def _cartesian(
133 spec: ChartSpec, width: float, max_height: float, theme: Theme
134) -> Layout:
135 height = min(max_height, max(150.0, width * 0.5))
136 rows, series = spec.rows, spec.series
137 swatch = "line" if spec.type == "line" else "square"
138 legend_shapes, legend_height = legend(
139 [LegendEntry(s.label, s.color, swatch) for s in series], width, theme
140 )
141 values = [
142 v for r in rows for s in series if (v := number(r.get(s.key))) is not None
143 ]
144 ticks = nice_ticks(min(0.0, min(values)), max(0.0, max(values)))
145 left = axes.value_axis_width(ticks, theme)
146 plot_width = max(40.0, width - left - 6)
147 band = BandScale(len(rows), left, left + plot_width)
148 categories = axes.fit_categories(
149 [text(r.get(spec.x_key)) for r in rows], band.band, theme
150 )
151 bottom = legend_height + categories.height + 2
152 plot_height = max(60.0, height - bottom - 6)
153 height = bottom + plot_height + 6
154 area = axes.Area(left, bottom, plot_width, plot_height)
155 y = LinearScale(ticks.lo, ticks.hi, area.bottom, area.top)
157 shapes: list[object] = [*axes.value_axis(ticks, area, y, theme)]
158 centres = [band.centre(i) for i in range(len(rows))]
159 for x in centres[:: categories.step]:
160 shapes.append(rule(x, area.bottom, x, area.top, axes.RULE, 0.6, axes.GRID_DASH))
161 shapes.append(axes.base_line(area))
162 zero = y(0.0)
163 if spec.type in ("bar", "grouped"):
164 gap = _CATEGORY_GAP.get(spec.type, 0.1)
165 group = band.band * (1 - gap)
166 bar = max(0.5, (group - _BAR_GAP * (len(series) - 1)) / len(series))
167 for i, row in enumerate(rows):
168 x0 = band.start(i) + band.band * gap / 2
169 for j, s in enumerate(series):
170 value = number(row.get(s.key))
171 if value is None:
172 continue
173 shapes.append(
174 rounded_bar(
175 x0 + j * (bar + _BAR_GAP),
176 bar,
177 zero,
178 y(value),
179 _BAR_RADIUS,
180 s.color,
181 )
182 )
183 else:
184 for s in series:
185 for run in _runs([number(r.get(s.key)) for r in rows]):
186 points = [(centres[i], y(v)) for i, v in run]
187 if spec.type == "area" and len(points) > 1:
188 outline = [*points, (points[-1][0], zero), (points[0][0], zero)]
189 shapes.append(
190 Polygon(
191 [c for p in outline for c in p],
192 fillColor=s.color,
193 fillOpacity=0.15,
194 strokeColor=None,
195 )
196 )
197 if len(points) > 1:
198 shapes.append(
199 PolyLine(
200 [c for p in points for c in p],
201 strokeColor=s.color,
202 strokeWidth=_LINE_WIDTH,
203 strokeLineJoin=1,
204 strokeLineCap=1,
205 )
206 )
207 else:
208 ((x, py),) = points
209 shapes.append(rule(x - 1.5, py, x + 1.5, py, s.color, _LINE_WIDTH))
210 shapes += axes.category_axis(categories, centres, area, theme)
211 drawing = Drawing(width, height)
212 for shape in shapes:
213 drawing.add(shape)
214 drawing.add(_placed(legend_shapes, 0, legend_height))
215 return Layout(drawing, width, height)
218def _runs(values: list[float | None]) -> list[list[tuple[int, float]]]:
219 """Unbroken stretches of values: a line breaks where one is missing."""
220 runs: list[list[tuple[int, float]]] = [[]]
221 for i, v in enumerate(values):
222 if v is None:
223 if runs[-1]:
224 runs.append([])
225 else:
226 runs[-1].append((i, v))
227 return [r for r in runs if r]
230def _placed(shapes: list[object], x: float, y: float) -> Group:
231 group = Group(*shapes)
232 group.translate(x, y)
233 return group
236def _pie_keys(spec: ChartSpec) -> tuple[str, str]:
237 first = spec.rows[0]
238 value_key = (
239 spec.series[0].key
240 if spec.series
241 else next(
242 (
243 k
244 for k, v in first.items()
245 if isinstance(v, (int, float)) and not isinstance(v, bool)
246 ),
247 "value",
248 )
249 )
250 name_key = (
251 spec.x_key
252 if spec.x_key != "name"
253 else next((k for k, v in first.items() if isinstance(v, str)), "name")
254 )
255 return value_key, name_key
258def _pie(spec: ChartSpec, width: float, max_height: float, theme: Theme) -> Layout:
259 value_key, name_key = _pie_keys(spec)
260 slices = [
261 (i, text(row.get(name_key)), value)
262 for i, row in enumerate(spec.rows)
263 if (value := number(row.get(value_key))) is not None and value > 0
264 ]
265 total = sum(v for _, _, v in slices)
266 if not slices or total <= 0:
267 raise VisualError("it has no positive values")
268 font, size = theme.regular, TICK_SIZE
269 labels = [
270 ellipsize(
271 f"{name} ({js_to_fixed(v / total * 100, 0)}%)", font, size, width * 0.28
272 )
273 for _, name, v in slices
274 ]
275 legend_shapes, legend_height = legend(
276 [LegendEntry(name, palette(i)) for i, name, _ in slices], width, theme
277 )
278 widest = max(measure(t, font, size) for t in labels)
279 # recharts' ``outerRadius={100}`` in pixels, smaller where the labels
280 # or the page need it; the drawing just holds the pie and its labels.
281 radius = min(75.0, width / 2 - widest - 24, (max_height - legend_height) / 2 - 22)
282 radius = max(30.0, radius)
283 height = legend_height + 2 * radius + 44
284 cx, cy = width / 2, legend_height + (height - legend_height) / 2
285 shapes: list[object] = []
286 angle = 0.0
287 placed: list[tuple[float, float, bool, str, float, float]] = []
288 for (i, _, value), text_ in zip(slices, labels):
289 sweep = value / total * 360
290 if sweep >= 359.999:
291 shapes.append(
292 Wedge(
293 cx,
294 cy,
295 radius,
296 0,
297 359.999,
298 fillColor=palette(i),
299 strokeColor=WHITE,
300 strokeWidth=1,
301 )
302 )
303 else:
304 shapes.append(
305 Wedge(
306 cx,
307 cy,
308 radius,
309 angle,
310 angle + sweep,
311 fillColor=palette(i),
312 strokeColor=WHITE,
313 strokeWidth=1,
314 )
315 )
316 mid = math.radians(angle + sweep / 2)
317 right = math.cos(mid) >= 0
318 px, py = cx + math.cos(mid) * radius, cy + math.sin(mid) * radius
319 lx, ly = cx + math.cos(mid) * (radius + 12), cy + math.sin(mid) * (radius + 12)
320 placed.append((lx, ly, right, text_, px, py))
321 angle += sweep
322 for side in (True, False):
323 mine = sorted((p for p in placed if p[2] == side), key=lambda p: -p[1])
324 last = math.inf
325 for lx, ly, right, text_, px, py in mine:
326 ly = min(ly, last - (size + 2))
327 last = ly
328 ex = lx + (6 if right else -6)
329 shapes.append(rule(px, py, lx, ly, MUTED, 0.5))
330 shapes.append(rule(lx, ly, ex, ly, MUTED, 0.5))
331 shapes.append(
332 label(
333 ex + (2 if right else -2),
334 ly - size * 0.35,
335 text_,
336 font,
337 size,
338 MUTED,
339 "start" if right else "end",
340 )
341 )
342 drawing = Drawing(width, height)
343 for shape in shapes:
344 drawing.add(shape)
345 drawing.add(_placed(legend_shapes, 0, legend_height))
346 return Layout(drawing, width, height)