Coverage for app / documents / visuals / plot.py: 98%

172 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1"""A ```plot fence: scatter, line and histogram plots. 

2 

3Read as fe-core's ``PlotContent`` reads it (``RichMarkdown.tsx``): any type 

4but ``histogram`` draws points, joined in the order given for ``line``; a 

5histogram bins ``data`` (else the series' y values) into ``bins`` (2–50, 

6default 10) equal-width buckets labelled by their lower edge; a best-fit 

7line (scatter only) is the least-squares line across the series' x range, 

8dashed. ``_hist_bins`` and ``_linear_regression`` are ports of fe-core's 

9``_histBins`` and ``_linearRegression``. 

10""" 

11 

12from __future__ import annotations 

13 

14import math 

15from dataclasses import dataclass 

16 

17from reportlab.graphics.shapes import Circle, Drawing, Group, PolyLine 

18from reportlab.lib.colors import Color 

19 

20from . import axes 

21from .colors import parse_color 

22from .fence import VisualError, number, read_object, text 

23from .primitives import LegendEntry, legend, rounded_bar, rule 

24from .registry import Layout, Visual, register_visual 

25from .scales import BandScale, LinearScale, nice_ticks 

26from .text import js_to_fixed 

27from .theme import LABEL_SIZE, PX, TICK_SIZE, Theme, palette 

28 

29#: The types fe-core draws (registry ``PlotType``, pinned by the tests). 

30PLOT_TYPES: tuple[str, ...] = ("scatter", "line", "histogram") 

31_MARKER = 3.4 

32_FIT_DASH = (5 * PX, 3 * PX) 

33#: The most points a plot draws, and the most values a histogram bins. 

34MAX_POINTS = 20_000 

35MAX_VALUES = 100_000 

36 

37 

38@dataclass(frozen=True) 

39class PlotSeries: 

40 name: str 

41 points: list[tuple[float, float]] 

42 color: Color 

43 best_fit: bool 

44 

45 

46@dataclass(frozen=True) 

47class PlotSpec: 

48 type: str 

49 title: str | None 

50 x_title: str 

51 y_title: str 

52 series: list[PlotSeries] 

53 values: list[float] 

54 bins: int 

55 

56 

57def _hist_bins(values: list[float], k: int) -> list[tuple[str, int]]: 

58 if not values: 

59 return [] 

60 lo, hi = min(values), max(values) 

61 w = (hi - lo) / k or 1 

62 out = [[js_to_fixed(lo + i * w, 2), 0] for i in range(k)] 

63 for v in values: 

64 out[min(math.floor((v - lo) / w), k - 1)][1] += 1 

65 return [(name, count) for name, count in out] 

66 

67 

68def _linear_regression( 

69 points: list[tuple[float, float]], 

70) -> tuple[tuple[float, float], tuple[float, float]] | None: 

71 n = len(points) 

72 if n < 2: 

73 return None 

74 sx = sy = sxy = sx2 = 0.0 

75 for x, y in points: 

76 sx += x 

77 sy += y 

78 sxy += x * y 

79 sx2 += x * x 

80 d = n * sx2 - sx * sx 

81 if abs(d) < 1e-10: 

82 return None 

83 b = (n * sxy - sx * sy) / d 

84 a = (sy - b * sx) / n 

85 xs = [x for x, _ in points] 

86 x0, x1 = min(xs), max(xs) 

87 return (x0, a + b * x0), (x1, a + b * x1) 

88 

89 

90def _bins(value: object) -> int: 

91 count = number(value) 

92 return 10 if count is None else max(2, min(50, math.floor(count))) 

93 

94 

95def _flag(value: object) -> bool | None: 

96 return value if isinstance(value, bool) else None 

97 

98 

99@register_visual 

100class PlotVisual(Visual): 

101 kind = "plot" 

102 noun = "Plot" 

103 

104 def read(self, source: str) -> PlotSpec: 

105 spec = read_object(source) 

106 kind = spec.get("type") or "scatter" 

107 kind = kind if kind in PLOT_TYPES else "scatter" 

108 title = spec.get("title") 

109 raw = spec.get("series") if isinstance(spec.get("series"), list) else [] 

110 overall_fit = _flag(spec.get("bestFit")) 

111 series: list[PlotSeries] = [] 

112 for i, s in enumerate(raw): 

113 if not isinstance(s, dict): 

114 continue 

115 points = [ 

116 (x, y) 

117 for p in (s.get("data") or []) 

118 if isinstance(p, list) 

119 and len(p) >= 2 

120 and (x := number(p[0])) is not None 

121 and (y := number(p[1])) is not None 

122 ] 

123 fit = _flag(s.get("bestFit")) 

124 series.append( 

125 PlotSeries( 

126 text(s.get("name")) or f"Series {i + 1}", 

127 points, 

128 parse_color(s.get("color"), palette(i)), 

129 bool(fit if fit is not None else overall_fit), 

130 ) 

131 ) 

132 values: list[float] = [] 

133 if kind == "histogram": 

134 data = spec.get("data") 

135 if isinstance(data, list) and data: 

136 values = [ 

137 float(v) 

138 for v in data 

139 if isinstance(v, (int, float)) 

140 and not isinstance(v, bool) 

141 and math.isfinite(v) 

142 ] 

143 else: 

144 values = [y for s in series for _, y in s.points] 

145 if not values: 

146 raise VisualError("it has no data") 

147 if len(values) > MAX_VALUES: 

148 raise VisualError(f"it has more than {MAX_VALUES:,} values") 

149 else: 

150 if not any(s.points for s in series): 

151 raise VisualError("it has no data") 

152 if sum(len(s.points) for s in series) > MAX_POINTS: 

153 raise VisualError(f"it has more than {MAX_POINTS:,} points") 

154 return PlotSpec( 

155 kind, 

156 text(title) or None if isinstance(title, str) else None, 

157 text(spec.get("xlabel")), 

158 text(spec.get("ylabel")), 

159 series, 

160 values, 

161 _bins(spec.get("bins")), 

162 ) 

163 

164 def title(self, spec: PlotSpec) -> str | None: 

165 return spec.title 

166 

167 def layout( 

168 self, spec: PlotSpec, width: float, max_height: float, theme: Theme 

169 ) -> Layout: 

170 if spec.type == "histogram": 

171 return _histogram(spec, width, max_height, theme) 

172 return _points(spec, width, max_height, theme) 

173 

174 

175def _frame( 

176 spec: PlotSpec, 

177 width: float, 

178 max_height: float, 

179 legend_height: float, 

180 x_height: float, 

181 left: float, 

182) -> tuple[axes.Area, float, float]: 

183 """The plot area, the drawing's height and where the x title sits.""" 

184 height = min(max_height, max(160.0, width * 0.54)) 

185 x_title_height = LABEL_SIZE + 4 if spec.x_title else 0.0 

186 y_title_width = LABEL_SIZE + 6 if spec.y_title else 0.0 

187 bottom = legend_height + x_title_height + x_height + 2 

188 plot_height = max(60.0, height - bottom - 6) 

189 height = bottom + plot_height + 6 

190 left += y_title_width 

191 area = axes.Area(left, bottom, max(40.0, width - left - 8), plot_height) 

192 return area, height, legend_height + 3 

193 

194 

195def _histogram(spec: PlotSpec, width: float, max_height: float, theme: Theme) -> Layout: 

196 bins = _hist_bins(spec.values, spec.bins) 

197 ticks = nice_ticks(0.0, float(max(c for _, c in bins))) 

198 left = axes.value_axis_width(ticks, theme) 

199 probe = BandScale(len(bins), left, width - 8) 

200 categories = axes.fit_categories([name for name, _ in bins], probe.band, theme) 

201 area, height, x_title_y = _frame( 

202 spec, width, max_height, 0.0, categories.height, left 

203 ) 

204 band = BandScale(len(bins), area.left, area.right) 

205 y = LinearScale(ticks.lo, ticks.hi, area.bottom, area.top) 

206 shapes: list[object] = [ 

207 *axes.value_axis(ticks, area, y, theme), 

208 axes.base_line(area), 

209 ] 

210 gap = band.band * 0.1 

211 for i, (_, count) in enumerate(bins): 

212 if count: 

213 shapes.append( 

214 rounded_bar( 

215 band.start(i) + gap / 2, 

216 band.band - gap, 

217 y(0), 

218 y(count), 

219 3 * PX, 

220 palette(0), 

221 ) 

222 ) 

223 centres = [band.centre(i) for i in range(len(bins))] 

224 shapes += axes.category_axis(categories, centres, area, theme) 

225 shapes += axes.axis_titles(spec.x_title, spec.y_title, area, x_title_y, theme) 

226 return _drawn(shapes, width, height) 

227 

228 

229def _domain(values: list[float]) -> tuple[float, float]: 

230 """recharts' number axis: ``[0, 'auto']``, extended to take the data.""" 

231 return min(0.0, min(values)), max(0.0, max(values)) 

232 

233 

234def _points(spec: PlotSpec, width: float, max_height: float, theme: Theme) -> Layout: 

235 drawn = [s for s in spec.series if s.points] 

236 swatch = "line" if spec.type == "line" else "square" 

237 legend_shapes, legend_height = legend( 

238 [LegendEntry(s.name, s.color, swatch) for s in drawn], width, theme 

239 ) 

240 xs = [x for s in drawn for x, _ in s.points] 

241 ys = [y for s in drawn for _, y in s.points] 

242 fits = { 

243 s.name: _linear_regression(s.points) 

244 for s in drawn 

245 if spec.type == "scatter" and s.best_fit 

246 } 

247 for fit in fits.values(): 

248 if fit: 

249 ys += [fit[0][1], fit[1][1]] 

250 x_ticks, y_ticks = nice_ticks(*_domain(xs)), nice_ticks(*_domain(ys)) 

251 left = axes.value_axis_width(y_ticks, theme) 

252 area, height, x_title_y = _frame( 

253 spec, width, max_height, legend_height, TICK_SIZE + 6, left 

254 ) 

255 x = LinearScale(x_ticks.lo, x_ticks.hi, area.left, area.right) 

256 y = LinearScale(y_ticks.lo, y_ticks.hi, area.bottom, area.top) 

257 shapes: list[object] = [ 

258 *axes.value_axis(y_ticks, area, y, theme), 

259 *axes.numeric_axis(x_ticks, area, x, theme), 

260 axes.base_line(area), 

261 ] 

262 for s in drawn: 

263 placed = [(x(px), y(py)) for px, py in s.points] 

264 if spec.type == "line" and len(placed) > 1: 

265 shapes.append( 

266 PolyLine( 

267 [c for p in placed for c in p], 

268 strokeColor=s.color, 

269 strokeWidth=2 * PX, 

270 strokeLineJoin=1, 

271 ) 

272 ) 

273 opacity = 0.8 if spec.type == "line" else 1.0 

274 for px, py in placed: 

275 shapes.append( 

276 Circle( 

277 px, 

278 py, 

279 _MARKER, 

280 fillColor=s.color, 

281 fillOpacity=opacity, 

282 strokeColor=None, 

283 ) 

284 ) 

285 fit = fits.get(s.name) 

286 if fit: 

287 (x0, y0), (x1, y1) = fit 

288 shapes.append( 

289 rule(x(x0), y(y0), x(x1), y(y1), s.color, 1.5 * PX, _FIT_DASH, 0.75) 

290 ) 

291 shapes += axes.axis_titles(spec.x_title, spec.y_title, area, x_title_y, theme) 

292 layout = _drawn(shapes, width, height) 

293 group = Group(*legend_shapes) 

294 group.translate(0, legend_height) 

295 layout.drawing.add(group) 

296 return layout 

297 

298 

299def _drawn(shapes: list[object], width: float, height: float) -> Layout: 

300 drawing = Drawing(width, height) 

301 for shape in shapes: 

302 drawing.add(shape) 

303 return Layout(drawing, width, height)