pixelplotlib 0.1.0__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.
pixelplotlib/axes.py ADDED
@@ -0,0 +1,1123 @@
1
+ """Axes: data coordinates, layout, decorations and the plotting API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from collections.abc import Sequence
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ import numpy as np
10
+
11
+ from . import artists as A
12
+ from .artists import RenderContext, Scale, make_norm
13
+ from .canvas import Canvas
14
+ from .colormaps import CmapLike, Ramp
15
+ from .ticks import format_ticks, log_ticks, nice_ticks
16
+
17
+ if TYPE_CHECKING: # pragma: no cover
18
+ from .figure import Figure
19
+
20
+ _TICK_GAP = 2 # pixels between a y tick mark and its label
21
+
22
+
23
+ def _overlaps(a, b) -> bool:
24
+ """Whether two ``(x0, y0, x1, y1)`` boxes (exclusive ends) intersect."""
25
+ return a[0] < b[2] and b[0] < a[2] and a[1] < b[3] and b[1] < a[3]
26
+
27
+
28
+ _LOCS = {
29
+ "upper right": (1, 0), "upper left": (0, 0), "lower left": (0, 1), "lower right": (1, 1),
30
+ "upper center": (0.5, 0), "lower center": (0.5, 1), "center left": (0, 0.5),
31
+ "center right": (1, 0.5), "center": (0.5, 0.5),
32
+ }
33
+
34
+ _FMT_COLORS = {"r": "red", "g": "green", "b": "blue", "c": "cyan", "m": "magenta",
35
+ "y": "yellow", "k": "black", "w": "white"}
36
+ _FMT_MARKERS = "osDdv^+x*.p"
37
+
38
+
39
+ def _parse_fmt(fmt: str):
40
+ color = marker = linestyle = None
41
+ s = fmt
42
+ for ls in ("--", "-.", "-", ":"):
43
+ if ls in s:
44
+ linestyle = ls
45
+ s = s.replace(ls, "", 1)
46
+ break
47
+ for ch in s:
48
+ if ch in _FMT_COLORS:
49
+ color = _FMT_COLORS[ch]
50
+ elif ch in _FMT_MARKERS:
51
+ marker = "D" if ch == "d" else ch
52
+ else:
53
+ raise ValueError(f"unrecognized format string {fmt!r}")
54
+ if marker and linestyle is None:
55
+ linestyle = "none"
56
+ return color, marker, linestyle
57
+
58
+
59
+ def _is_str_seq(x) -> bool:
60
+ if isinstance(x, (str, bytes)) or not hasattr(x, "__len__") or len(x) == 0:
61
+ return False
62
+ first = x[0]
63
+ return isinstance(first, str)
64
+
65
+
66
+ class Colorbar:
67
+ def __init__(self, mappable, label=None, ticks=None):
68
+ self.mappable = mappable
69
+ self.label = label
70
+ self.ticks = ticks
71
+
72
+ def tick_values(self, max_ticks: int):
73
+ m = self.mappable
74
+ if self.ticks is not None:
75
+ vals = np.asarray(self.ticks, dtype=np.float64)
76
+ elif getattr(m, "levels", None) is not None:
77
+ vals = np.asarray(m.levels, dtype=np.float64)
78
+ stride = max(1, math.ceil(len(vals) / max_ticks))
79
+ vals = vals[::stride]
80
+ elif m.norm.kind == "log":
81
+ vals = log_ticks(m.norm.vmin, m.norm.vmax, max_ticks)
82
+ else:
83
+ vals, _ = nice_ticks(m.norm.vmin, m.norm.vmax, max_ticks)
84
+ lo, hi = sorted((m.norm.vmin, m.norm.vmax))
85
+ tol = (hi - lo) * 1e-9
86
+ vals = vals[(vals >= lo - tol) & (vals <= hi + tol)]
87
+ return vals, format_ticks(vals, log=m.norm.kind == "log")
88
+
89
+
90
+ class Axes:
91
+ """A single plot panel. Create via :meth:`Figure.add_subplot` or :func:`subplots`."""
92
+
93
+ def __init__(self, figure: Figure, spec):
94
+ self.figure = figure
95
+ self._spec = spec
96
+ self.artists: list[A.Artist] = []
97
+ self._title = self._xlabel = self._ylabel = None
98
+ self._xlim: list[float | None] = [None, None]
99
+ self._ylim: list[float | None] = [None, None]
100
+ self._xscale = Scale("linear")
101
+ self._yscale = Scale("linear")
102
+ self._xticks = self._yticks = None
103
+ self._xticklabels = self._yticklabels = None
104
+ self._grid: str | None = None
105
+ self._legend: dict | None = None
106
+ self._colorbar: Colorbar | None = None
107
+ self._axis_on = True
108
+ self._aspect = "auto"
109
+ self._margins = [0.05, 0.05]
110
+ self._series = 0
111
+ self._xcats: dict[str, int] = {}
112
+ self._ycats: dict[str, int] = {}
113
+ self._invert = [False, False]
114
+ self.last_rect: tuple[int, int, int, int] | None = None
115
+
116
+ # ------------------------------------------------------------------ basics
117
+ @property
118
+ def style(self):
119
+ return self.figure.style
120
+
121
+ def _cycle(self) -> dict:
122
+ st = self.style
123
+ i = self._series
124
+ self._series += 1
125
+ return dict(
126
+ color=st.series_color(i),
127
+ linestyle=st.linestyles[i % len(st.linestyles)],
128
+ marker=st.markers[i % len(st.markers)],
129
+ alpha=st.fill_alphas[i % len(st.fill_alphas)],
130
+ )
131
+
132
+ def _color(self, c, default):
133
+ return self.style.color(c) if c is not None else default
134
+
135
+ def _colors(self, c, n, default):
136
+ """Resolve ``c`` (None, one color or one per item) to a list of RGB tuples."""
137
+ if c is None:
138
+ return [default]
139
+ if isinstance(c, (list, tuple)) and len(c) == n and n > 0 and not (
140
+ n in (3, 4) and all(isinstance(v, (int, float, np.number)) for v in c)
141
+ ):
142
+ return [self.style.color(v) for v in c]
143
+ return [self.style.color(c)]
144
+
145
+ def _add(self, artist: A.Artist) -> A.Artist:
146
+ self.artists.append(artist)
147
+ return artist
148
+
149
+ def _cat(self, values, axis: str):
150
+ """Map categorical (string) values to integer positions."""
151
+ if not _is_str_seq(values):
152
+ return np.asarray(values, dtype=np.float64)
153
+ cats = self._xcats if axis == "x" else self._ycats
154
+ out = []
155
+ for v in values:
156
+ if v not in cats:
157
+ cats[v] = len(cats)
158
+ out.append(cats[v])
159
+ return np.asarray(out, dtype=np.float64)
160
+
161
+ # ------------------------------------------------------------------ setters
162
+ def set_title(self, title: str | None):
163
+ self._title = title
164
+ return self
165
+
166
+ def set_xlabel(self, label: str | None):
167
+ self._xlabel = label
168
+ return self
169
+
170
+ def set_ylabel(self, label: str | None):
171
+ self._ylabel = label
172
+ return self
173
+
174
+ def set_xlim(self, left=None, right=None):
175
+ if isinstance(left, (tuple, list)):
176
+ left, right = left
177
+ self._xlim = [left, right]
178
+ return self
179
+
180
+ def set_ylim(self, bottom=None, top=None):
181
+ if isinstance(bottom, (tuple, list)):
182
+ bottom, top = bottom
183
+ self._ylim = [bottom, top]
184
+ return self
185
+
186
+ def get_xlim(self) -> tuple[float, float]:
187
+ return self._limits()[0]
188
+
189
+ def get_ylim(self) -> tuple[float, float]:
190
+ return self._limits()[1]
191
+
192
+ def set_xscale(self, scale: str):
193
+ self._xscale = Scale(scale)
194
+ return self
195
+
196
+ def set_yscale(self, scale: str):
197
+ self._yscale = Scale(scale)
198
+ return self
199
+
200
+ def set_xticks(self, ticks, labels: Sequence[str] | None = None):
201
+ self._xticks = None if ticks is None else np.asarray(ticks, dtype=np.float64)
202
+ self._xticklabels = None if labels is None else [str(s) for s in labels]
203
+ return self
204
+
205
+ def set_yticks(self, ticks, labels: Sequence[str] | None = None):
206
+ self._yticks = None if ticks is None else np.asarray(ticks, dtype=np.float64)
207
+ self._yticklabels = None if labels is None else [str(s) for s in labels]
208
+ return self
209
+
210
+ def set_xticklabels(self, labels):
211
+ self._xticklabels = [str(s) for s in labels]
212
+ return self
213
+
214
+ def set_yticklabels(self, labels):
215
+ self._yticklabels = [str(s) for s in labels]
216
+ return self
217
+
218
+ def set_aspect(self, aspect: str | float):
219
+ """``"auto"`` (fill the panel) or ``"equal"`` / a number (data units y per x)."""
220
+ self._aspect = aspect
221
+ return self
222
+
223
+ def margins(self, x: float | None = None, y: float | None = None):
224
+ """Fractional padding added around the data when autoscaling."""
225
+ if y is None:
226
+ y = x
227
+ if x is not None:
228
+ self._margins[0] = x
229
+ if y is not None:
230
+ self._margins[1] = y
231
+ return self
232
+
233
+ def invert_xaxis(self):
234
+ self._invert[0] = not self._invert[0]
235
+ return self
236
+
237
+ def invert_yaxis(self):
238
+ self._invert[1] = not self._invert[1]
239
+ return self
240
+
241
+ def grid(self, visible: bool = True, axis: str = "both"):
242
+ self._grid = axis if visible else None
243
+ return self
244
+
245
+ def axis(self, state: str | bool = "on"):
246
+ """``axis("off")`` hides frame, ticks and labels."""
247
+ self._axis_on = state not in ("off", False)
248
+ return self
249
+
250
+ def set_axis_off(self):
251
+ return self.axis("off")
252
+
253
+ def legend(self, loc: str = "best", title: str | None = None):
254
+ """Show a legend of all labelled artists."""
255
+ if loc != "best" and loc not in _LOCS:
256
+ raise ValueError(f"unknown legend loc {loc!r}; choose from {['best', *_LOCS]}")
257
+ self._legend = dict(loc=loc, title=title)
258
+ return self
259
+
260
+ def colorbar(self, mappable=None, label: str | None = None, ticks=None):
261
+ """Attach a colorbar for ``mappable`` (defaults to the last colormapped artist)."""
262
+ if mappable is None:
263
+ mappable = next((a for a in reversed(self.artists)
264
+ if getattr(a, "ramp", None) is not None
265
+ and getattr(a, "norm", None) is not None), None)
266
+ if mappable is None:
267
+ raise ValueError("no colormapped artist to attach a colorbar to")
268
+ self._colorbar = Colorbar(mappable, label, ticks)
269
+ return self._colorbar
270
+
271
+ def set(self, **kwargs):
272
+ """Set several properties at once, e.g. ``ax.set(title=..., xlabel=..., xlim=...)``."""
273
+ for key, value in kwargs.items():
274
+ setter = getattr(self, f"set_{key}", None)
275
+ if setter is None:
276
+ raise AttributeError(f"unknown property {key!r}")
277
+ if isinstance(value, (tuple, list)) and key in ("xlim", "ylim"):
278
+ setter(*value)
279
+ else:
280
+ setter(value)
281
+ return self
282
+
283
+ # ------------------------------------------------------------------ plotting API
284
+ def plot(self, *args, color=None, linewidth=None, lw=None, linestyle=None, ls=None,
285
+ marker=None, markersize=1, ms=None, label=None):
286
+ """Line plot: ``plot(y)``, ``plot(x, y)`` or ``plot(x, y, fmt)`` (e.g. ``"r--o"``).
287
+
288
+ A 2-D ``y`` draws one line per column.
289
+ """
290
+ fmt = None
291
+ if args and isinstance(args[-1], str):
292
+ fmt = args[-1]
293
+ args = args[:-1]
294
+ if len(args) == 1:
295
+ y = np.asarray(args[0], dtype=np.float64)
296
+ x = np.arange(y.shape[0], dtype=np.float64)
297
+ elif len(args) == 2:
298
+ x, y = self._cat(args[0], "x"), np.asarray(args[1], dtype=np.float64)
299
+ else:
300
+ raise TypeError("plot() takes y, (x, y) or (x, y, fmt)")
301
+ fcolor = fmarker = fls = None
302
+ if fmt:
303
+ fcolor, fmarker, fls = _parse_fmt(fmt)
304
+ lines = []
305
+ ys = y.T if y.ndim == 2 else [y]
306
+ labels = label if isinstance(label, (list, tuple)) else [label] * len(ys)
307
+ for k, yy in enumerate(ys):
308
+ cyc = self._cycle()
309
+ lines.append(self._add(A.Line(
310
+ x, yy,
311
+ color=self._color(color or fcolor, cyc["color"]),
312
+ width=linewidth or lw or self.style.line_width,
313
+ linestyle=linestyle or ls or fls or cyc["linestyle"],
314
+ marker=marker or fmarker,
315
+ markersize=ms or markersize,
316
+ label=labels[k],
317
+ )))
318
+ return lines if len(lines) > 1 else lines[0]
319
+
320
+ def step(self, x, y, where: str = "pre", **kwargs):
321
+ """Staircase plot; ``where`` is ``"pre"``, ``"post"`` or ``"mid"``."""
322
+ x = self._cat(x, "x")
323
+ y = np.asarray(y, dtype=np.float64)
324
+ if len(x) < 2:
325
+ return self.plot(x, y, **kwargs)
326
+ if where == "pre":
327
+ sx, sy = np.repeat(x, 2)[:-1], np.repeat(y, 2)[1:]
328
+ elif where == "post":
329
+ sx, sy = np.repeat(x, 2)[1:], np.repeat(y, 2)[:-1]
330
+ elif where == "mid":
331
+ mids = (x[:-1] + x[1:]) / 2
332
+ sx = np.concatenate([[x[0]], np.repeat(mids, 2), [x[-1]]])
333
+ sy = np.repeat(y, 2)
334
+ else:
335
+ raise ValueError("where must be 'pre', 'post' or 'mid'")
336
+ return self.plot(sx, sy, **kwargs)
337
+
338
+ def scatter(self, x, y, c=None, color=None, marker=None, size=1, s=None, cmap=None,
339
+ vmin=None, vmax=None, norm=None, outline=None, label=None):
340
+ """Scatter plot with pixel sprites. ``c`` may be values to colormap."""
341
+ cyc = self._cycle()
342
+ x = self._cat(x, "x")
343
+ y = self._cat(y, "y")
344
+ values = ramp = nrm = None
345
+ if c is not None and np.ndim(c) == 1 and len(c) == len(x) and not isinstance(c[0], str):
346
+ values = np.asarray(c, dtype=np.float64)
347
+ ramp = self.style.ramp(cmap)
348
+ nrm = make_norm(values, vmin, vmax, norm)
349
+ elif c is not None:
350
+ color = c
351
+ st = self.style
352
+ if outline is None and st.marker_outline is not None:
353
+ outline = st.marker_outline
354
+ return self._add(A.Scatter(
355
+ x, y, self._color(color, cyc["color"]), marker=marker or cyc["marker"],
356
+ size=s or size, values=values, ramp=ramp, norm=nrm,
357
+ outline=st.color(outline) if outline not in (None, False) else None, label=label,
358
+ ))
359
+
360
+ def bar(self, x, height, width=0.8, bottom=0.0, color=None, alpha=None, edgecolor="auto",
361
+ label=None):
362
+ """Vertical bars. ``x`` may be category names."""
363
+ cyc = self._cycle()
364
+ x = self._cat(x, "x")
365
+ h = np.broadcast_to(np.asarray(height, dtype=np.float64), x.shape)
366
+ return self._add(A.Bars(
367
+ x, h, width, bottom, self._colors(color, len(x), cyc["color"]), "v",
368
+ alpha=cyc["alpha"] if alpha is None else alpha,
369
+ outline=self._outline(edgecolor), label=label,
370
+ ))
371
+
372
+ def barh(self, y, width, height=0.8, left=0.0, color=None, alpha=None, edgecolor="auto",
373
+ label=None):
374
+ """Horizontal bars. ``y`` may be category names."""
375
+ cyc = self._cycle()
376
+ y = self._cat(y, "y")
377
+ w = np.broadcast_to(np.asarray(width, dtype=np.float64), y.shape)
378
+ return self._add(A.Bars(
379
+ y, w, height, left, self._colors(color, len(y), cyc["color"]), "h",
380
+ alpha=cyc["alpha"] if alpha is None else alpha,
381
+ outline=self._outline(edgecolor), label=label,
382
+ ))
383
+
384
+ def _outline(self, edgecolor):
385
+ if edgecolor == "auto":
386
+ return self.style.bar_outline
387
+ return edgecolor
388
+
389
+ def hist(self, data, bins=10, range=None, density=False, cumulative=False, color=None,
390
+ alpha=None, histtype="bar", edgecolor="auto", label=None, weights=None):
391
+ """Histogram. Returns ``(counts, edges, artist)``."""
392
+ d = np.asarray(data, dtype=np.float64).ravel()
393
+ if weights is not None:
394
+ weights = np.asarray(weights, dtype=np.float64).ravel()[np.isfinite(d)]
395
+ d = d[np.isfinite(d)]
396
+ if self._xscale.log and isinstance(bins, int):
397
+ pos = d[d > 0]
398
+ lo, hi = range or (pos.min(), pos.max())
399
+ bins = np.logspace(math.log10(lo), math.log10(hi), bins + 1)
400
+ counts, edges = np.histogram(d, bins=bins, range=range, density=density,
401
+ weights=weights)
402
+ if cumulative:
403
+ counts = np.cumsum(counts)
404
+ if density:
405
+ counts = counts / counts[-1]
406
+ if histtype == "step":
407
+ x = np.repeat(edges, 2)
408
+ y = np.concatenate([[0], np.repeat(counts, 2), [0]])
409
+ art = self.plot(x, y, color=color, label=label)
410
+ art.sticky_y = (0.0,)
411
+ return counts, edges, art
412
+ cyc = self._cycle()
413
+ art = self._add(A.Bars(
414
+ (edges[:-1] + edges[1:]) / 2, counts, np.diff(edges), 0.0,
415
+ self._colors(color, len(counts), cyc["color"]), "v",
416
+ alpha=cyc["alpha"] if alpha is None else alpha, outline=self._outline(edgecolor),
417
+ label=label,
418
+ ))
419
+ return counts, edges, art
420
+
421
+ def hist2d(self, x, y, bins=20, range=None, density=False, cmap=None, norm=None,
422
+ vmin=None, vmax=None, dither=None):
423
+ """2-D histogram rendered as a heatmap. Empty bins are left transparent."""
424
+ x = np.asarray(x, dtype=np.float64).ravel()
425
+ y = np.asarray(y, dtype=np.float64).ravel()
426
+ ok = np.isfinite(x) & np.isfinite(y)
427
+ h, xe, ye = np.histogram2d(x[ok], y[ok], bins=bins, range=range, density=density)
428
+ h = h.T.astype(np.float64)
429
+ h[h == 0] = np.nan
430
+ art = self.pcolormesh(xe, ye, h, cmap=cmap, norm=norm, vmin=vmin, vmax=vmax,
431
+ dither=dither)
432
+ return h, xe, ye, art
433
+
434
+ def fill_between(self, x, y1, y2=0.0, color=None, alpha=None, edgecolor=None, label=None):
435
+ """Fill the area between two curves (``alpha`` is emulated with dithering)."""
436
+ cyc = self._cycle()
437
+ c = self._color(color, cyc["color"])
438
+ if alpha is None:
439
+ alpha = min(cyc["alpha"], 0.5) if len(self.style.fill_alphas) > 1 else 0.5
440
+ edge = self.style.color(edgecolor) if edgecolor not in (None, "none") else None
441
+ return self._add(A.FillBetween(self._cat(x, "x"), y1, y2, c, alpha, edge, label))
442
+
443
+ def fill(self, x, y, color=None, alpha=1.0, edgecolor=None, label=None):
444
+ """Fill a polygon."""
445
+ cyc = self._cycle()
446
+ edge = self.style.color(edgecolor) if edgecolor not in (None, "none") else None
447
+ return self._add(A.Polygon(x, y, self._color(color, cyc["color"]), alpha, edge, label))
448
+
449
+ def errorbar(self, x, y, yerr=None, xerr=None, color=None, marker="o", markersize=1,
450
+ capsize=1, linestyle="none", label=None):
451
+ """Points with error bars. Errors can be scalars, arrays or ``(lower, upper)`` pairs."""
452
+ cyc = self._cycle()
453
+ return self._add(A.ErrorBars(self._cat(x, "x"), y, xerr, yerr,
454
+ self._color(color, cyc["color"]), capsize, marker,
455
+ markersize, linestyle, label))
456
+
457
+ def stem(self, x, y=None, bottom=0.0, color=None, marker="o", label=None):
458
+ """Stem plot (vertical lines from ``bottom`` to each value)."""
459
+ if y is None:
460
+ y, x = x, np.arange(len(x))
461
+ cyc = self._cycle()
462
+ return self._add(A.Stems(self._cat(x, "x"), y, bottom, self._color(color, cyc["color"]),
463
+ marker, 1, label))
464
+
465
+ def axhline(self, y=0.0, color=None, linestyle="-", linewidth=1, label=None):
466
+ return self._add(A.RefLine(y, "h", self._color(color, self.style.fg), linestyle,
467
+ linewidth, label))
468
+
469
+ def axvline(self, x=0.0, color=None, linestyle="-", linewidth=1, label=None):
470
+ return self._add(A.RefLine(x, "v", self._color(color, self.style.fg), linestyle,
471
+ linewidth, label))
472
+
473
+ def axhspan(self, ymin, ymax, color=None, alpha=0.5, label=None):
474
+ return self._add(A.Span(ymin, ymax, "h", self._color(color, self.style.fg), alpha,
475
+ label))
476
+
477
+ def axvspan(self, xmin, xmax, color=None, alpha=0.5, label=None):
478
+ return self._add(A.Span(xmin, xmax, "v", self._color(color, self.style.fg), alpha,
479
+ label))
480
+
481
+ def imshow(self, data, cmap: CmapLike | None = None, vmin=None, vmax=None, norm=None,
482
+ extent=None, origin: str = "upper", aspect: str | None = None, dither=None):
483
+ """Display a 2-D array (colormapped) or an RGB(A) image (pixelated to the palette).
484
+
485
+ ``extent`` is ``(left, right, bottom, top)``. ``dither=False`` gives posterized bands.
486
+ """
487
+ arr = np.asarray(data)
488
+ if arr.ndim not in (2, 3):
489
+ raise ValueError("imshow expects a 2-D array or an (H, W, 3|4) image")
490
+ h, w = arr.shape[:2]
491
+ if extent is None:
492
+ extent = (-0.5, w - 0.5, h - 0.5, -0.5) if origin == "upper" else (
493
+ -0.5, w - 0.5, -0.5, h - 0.5)
494
+ left, right, bottom, top = extent
495
+ x_edges = np.linspace(left, right, w + 1)
496
+ # row 0 is drawn at ``top`` for origin="upper" and at ``bottom`` for "lower"
497
+ y_edges = np.linspace(top, bottom, h + 1) if origin == "upper" else np.linspace(
498
+ bottom, top, h + 1)
499
+ if aspect is not None:
500
+ self.set_aspect(aspect)
501
+ if left > right:
502
+ self._invert[0] = True
503
+ if bottom > top:
504
+ self._invert[1] = True
505
+ return self._add_image(arr, x_edges, y_edges, cmap, vmin, vmax, norm, dither)
506
+
507
+ def pcolormesh(self, *args, cmap=None, vmin=None, vmax=None, norm=None, dither=None):
508
+ """``pcolormesh(C)`` or ``pcolormesh(x_edges, y_edges, C)`` for (ir)regular grids."""
509
+ if len(args) == 1:
510
+ c = np.asarray(args[0])
511
+ xe = np.arange(c.shape[1] + 1, dtype=np.float64)
512
+ ye = np.arange(c.shape[0] + 1, dtype=np.float64)
513
+ elif len(args) == 3:
514
+ xe, ye, c = (np.asarray(a) for a in args)
515
+ if xe.ndim == 2:
516
+ xe = xe[0]
517
+ if ye.ndim == 2:
518
+ ye = ye[:, 0]
519
+ if len(xe) == c.shape[1]:
520
+ xe = _centers_to_edges(xe)
521
+ if len(ye) == c.shape[0]:
522
+ ye = _centers_to_edges(ye)
523
+ else:
524
+ raise TypeError("pcolormesh takes C or (x, y, C)")
525
+ return self._add_image(c, xe, ye, cmap, vmin, vmax, norm, dither)
526
+
527
+ def _add_image(self, arr, x_edges, y_edges, cmap, vmin, vmax, norm, dither):
528
+ dither = self.style.dither if dither is None else dither
529
+ if arr.ndim == 3:
530
+ return self._add(A.Image(arr, x_edges, y_edges, None, None, dither))
531
+ ramp = self.style.ramp(cmap)
532
+ nrm = make_norm(arr, vmin, vmax, norm)
533
+ return self._add(A.Image(arr, x_edges, y_edges, ramp, nrm, dither))
534
+
535
+ def _grid_args(self, args):
536
+ if len(args) == 1:
537
+ z = np.asarray(args[0], dtype=np.float64)
538
+ x = np.arange(z.shape[1], dtype=np.float64)
539
+ y = np.arange(z.shape[0], dtype=np.float64)
540
+ elif len(args) == 3:
541
+ x, y, z = (np.asarray(a, dtype=np.float64) for a in args)
542
+ if x.ndim == 2:
543
+ x = x[0]
544
+ if y.ndim == 2:
545
+ y = y[:, 0]
546
+ else:
547
+ raise TypeError("expected Z or (X, Y, Z)")
548
+ return x, y, z
549
+
550
+ @staticmethod
551
+ def _levels(z, levels):
552
+ if np.ndim(levels) == 0:
553
+ finite = z[np.isfinite(z)]
554
+ ticks, _ = nice_ticks(finite.min(), finite.max(), int(levels) + 1)
555
+ # ensure the levels cover the data range
556
+ step = ticks[1] - ticks[0] if len(ticks) > 1 else 1.0
557
+ lo = ticks[0] - step if ticks[0] > finite.min() else ticks[0]
558
+ hi = ticks[-1] + step if ticks[-1] < finite.max() else ticks[-1]
559
+ return np.arange(lo, hi + step * 0.5, step)
560
+ return np.asarray(levels, dtype=np.float64)
561
+
562
+ def contour(self, *args, levels=8, colors=None, cmap=None, linestyles=None, linewidth=1,
563
+ label=None):
564
+ """Contour lines (marching squares). Single-color negative levels are dashed."""
565
+ x, y, z = self._grid_args(args)
566
+ lv = self._levels(z, levels)
567
+ if np.ndim(levels) == 0:
568
+ lv = lv[(lv > np.nanmin(z)) & (lv < np.nanmax(z))]
569
+ if colors is not None:
570
+ cols = self._colors(colors, len(lv), self.style.fg)
571
+ cols = [cols[i % len(cols)] for i in range(len(lv))]
572
+ single = len(set(cols)) == 1
573
+ else:
574
+ ramp = self.style.ramp(cmap)
575
+ denom = (lv[-1] - lv[0]) or 1.0
576
+ cols = [ramp.color_at((v - lv[0]) / denom) for v in lv]
577
+ single = False
578
+ if linestyles is None:
579
+ styles = ["--" if (single and v < 0) else "-" for v in lv]
580
+ elif isinstance(linestyles, str):
581
+ styles = [linestyles] * len(lv)
582
+ else:
583
+ styles = [linestyles[i % len(linestyles)] for i in range(len(lv))]
584
+ return self._add(A.ContourLines(x, y, z, lv, cols, styles, linewidth, label))
585
+
586
+ def contourf(self, *args, levels=8, cmap=None, dither=None):
587
+ """Filled contours; each band gets its own (dithered) color."""
588
+ x, y, z = self._grid_args(args)
589
+ lv = self._levels(z, levels)
590
+ ramp = self.style.ramp(cmap)
591
+ return self._add(A.FilledContour(x, y, z, lv, ramp,
592
+ self.style.dither if dither is None else dither))
593
+
594
+ def quiver(self, X, Y, U, V, C=None, color=None, cmap=None, scale=None, pivot="tail",
595
+ label=None):
596
+ """Vector field arrows. ``scale`` is pixels per data unit (auto by default)."""
597
+ X, Y, U, V = (np.asarray(a, dtype=np.float64) for a in (X, Y, U, V))
598
+ if X.ndim == 1 and Y.ndim == 1 and U.ndim == 2:
599
+ X, Y = np.meshgrid(X, Y)
600
+ cyc = self._cycle()
601
+ if C is not None:
602
+ ramp = self.style.ramp(cmap)
603
+ c = np.asarray(C, dtype=np.float64).ravel()
604
+ cols: Any = ramp.map(make_norm(c)(c)[None, :], dither=False)[0]
605
+ else:
606
+ cols = self._color(color, cyc["color"])
607
+ return self._add(A.Quiver(X, Y, U, V, cols, scale, pivot, label))
608
+
609
+ def pie(self, values, labels=None, colors=None, autopct=None, startangle=90.0,
610
+ counterclock=True, depth=None, outline="auto"):
611
+ """Pie chart. ``depth`` (pixels or ``"auto"``) tilts the pie and adds a 3-D extrusion."""
612
+ st = self.style
613
+ n = len(values)
614
+ if colors is None:
615
+ cols = [st.series_color(i) for i in range(n)]
616
+ else:
617
+ cols = [st.color(c) for c in colors]
618
+ if depth is None:
619
+ depth = "auto" if st.bar_shading else 0
620
+ if outline == "auto":
621
+ outline = st.bar_outline if st.bar_outline not in (None, "auto") else (
622
+ "#000000" if st.bar_shading else None)
623
+ self.axis("off")
624
+ return self._add(A.Pie(values, labels, cols, autopct, startangle, counterclock, depth,
625
+ outline))
626
+
627
+ def boxplot(self, data, labels=None, positions=None, widths=0.5, color=None,
628
+ showfliers=True, label=None):
629
+ """Box-and-whisker plot of one or several datasets."""
630
+ datasets = _as_datasets(data)
631
+ n = len(datasets)
632
+ pos = np.arange(n, dtype=np.float64) if positions is None else np.asarray(positions)
633
+ if color is None:
634
+ cols = [self.style.series_color(i) for i in range(n)]
635
+ else:
636
+ cols = self._colors(color, n, self.style.series_color(0))
637
+ if labels is not None:
638
+ self.set_xticks(pos, labels)
639
+ return self._add(A.BoxPlot(datasets, pos, widths, cols, showfliers, label))
640
+
641
+ def violinplot(self, data, labels=None, positions=None, widths=0.7, color=None,
642
+ show_box=True, label=None):
643
+ """Violin plot (Gaussian KDE evaluated per pixel row)."""
644
+ datasets = _as_datasets(data)
645
+ n = len(datasets)
646
+ pos = np.arange(n, dtype=np.float64) if positions is None else np.asarray(positions)
647
+ if color is None:
648
+ cols = [self.style.series_color(i) for i in range(n)]
649
+ else:
650
+ cols = self._colors(color, n, self.style.series_color(0))
651
+ if labels is not None:
652
+ self.set_xticks(pos, labels)
653
+ return self._add(A.Violins(datasets, pos, widths, cols, show_box, label))
654
+
655
+ def text(self, x, y, s, color=None, ha="left", va="baseline", transform="data",
656
+ fontsize="small", box=False):
657
+ """Draw text. ``transform`` is ``"data"``, ``"axes"`` (0..1) or ``"pixels"``.
658
+
659
+ ``fontsize`` is ``"small"`` (tick font) or ``"large"`` (label font).
660
+ """
661
+ st = self.style
662
+ font = st.get_font() if fontsize == "large" else st.get_tick_font()
663
+ return self._add(A.Text(x, y, s, self._color(color, st.fg), ha, va, transform, font,
664
+ box))
665
+
666
+ def annotate(self, text, xy, xytext=None, color=None, arrow=True, ha="center",
667
+ va="bottom", fontsize="small"):
668
+ """Label the point ``xy`` with ``text`` placed at ``xytext`` and an arrow."""
669
+ st = self.style
670
+ font = st.get_font() if fontsize == "large" else st.get_tick_font()
671
+ if xytext is None:
672
+ xytext, arrow = xy, False
673
+ return self._add(A.Annotation(text, xy, xytext, self._color(color, st.fg), arrow,
674
+ ha=ha, va=va, font=font))
675
+
676
+ # ------------------------------------------------------------------ limits
677
+ def _limits(self):
678
+ xlog, ylog = self._xscale.log, self._yscale.log
679
+ xb, yb, sx, sy = [], [], [], []
680
+ for a in self.artists:
681
+ b = a.bounds(xlog, ylog)
682
+ if b is None:
683
+ continue
684
+ if b[0] is not None:
685
+ xb += [b[0], b[1]]
686
+ if b[2] is not None:
687
+ yb += [b[2], b[3]]
688
+ sx += list(a.sticky_x)
689
+ sy += list(a.sticky_y)
690
+ if self._xcats and not xb:
691
+ xb = [0, len(self._xcats) - 1]
692
+ if self._ycats and not yb:
693
+ yb = [0, len(self._ycats) - 1]
694
+ mx = 0.1 if self._xcats and not sx else self._margins[0]
695
+ xlim = _resolve_lim(self._xlim, xb, sx, mx, self._xscale)
696
+ ylim = _resolve_lim(self._ylim, yb, sy, self._margins[1], self._yscale)
697
+ if self._invert[0]:
698
+ xlim = xlim[::-1]
699
+ if self._invert[1] and self._ylim == [None, None]:
700
+ ylim = ylim[::-1]
701
+ return xlim, ylim
702
+
703
+ # ------------------------------------------------------------------ ticks
704
+ def _tick_info(self, axis: str, lim, length: int, font):
705
+ scale = self._xscale if axis == "x" else self._yscale
706
+ user = self._xticks if axis == "x" else self._yticks
707
+ user_labels = self._xticklabels if axis == "x" else self._yticklabels
708
+ cats = self._xcats if axis == "x" else self._ycats
709
+ lo, hi = sorted(lim)
710
+ st = self.style
711
+ if user is not None:
712
+ vals = user
713
+ labels = user_labels if user_labels is not None else format_ticks(vals, scale.log)
714
+ elif cats:
715
+ vals = np.array(list(cats.values()), dtype=np.float64)
716
+ labels = list(cats.keys())
717
+ else:
718
+ vals = labels = None
719
+ if vals is not None:
720
+ tol = (hi - lo) * 1e-9
721
+ keep = (vals >= lo - tol) & (vals <= hi + tol)
722
+ labels = [st.text(lb) for lb, k in zip(labels, keep) if k]
723
+ vals = vals[keep]
724
+ return self._thin(axis, vals, labels, length, font)
725
+ spacing = 5 * font.measure("0")[0] + 3 if axis == "x" else font.line_height * 2 + 4
726
+ max_ticks = max(2, length // spacing + 1)
727
+ while True:
728
+ if scale.log:
729
+ vals = log_ticks(lo, hi, max_ticks)
730
+ else:
731
+ vals, _ = nice_ticks(lo, hi, max_ticks)
732
+ labels = [st.text(s) for s in format_ticks(vals, scale.log)]
733
+ if axis == "y" or max_ticks <= 2:
734
+ break
735
+ widths = sum(font.measure(s)[0] for s in labels) + 4 * len(labels)
736
+ if widths <= length:
737
+ break
738
+ max_ticks -= 1
739
+ return vals, labels
740
+
741
+ def _thin(self, axis, vals, labels, length, font):
742
+ """Drop every other label until categorical/user labels no longer overlap."""
743
+ if len(vals) < 2:
744
+ return vals, labels
745
+ stride = 1
746
+ while stride < len(vals):
747
+ sel = slice(None, None, stride)
748
+ if axis == "x":
749
+ need = sum(font.measure(s)[0] + 3 for s in labels[sel])
750
+ else:
751
+ need = (font.line_height + 1) * len(labels[sel])
752
+ if need <= length:
753
+ break
754
+ stride += 1
755
+ return vals, [lb if i % stride == 0 else "" for i, lb in enumerate(labels)]
756
+
757
+ # ------------------------------------------------------------------ rendering
758
+ def render(self, canvas: Canvas, cell: tuple[int, int, int, int]) -> None:
759
+ st = self.style
760
+ font = st.get_font()
761
+ tfont = st.get_tick_font()
762
+ shadow = st.color(st.text_shadow) if st.text_shadow is not None else None
763
+ fg = st.fg
764
+ if st.panel:
765
+ draw_panel(canvas, st, cell, st.panel_fill, st.panel_border, st.panel_radius,
766
+ st.panel_shadow)
767
+ inset = len(st.panel_border) + 2
768
+ else:
769
+ inset = 1
770
+ cx0, cy0, cx1, cy1 = cell
771
+ content = (cx0 + inset, cy0 + inset, cx1 - inset - (1 if st.panel_shadow else 0),
772
+ cy1 - inset - (1 if st.panel_shadow else 0))
773
+ xlim, ylim = self._limits()
774
+ title = st.text(self._title) if self._title else None
775
+ title_h = font.measure(title)[1] + st.pad if title else 0
776
+
777
+ if not self._axis_on:
778
+ plot = (content[0], content[1] + title_h, content[2], content[3])
779
+ xt = yt = np.array([])
780
+ xtl = ytl = []
781
+ else:
782
+ xlabel = st.text(self._xlabel) if self._xlabel else None
783
+ ylabel = st.text(self._ylabel) if self._ylabel else None
784
+ xlabel_h = font.measure(xlabel)[1] + st.pad if xlabel else 0
785
+ ylabel_w = font.measure(ylabel)[1] + st.pad if ylabel else 0
786
+ tl = st.tick_length
787
+ cap = tfont.ascent
788
+ plot = (content[0] + ylabel_w + 24, content[1] + title_h + 4, content[2] - 8,
789
+ content[3] - xlabel_h - tl - tfont.line_height - 2)
790
+ for _ in range(3):
791
+ pw = max(plot[2] - plot[0], 8)
792
+ ph = max(plot[3] - plot[1], 8)
793
+ xt, xtl = self._tick_info("x", xlim, pw, tfont)
794
+ yt, ytl = self._tick_info("y", ylim, ph, tfont)
795
+ ytw = max((tfont.measure(s)[0] for s in ytl), default=0)
796
+ xth = max((tfont.measure(s)[1] for s in xtl if s), default=0)
797
+ last_w = tfont.measure(xtl[-1])[0] if xtl else 0
798
+ cbar_w = self._colorbar_width(tfont, font, ph) if self._colorbar else 0
799
+ left = content[0] + ylabel_w + (ytw + _TICK_GAP if ytw else 0) + tl + 1
800
+ top = content[1] + max(title_h, cap // 2 + 1 if ytl else 0) + 1
801
+ right = content[2] - max(last_w // 2 + 1, 1) - cbar_w
802
+ if cbar_w:
803
+ right = content[2] - cbar_w
804
+ bottom = content[3] - xlabel_h - (xth + 1 if xth else 0) - tl - 1
805
+ plot = (left, top, max(right, left + 8), max(bottom, top + 8))
806
+ plot = self._apply_aspect(plot, xlim, ylim)
807
+ # final ticks for the final size
808
+ xt, xtl = self._tick_info("x", xlim, plot[2] - plot[0], tfont)
809
+ yt, ytl = self._tick_info("y", ylim, plot[3] - plot[1], tfont)
810
+
811
+ self.last_rect = plot
812
+ ctx = RenderContext(canvas, st, plot, xlim, ylim, self._xscale, self._yscale)
813
+ px0, py0, px1, py1 = plot
814
+
815
+ if st.plot_fill is not None:
816
+ fill_area(canvas, st, plot, st.plot_fill)
817
+ if self._grid and self._axis_on:
818
+ gc = st.color(st.grid_color, st.foreground)
819
+ with canvas.clip(*plot):
820
+ if self._grid in ("both", "x"):
821
+ for v in xt:
822
+ x = float(ctx.tx(v))
823
+ canvas.polyline([x, x], [py0, py1 - 1], gc, dash=st.grid_linestyle)
824
+ if self._grid in ("both", "y"):
825
+ for v in yt:
826
+ y = float(ctx.ty(v))
827
+ canvas.polyline([px0, px1 - 1], [y, y], gc, dash=st.grid_linestyle)
828
+
829
+ with canvas.clip(*plot):
830
+ for art in sorted(self.artists, key=lambda a: a.zorder):
831
+ art.draw(ctx)
832
+
833
+ if self._axis_on:
834
+ fc = st.color(st.frame_color, st.foreground)
835
+ canvas.rect(px0 - 1, py0 - 1, px1 + 1, py1 + 1, fc)
836
+ tl = st.tick_length
837
+ boxes = []
838
+ for v, s in zip(xt, xtl):
839
+ x = int(round(float(ctx.tx(v))))
840
+ canvas.fill_rect(x, py1 + 1, x + 1, py1 + 1 + tl, fc)
841
+ if s:
842
+ w = tfont.measure(s)[0]
843
+ lx = min(max(x - w // 2, content[0]), content[2] - w)
844
+ boxes.append(canvas.text(lx, py1 + 2 + tl, s, tfont, fg, "left", "top",
845
+ shadow=shadow))
846
+ cap = tfont.ascent
847
+ for v, s in zip(yt, ytl):
848
+ y = int(round(float(ctx.ty(v))))
849
+ canvas.fill_rect(px0 - 1 - tl, y, px0 - 1, y + 1, fc)
850
+ if not s:
851
+ continue
852
+ right = px0 - 1 - tl - _TICK_GAP # exclusive right edge of the label
853
+ box = (right - tfont.measure(s)[0], y - cap // 2, right, y - cap // 2 + cap)
854
+ if any(_overlaps(box, b) for b in boxes):
855
+ continue # e.g. the lowest y label colliding with the first x label
856
+ canvas.text(right - 1, y, s, tfont, fg, "right", "center", shadow=shadow)
857
+ if self._xlabel:
858
+ canvas.text((px0 + px1) // 2, content[3] - font.measure(st.text(self._xlabel))[1],
859
+ st.text(self._xlabel), font, fg, "center", "top", shadow=shadow)
860
+ if self._ylabel:
861
+ canvas.text(content[0], (py0 + py1) // 2, st.text(self._ylabel), font, fg,
862
+ "left", "center", rotation=90, shadow=shadow)
863
+ if title:
864
+ tc = st.color(st.title_color, st.foreground)
865
+ w = font.measure(title)[0]
866
+ tx = min(max((px0 + px1) // 2 - w // 2, content[0]), max(content[2] - w, content[0]))
867
+ canvas.text(tx, content[1], title, font, tc, "left", "top", shadow=shadow)
868
+ if self._colorbar is not None:
869
+ self._draw_colorbar(canvas, plot, tfont, font, shadow)
870
+ if self._legend is not None:
871
+ self._draw_legend(canvas, ctx, tfont, shadow)
872
+
873
+ def _apply_aspect(self, plot, xlim, ylim):
874
+ if self._aspect == "auto":
875
+ return plot
876
+ ratio = 1.0 if self._aspect == "equal" else float(self._aspect)
877
+ x0, y0, x1, y1 = plot
878
+ w, h = x1 - x0, y1 - y0
879
+ fx = self._xscale.fwd(np.array(xlim))
880
+ fy = self._yscale.fwd(np.array(ylim))
881
+ dx, dy = abs(fx[1] - fx[0]), abs(fy[1] - fy[0]) * ratio
882
+ if dx == 0 or dy == 0:
883
+ return plot
884
+ if dx / w > dy / h:
885
+ nh = max(int(round(dy * w / dx)), 4)
886
+ off = (h - nh) // 2
887
+ return (x0, y0 + off, x1, y0 + off + nh)
888
+ nw = max(int(round(dx * h / dy)), 4)
889
+ off = (w - nw) // 2
890
+ return (x0 + off, y0, x0 + off + nw, y1)
891
+
892
+ # ------------------------------------------------------------------ colorbar
893
+ _CBAR_GAP = 4
894
+ _CBAR_W = 6
895
+
896
+ def _colorbar_width(self, tfont, font, height):
897
+ cb = self._colorbar
898
+ st = self.style
899
+ _, labels = cb.tick_values(max(2, height // (tfont.line_height * 2 + 4) + 1))
900
+ lw = max((tfont.measure(s)[0] for s in labels), default=0)
901
+ label_w = font.measure(st.text(cb.label))[1] + st.pad if cb.label else 0
902
+ return (self._CBAR_GAP + self._CBAR_W + 2 + st.tick_length + _TICK_GAP + lw + label_w
903
+ + 1)
904
+
905
+ def _draw_colorbar(self, canvas, plot, tfont, font, shadow):
906
+ st = self.style
907
+ cb = self._colorbar
908
+ m = cb.mappable
909
+ px0, py0, px1, py1 = plot
910
+ bx0 = px1 + 1 + self._CBAR_GAP
911
+ bx1 = bx0 + self._CBAR_W
912
+ h = py1 - py0
913
+ rows = np.arange(h)
914
+ t = 1.0 - rows / max(h - 1, 1)
915
+ levels = getattr(m, "levels", None)
916
+ if levels is not None and len(levels) > 1:
917
+ n = len(levels) - 1
918
+ band = np.clip(np.floor(t * n), 0, n - 1)
919
+ t = (band + 0.5) / n
920
+ tt = np.repeat(t[:, None], self._CBAR_W, axis=1)
921
+ img = m.ramp.map(tt, getattr(m, "dither", True), bx0, py0)
922
+ canvas.blit(img, bx0, py0)
923
+ fc = st.color(st.frame_color, st.foreground)
924
+ canvas.rect(bx0 - 1, py0 - 1, bx1 + 1, py1 + 1, fc)
925
+ vals, labels = cb.tick_values(max(2, h // (tfont.line_height * 2 + 4) + 1))
926
+ tl = st.tick_length
927
+ lw = 0
928
+ for v, s in zip(vals, labels):
929
+ if levels is not None and len(levels) > 1:
930
+ u = float(np.interp(v, levels, np.linspace(0, 1, len(levels))))
931
+ else:
932
+ u = float(m.norm(np.array([v]))[0])
933
+ y = int(round(py0 + (1 - u) * (h - 1)))
934
+ canvas.fill_rect(bx1 + 1, y, bx1 + 1 + tl, y + 1, fc)
935
+ canvas.text(bx1 + 1 + tl + _TICK_GAP, y, st.text(s), tfont, st.fg, "left", "center",
936
+ shadow=shadow)
937
+ lw = max(lw, tfont.measure(st.text(s))[0])
938
+ if cb.label:
939
+ canvas.text(bx1 + 1 + tl + _TICK_GAP + lw + st.pad, (py0 + py1) // 2,
940
+ st.text(cb.label), font,
941
+ st.fg, "left", "center", rotation=90, shadow=shadow)
942
+
943
+ # ------------------------------------------------------------------ legend
944
+ def _draw_legend(self, canvas, ctx, font, shadow):
945
+ st = self.style
946
+ entries = [e for a in self.artists for e in a.legend_entries()]
947
+ if not entries:
948
+ return
949
+ title = st.text(self._legend.get("title")) if self._legend.get("title") else None
950
+ handle_w = 9
951
+ lh = font.line_height
952
+ labels = [st.text(e["label"]) for e in entries]
953
+ text_w = max(font.measure(s)[0] for s in labels)
954
+ if title:
955
+ text_w = max(text_w, font.measure(title)[0] - handle_w - 2)
956
+ w = 3 + handle_w + 2 + text_w + 3
957
+ h = 3 + (lh + 1) * (len(entries) + (1 if title else 0)) + 1
958
+ px0, py0, px1, py1 = ctx.rect
959
+ loc = self._legend["loc"]
960
+ if loc == "best":
961
+ loc = self._best_loc(ctx, w, h)
962
+ fx, fy = _LOCS[loc]
963
+ lx = int(px0 + 2 + fx * (px1 - px0 - 4 - w))
964
+ ly = int(py0 + 2 + fy * (py1 - py0 - 4 - h))
965
+ fill = st.legend_fill or st.panel_fill or st.background
966
+ draw_panel(canvas, st, (lx, ly, lx + w, ly + h), fill, (st.foreground,),
967
+ 1 if st.panel_radius else 0, None)
968
+ y = ly + 3
969
+ if title:
970
+ canvas.text(lx + 3, y, title, font, st.color(st.title_color, st.foreground),
971
+ shadow=shadow)
972
+ y += lh + 1
973
+ for e, s in zip(entries, labels):
974
+ A.legend_handle(canvas, st, e, lx + 3, y, handle_w, font.ascent)
975
+ canvas.text(lx + 3 + handle_w + 2, y, s, font, st.fg, shadow=shadow)
976
+ y += lh + 1
977
+
978
+ def _best_loc(self, ctx, w, h):
979
+ xs, ys = [], []
980
+ for a in self.artists:
981
+ p = a.points()
982
+ if p is not None:
983
+ xs.append(np.asarray(ctx.tx(p[0]), dtype=np.float64).ravel())
984
+ ys.append(np.asarray(ctx.ty(p[1]), dtype=np.float64).ravel())
985
+ if not xs:
986
+ return "upper right"
987
+ px, py = np.concatenate(xs), np.concatenate(ys)
988
+ # densify line segments a bit so long lines through a corner count
989
+ px0, py0, px1, py1 = ctx.rect
990
+ best, best_score = "upper right", None
991
+ for loc in ("upper right", "upper left", "lower right", "lower left"):
992
+ fx, fy = _LOCS[loc]
993
+ lx = px0 + 2 + fx * (px1 - px0 - 4 - w)
994
+ ly = py0 + 2 + fy * (py1 - py0 - 4 - h)
995
+ inside = (px >= lx - 2) & (px <= lx + w + 2) & (py >= ly - 2) & (py <= ly + h + 2)
996
+ score = int(inside.sum())
997
+ if best_score is None or score < best_score:
998
+ best, best_score = loc, score
999
+ return best
1000
+
1001
+
1002
+ def _resolve_lim(user, bounds, sticky, margin, scale: Scale):
1003
+ if user[0] is not None and user[1] is not None:
1004
+ return (float(user[0]), float(user[1]))
1005
+ vals = np.asarray(bounds, dtype=np.float64)
1006
+ vals = vals[np.isfinite(vals)]
1007
+ if scale.log:
1008
+ vals = vals[vals > 0]
1009
+ if vals.size == 0:
1010
+ lo, hi = (1.0, 10.0) if scale.log else (0.0, 1.0)
1011
+ else:
1012
+ lo, hi = float(vals.min()), float(vals.max())
1013
+ flo, fhi = float(scale.fwd(lo)), float(scale.fwd(hi))
1014
+ if flo == fhi:
1015
+ d = 0.5 if scale.log else (abs(flo) * 0.1 or 0.5)
1016
+ flo, fhi = flo - d, fhi + d
1017
+ else:
1018
+ span = fhi - flo
1019
+ nlo, nhi = flo - margin * span, fhi + margin * span
1020
+ fs = scale.fwd(np.asarray(list(sticky), dtype=np.float64))
1021
+ fs = fs[np.isfinite(fs)]
1022
+ tol = span * 1e-9
1023
+ below = fs[(fs > nlo) & (fs <= flo + tol)]
1024
+ above = fs[(fs < nhi) & (fs >= fhi - tol)]
1025
+ flo = float(below.max()) if below.size else nlo
1026
+ fhi = float(above.min()) if above.size else nhi
1027
+ lo, hi = float(scale.inv(flo)), float(scale.inv(fhi))
1028
+ if user[0] is not None:
1029
+ lo = float(user[0])
1030
+ if user[1] is not None:
1031
+ hi = float(user[1])
1032
+ return (lo, hi)
1033
+
1034
+
1035
+ def _centers_to_edges(c):
1036
+ c = np.asarray(c, dtype=np.float64)
1037
+ if len(c) == 1:
1038
+ return np.array([c[0] - 0.5, c[0] + 0.5])
1039
+ mid = (c[:-1] + c[1:]) / 2
1040
+ return np.concatenate([[c[0] - (mid[0] - c[0])], mid, [c[-1] + (c[-1] - mid[-1])]])
1041
+
1042
+
1043
+ def _as_datasets(data):
1044
+ if isinstance(data, np.ndarray):
1045
+ if data.ndim == 1:
1046
+ return [data]
1047
+ return [data[:, i] for i in range(data.shape[1])]
1048
+ if len(data) and np.ndim(data[0]) == 0:
1049
+ return [np.asarray(data, dtype=np.float64)]
1050
+ return [np.asarray(d, dtype=np.float64) for d in data]
1051
+
1052
+
1053
+ # ---------------------------------------------------------------------- panels
1054
+ def is_gradient(fill) -> bool:
1055
+ return (isinstance(fill, (tuple, list)) and len(fill) == 2
1056
+ and all(isinstance(f, (str, tuple, list)) for f in fill))
1057
+
1058
+
1059
+ def fill_area(canvas: Canvas, style, rect, fill, mask: np.ndarray | None = None):
1060
+ """Fill ``rect`` with a solid color or a dithered ``(top, bottom)`` gradient."""
1061
+ if fill is None:
1062
+ return
1063
+ x0, y0, x1, y1 = rect
1064
+ w, h = x1 - x0, y1 - y0
1065
+ if w <= 0 or h <= 0:
1066
+ return
1067
+ if is_gradient(fill):
1068
+ ramp = _gradient_ramp(style, fill)
1069
+ t = np.repeat((np.arange(h) / max(h - 1, 1))[:, None], w, axis=1)
1070
+ img = ramp.map(t, style.dither, x0, y0)
1071
+ canvas.blit(img, x0, y0, mask=mask)
1072
+ else:
1073
+ c = style.color(fill)
1074
+ if mask is None:
1075
+ canvas.fill_rect(x0, y0, x1, y1, c)
1076
+ else:
1077
+ canvas.fill_mask(mask, x0, y0, c)
1078
+
1079
+
1080
+ def _gradient_ramp(style, fill) -> Ramp:
1081
+ from .colormaps import Colormap, build_ramp
1082
+
1083
+ cm = Colormap("gradient", [style.color(fill[0]), style.color(fill[1])])
1084
+ pal = style.colors.palette
1085
+ if pal is not None and len(pal) <= 4:
1086
+ return Ramp(np.array([0.0, 1.0]), np.array([style.color(fill[0]),
1087
+ style.color(fill[1])], dtype=np.uint8))
1088
+ return build_ramp(cm, style.colors, style.gradient_levels)
1089
+
1090
+
1091
+ def rounded_mask(w: int, h: int, r: int) -> np.ndarray:
1092
+ m = np.ones((h, w), dtype=bool)
1093
+ r = min(r, w // 2, h // 2)
1094
+ if r <= 0:
1095
+ return m
1096
+ yy, xx = np.mgrid[0:r, 0:r]
1097
+ dx = r - (xx + 0.5)
1098
+ dy = r - (yy + 0.5)
1099
+ corner = dx * dx + dy * dy <= (r - 0.5) ** 2
1100
+ m[:r, :r] &= corner
1101
+ m[:r, w - r :] &= corner[:, ::-1]
1102
+ m[h - r :, :r] &= corner[::-1, :]
1103
+ m[h - r :, w - r :] &= corner[::-1, ::-1]
1104
+ return m
1105
+
1106
+
1107
+ def draw_panel(canvas: Canvas, style, rect, fill, border, radius=0, shadow=None):
1108
+ """Retro UI window: optional drop shadow, concentric border rings and (gradient) fill."""
1109
+ x0, y0, x1, y1 = rect
1110
+ if shadow is not None:
1111
+ x1 -= 1
1112
+ y1 -= 1
1113
+ w, h = x1 - x0, y1 - y0
1114
+ if w <= 2 or h <= 2:
1115
+ return
1116
+ if shadow is not None:
1117
+ canvas.fill_mask(rounded_mask(w, h, radius), x0 + 1, y0 + 1, style.color(shadow))
1118
+ n = len(border)
1119
+ for i, c in enumerate(border):
1120
+ outer = rounded_mask(w - 2 * i, h - 2 * i, max(radius - i, 0))
1121
+ canvas.fill_mask(outer, x0 + i, y0 + i, style.color(c))
1122
+ inner = rounded_mask(w - 2 * n, h - 2 * n, max(radius - n, 0))
1123
+ fill_area(canvas, style, (x0 + n, y0 + n, x1 - n, y1 - n), fill, mask=inner)