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/__init__.py +41 -0
- pixelplotlib/animation.py +73 -0
- pixelplotlib/artists.py +1313 -0
- pixelplotlib/axes.py +1123 -0
- pixelplotlib/canvas.py +369 -0
- pixelplotlib/colormaps.py +163 -0
- pixelplotlib/colors.py +143 -0
- pixelplotlib/dither.py +89 -0
- pixelplotlib/figure.py +259 -0
- pixelplotlib/fonts.py +358 -0
- pixelplotlib/markers.py +53 -0
- pixelplotlib/palettes.py +62 -0
- pixelplotlib/pyplot.py +106 -0
- pixelplotlib/rich.py +139 -0
- pixelplotlib/sixel.py +147 -0
- pixelplotlib/styles.py +347 -0
- pixelplotlib/textual.py +77 -0
- pixelplotlib/ticks.py +90 -0
- pixelplotlib-0.1.0.dist-info/METADATA +608 -0
- pixelplotlib-0.1.0.dist-info/RECORD +22 -0
- pixelplotlib-0.1.0.dist-info/WHEEL +4 -0
- pixelplotlib-0.1.0.dist-info/licenses/LICENSE +18 -0
pixelplotlib/artists.py
ADDED
|
@@ -0,0 +1,1313 @@
|
|
|
1
|
+
"""Drawable plot elements."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
from .canvas import Canvas, dash_pattern, dilate
|
|
12
|
+
from .colormaps import Ramp
|
|
13
|
+
from .dither import pixelate
|
|
14
|
+
from .markers import marker_mask
|
|
15
|
+
|
|
16
|
+
EPS = 1e-6
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _f(a) -> np.ndarray:
|
|
20
|
+
return np.asarray(a, dtype=np.float64).ravel()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _finite_range(v: np.ndarray, log: bool):
|
|
24
|
+
v = v[np.isfinite(v)]
|
|
25
|
+
if log:
|
|
26
|
+
v = v[v > 0]
|
|
27
|
+
if v.size == 0:
|
|
28
|
+
return None
|
|
29
|
+
return float(v.min()), float(v.max())
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Scale:
|
|
33
|
+
"""Maps data values to a linear "transformed" space (identity or log10)."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, kind: str = "linear"):
|
|
36
|
+
if kind not in ("linear", "log"):
|
|
37
|
+
raise ValueError("scale must be 'linear' or 'log'")
|
|
38
|
+
self.kind = kind
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def log(self) -> bool:
|
|
42
|
+
return self.kind == "log"
|
|
43
|
+
|
|
44
|
+
def fwd(self, v):
|
|
45
|
+
v = np.asarray(v, dtype=np.float64)
|
|
46
|
+
if self.log:
|
|
47
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
48
|
+
return np.where(v > 0, np.log10(np.where(v > 0, v, 1.0)), np.nan)
|
|
49
|
+
return v
|
|
50
|
+
|
|
51
|
+
def inv(self, u):
|
|
52
|
+
u = np.asarray(u, dtype=np.float64)
|
|
53
|
+
return 10.0**u if self.log else u
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class Norm:
|
|
57
|
+
"""Value normalization for colormapped artists."""
|
|
58
|
+
|
|
59
|
+
def __init__(self, vmin: float, vmax: float, kind: str = "linear"):
|
|
60
|
+
self.vmin, self.vmax, self.kind = float(vmin), float(vmax), kind
|
|
61
|
+
if kind == "log" and (self.vmin <= 0 or self.vmax <= 0):
|
|
62
|
+
raise ValueError("log norm needs positive vmin/vmax")
|
|
63
|
+
|
|
64
|
+
def __call__(self, v) -> np.ndarray:
|
|
65
|
+
v = np.asarray(v, dtype=np.float64)
|
|
66
|
+
if self.kind == "log":
|
|
67
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
68
|
+
lv = np.log10(np.where(v > 0, v, np.nan))
|
|
69
|
+
lo, hi = math.log10(self.vmin), math.log10(self.vmax)
|
|
70
|
+
return (lv - lo) / ((hi - lo) or 1.0)
|
|
71
|
+
return (v - self.vmin) / ((self.vmax - self.vmin) or 1.0)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def make_norm(values, vmin=None, vmax=None, norm: str | None = None) -> Norm:
|
|
75
|
+
kind = norm or "linear"
|
|
76
|
+
v = _f(values)
|
|
77
|
+
v = v[np.isfinite(v)]
|
|
78
|
+
if kind == "log":
|
|
79
|
+
v = v[v > 0]
|
|
80
|
+
lo = vmin if vmin is not None else (float(v.min()) if v.size else 0.0)
|
|
81
|
+
hi = vmax if vmax is not None else (float(v.max()) if v.size else 1.0)
|
|
82
|
+
if lo == hi:
|
|
83
|
+
lo, hi = (lo / 10, hi * 10) if kind == "log" else (lo - 0.5, hi + 0.5)
|
|
84
|
+
return Norm(lo, hi, kind)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class RenderContext:
|
|
88
|
+
"""Everything an artist needs to draw itself inside an axes."""
|
|
89
|
+
|
|
90
|
+
def __init__(self, canvas: Canvas, style, rect, xlim, ylim, xscale: Scale, yscale: Scale):
|
|
91
|
+
self.canvas = canvas
|
|
92
|
+
self.style = style
|
|
93
|
+
self.rect = rect
|
|
94
|
+
self.xlim, self.ylim = xlim, ylim
|
|
95
|
+
self.xscale, self.yscale = xscale, yscale
|
|
96
|
+
self._fx = (float(xscale.fwd(xlim[0])), float(xscale.fwd(xlim[1])))
|
|
97
|
+
self._fy = (float(yscale.fwd(ylim[0])), float(yscale.fwd(ylim[1])))
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def width(self) -> int:
|
|
101
|
+
return self.rect[2] - self.rect[0]
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def height(self) -> int:
|
|
105
|
+
return self.rect[3] - self.rect[1]
|
|
106
|
+
|
|
107
|
+
def ux(self, x):
|
|
108
|
+
lo, hi = self._fx
|
|
109
|
+
return (self.xscale.fwd(x) - lo) / ((hi - lo) or 1.0)
|
|
110
|
+
|
|
111
|
+
def uy(self, y):
|
|
112
|
+
lo, hi = self._fy
|
|
113
|
+
return (self.yscale.fwd(y) - lo) / ((hi - lo) or 1.0)
|
|
114
|
+
|
|
115
|
+
def tx(self, x):
|
|
116
|
+
"""Data x -> pixel-center x coordinate (float)."""
|
|
117
|
+
return self.rect[0] - 0.5 + self.ux(x) * (self.width - EPS)
|
|
118
|
+
|
|
119
|
+
def ty(self, y):
|
|
120
|
+
return self.rect[1] - 0.5 + (1.0 - self.uy(y)) * (self.height - EPS)
|
|
121
|
+
|
|
122
|
+
def inv_x(self, px):
|
|
123
|
+
u = (np.asarray(px, dtype=np.float64) - (self.rect[0] - 0.5)) / (self.width - EPS)
|
|
124
|
+
lo, hi = self._fx
|
|
125
|
+
return self.xscale.inv(lo + u * (hi - lo))
|
|
126
|
+
|
|
127
|
+
def inv_y(self, py):
|
|
128
|
+
u = 1.0 - (np.asarray(py, dtype=np.float64) - (self.rect[1] - 0.5)) / (self.height - EPS)
|
|
129
|
+
lo, hi = self._fy
|
|
130
|
+
return self.yscale.inv(lo + u * (hi - lo))
|
|
131
|
+
|
|
132
|
+
# pixel spans for areas: pixels whose centers lie within [a, b)
|
|
133
|
+
@staticmethod
|
|
134
|
+
def span(a: float, b: float, minimum: int = 0) -> tuple[int, int]:
|
|
135
|
+
lo, hi = (a, b) if a <= b else (b, a)
|
|
136
|
+
if not (np.isfinite(lo) and np.isfinite(hi)):
|
|
137
|
+
return 0, 0
|
|
138
|
+
p0, p1 = int(math.ceil(lo)), int(math.ceil(hi))
|
|
139
|
+
if p1 - p0 < minimum:
|
|
140
|
+
if b < a: # value grows upwards on screen: extend towards smaller pixel rows
|
|
141
|
+
p0 = p1 - minimum
|
|
142
|
+
else:
|
|
143
|
+
p1 = p0 + minimum
|
|
144
|
+
return p0, p1
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class Artist:
|
|
148
|
+
zorder = 2
|
|
149
|
+
label: str | None = None
|
|
150
|
+
sticky_x: Sequence[float] = ()
|
|
151
|
+
sticky_y: Sequence[float] = ()
|
|
152
|
+
|
|
153
|
+
def bounds(self, xlog: bool, ylog: bool):
|
|
154
|
+
"""Data bounding box ``(xmin, xmax, ymin, ymax)``; entries may be ``None``."""
|
|
155
|
+
return None
|
|
156
|
+
|
|
157
|
+
def points(self):
|
|
158
|
+
"""Representative data points (for legend placement)."""
|
|
159
|
+
return None
|
|
160
|
+
|
|
161
|
+
def legend_entries(self) -> list[dict]:
|
|
162
|
+
return []
|
|
163
|
+
|
|
164
|
+
def draw(self, ctx: RenderContext) -> None: # pragma: no cover - abstract
|
|
165
|
+
raise NotImplementedError
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _xy_bounds(x, y, xlog, ylog):
|
|
169
|
+
x, y = _f(x), _f(y)
|
|
170
|
+
ok = np.isfinite(x) & np.isfinite(y)
|
|
171
|
+
if xlog:
|
|
172
|
+
ok &= x > 0
|
|
173
|
+
if ylog:
|
|
174
|
+
ok &= y > 0
|
|
175
|
+
if not ok.any():
|
|
176
|
+
return None
|
|
177
|
+
return float(x[ok].min()), float(x[ok].max()), float(y[ok].min()), float(y[ok].max())
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
# ---------------------------------------------------------------------- markers
|
|
181
|
+
def draw_markers(ctx: RenderContext, px, py, marker, size: int, colors, outline=None):
|
|
182
|
+
"""Stamp sprites at pixel-center coordinates. ``colors`` is one RGB or one per point."""
|
|
183
|
+
px, py = _f(px), _f(py)
|
|
184
|
+
ok = np.isfinite(px) & np.isfinite(py)
|
|
185
|
+
if not ok.any():
|
|
186
|
+
return
|
|
187
|
+
cx = np.floor(px[ok] + 0.5).astype(np.int64)
|
|
188
|
+
cy = np.floor(py[ok] + 0.5).astype(np.int64)
|
|
189
|
+
mask = marker_mask(marker, size)
|
|
190
|
+
h, w = mask.shape
|
|
191
|
+
per_point = isinstance(colors, np.ndarray) and colors.ndim == 2
|
|
192
|
+
if outline is not None:
|
|
193
|
+
om = dilate(mask)
|
|
194
|
+
oy, ox = np.nonzero(om)
|
|
195
|
+
ctx.canvas.put(
|
|
196
|
+
(cx[:, None] + ox[None, :] - 2 - w // 2).ravel(),
|
|
197
|
+
(cy[:, None] + oy[None, :] - 2 - h // 2).ravel(),
|
|
198
|
+
outline,
|
|
199
|
+
)
|
|
200
|
+
my, mx = np.nonzero(mask)
|
|
201
|
+
xs = (cx[:, None] + mx[None, :] - w // 2).ravel()
|
|
202
|
+
ys = (cy[:, None] + my[None, :] - h // 2).ravel()
|
|
203
|
+
if per_point:
|
|
204
|
+
cols = np.repeat(colors[ok], len(mx), axis=0)
|
|
205
|
+
ctx.canvas.put_rgb(xs, ys, cols)
|
|
206
|
+
else:
|
|
207
|
+
ctx.canvas.put(xs, ys, colors)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
# ---------------------------------------------------------------------- lines
|
|
211
|
+
class Line(Artist):
|
|
212
|
+
def __init__(self, x, y, color, width=1, linestyle="-", marker=None, markersize=1,
|
|
213
|
+
label=None, shadow=True, zorder=2):
|
|
214
|
+
self.x, self.y = _f(x), _f(y)
|
|
215
|
+
self.color = color
|
|
216
|
+
self.width = int(width)
|
|
217
|
+
self.linestyle = linestyle
|
|
218
|
+
self.marker = marker
|
|
219
|
+
self.markersize = markersize
|
|
220
|
+
self.label = label
|
|
221
|
+
self.shadow = shadow
|
|
222
|
+
self.zorder = zorder
|
|
223
|
+
|
|
224
|
+
def bounds(self, xlog, ylog):
|
|
225
|
+
return _xy_bounds(self.x, self.y, xlog, ylog)
|
|
226
|
+
|
|
227
|
+
def points(self):
|
|
228
|
+
return self.x, self.y
|
|
229
|
+
|
|
230
|
+
def legend_entries(self):
|
|
231
|
+
if not self.label:
|
|
232
|
+
return []
|
|
233
|
+
return [dict(kind="line", label=self.label, color=self.color, linestyle=self.linestyle,
|
|
234
|
+
width=self.width, marker=self.marker)]
|
|
235
|
+
|
|
236
|
+
def draw(self, ctx):
|
|
237
|
+
px, py = ctx.tx(self.x), ctx.ty(self.y)
|
|
238
|
+
st = ctx.style
|
|
239
|
+
if self.linestyle not in ("none", "", None):
|
|
240
|
+
if self.shadow and st.line_halo is not None:
|
|
241
|
+
# background-colored outline keeps lines readable on dithered fills
|
|
242
|
+
ctx.canvas.polyline(px, py, st.color(st.line_halo), self.width + 2,
|
|
243
|
+
self.linestyle)
|
|
244
|
+
if self.shadow and st.line_shadow is not None:
|
|
245
|
+
ctx.canvas.polyline(px + 1, py + 1, st.color(st.line_shadow), self.width,
|
|
246
|
+
self.linestyle)
|
|
247
|
+
ctx.canvas.polyline(px, py, self.color, self.width, self.linestyle)
|
|
248
|
+
if self.marker:
|
|
249
|
+
outline = st.color(st.marker_outline) if st.marker_outline is not None else None
|
|
250
|
+
draw_markers(ctx, px, py, self.marker, self.markersize, self.color, outline)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
class RefLine(Artist):
|
|
254
|
+
"""Infinite horizontal or vertical line (``axhline``/``axvline``)."""
|
|
255
|
+
|
|
256
|
+
def __init__(self, value, orientation, color, linestyle="-", width=1, label=None):
|
|
257
|
+
self.value = float(value)
|
|
258
|
+
self.orientation = orientation
|
|
259
|
+
self.color = color
|
|
260
|
+
self.linestyle = linestyle
|
|
261
|
+
self.width = width
|
|
262
|
+
self.label = label
|
|
263
|
+
self.zorder = 1.5
|
|
264
|
+
|
|
265
|
+
def bounds(self, xlog, ylog):
|
|
266
|
+
if self.orientation == "h":
|
|
267
|
+
return None, None, self.value, self.value
|
|
268
|
+
return self.value, self.value, None, None
|
|
269
|
+
|
|
270
|
+
def legend_entries(self):
|
|
271
|
+
if not self.label:
|
|
272
|
+
return []
|
|
273
|
+
return [dict(kind="line", label=self.label, color=self.color, linestyle=self.linestyle,
|
|
274
|
+
width=self.width, marker=None)]
|
|
275
|
+
|
|
276
|
+
def draw(self, ctx):
|
|
277
|
+
x0, y0, x1, y1 = ctx.rect
|
|
278
|
+
if self.orientation == "h":
|
|
279
|
+
y = float(ctx.ty(self.value))
|
|
280
|
+
ctx.canvas.polyline([x0, x1 - 1], [y, y], self.color, self.width, self.linestyle)
|
|
281
|
+
else:
|
|
282
|
+
x = float(ctx.tx(self.value))
|
|
283
|
+
ctx.canvas.polyline([x, x], [y0, y1 - 1], self.color, self.width, self.linestyle)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
class Span(Artist):
|
|
287
|
+
"""Shaded band across the axes (``axhspan``/``axvspan``)."""
|
|
288
|
+
|
|
289
|
+
def __init__(self, v0, v1, orientation, color, alpha=0.5, label=None):
|
|
290
|
+
self.v0, self.v1 = float(v0), float(v1)
|
|
291
|
+
self.orientation = orientation
|
|
292
|
+
self.color = color
|
|
293
|
+
self.alpha = alpha
|
|
294
|
+
self.label = label
|
|
295
|
+
self.zorder = 1
|
|
296
|
+
|
|
297
|
+
def bounds(self, xlog, ylog):
|
|
298
|
+
lo, hi = min(self.v0, self.v1), max(self.v0, self.v1)
|
|
299
|
+
if self.orientation == "h":
|
|
300
|
+
return None, None, lo, hi
|
|
301
|
+
return lo, hi, None, None
|
|
302
|
+
|
|
303
|
+
def legend_entries(self):
|
|
304
|
+
if not self.label:
|
|
305
|
+
return []
|
|
306
|
+
return [dict(kind="patch", label=self.label, color=self.color, alpha=self.alpha)]
|
|
307
|
+
|
|
308
|
+
def draw(self, ctx):
|
|
309
|
+
x0, y0, x1, y1 = ctx.rect
|
|
310
|
+
if self.orientation == "h":
|
|
311
|
+
a, b = ctx.span(float(ctx.ty(self.v0)), float(ctx.ty(self.v1)))
|
|
312
|
+
ctx.canvas.fill_rect(x0, a, x1, b, self.color, self.alpha)
|
|
313
|
+
else:
|
|
314
|
+
a, b = ctx.span(float(ctx.tx(self.v0)), float(ctx.tx(self.v1)))
|
|
315
|
+
ctx.canvas.fill_rect(a, y0, b, y1, self.color, self.alpha)
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
# ---------------------------------------------------------------------- scatter
|
|
319
|
+
class Scatter(Artist):
|
|
320
|
+
def __init__(self, x, y, color, marker="o", size=1, values=None, ramp: Ramp | None = None,
|
|
321
|
+
norm: Norm | None = None, outline=None, label=None):
|
|
322
|
+
self.x, self.y = _f(x), _f(y)
|
|
323
|
+
self.color = color
|
|
324
|
+
self.marker = marker
|
|
325
|
+
self.size = size
|
|
326
|
+
self.values = None if values is None else _f(values)
|
|
327
|
+
self.ramp = ramp
|
|
328
|
+
self.norm = norm
|
|
329
|
+
self.outline = outline
|
|
330
|
+
self.label = label
|
|
331
|
+
self.zorder = 3
|
|
332
|
+
|
|
333
|
+
def bounds(self, xlog, ylog):
|
|
334
|
+
return _xy_bounds(self.x, self.y, xlog, ylog)
|
|
335
|
+
|
|
336
|
+
def points(self):
|
|
337
|
+
return self.x, self.y
|
|
338
|
+
|
|
339
|
+
def legend_entries(self):
|
|
340
|
+
if not self.label:
|
|
341
|
+
return []
|
|
342
|
+
color = self.color
|
|
343
|
+
if self.values is not None and self.ramp is not None:
|
|
344
|
+
color = self.ramp.color_at(0.75)
|
|
345
|
+
return [dict(kind="marker", label=self.label, color=color, marker=self.marker)]
|
|
346
|
+
|
|
347
|
+
def draw(self, ctx):
|
|
348
|
+
px, py = ctx.tx(self.x), ctx.ty(self.y)
|
|
349
|
+
colors: Any = self.color
|
|
350
|
+
if self.values is not None and self.ramp is not None:
|
|
351
|
+
t = self.norm(self.values)
|
|
352
|
+
colors = self.ramp.map(t[None, :], dither=False)[0]
|
|
353
|
+
order = np.argsort(t, kind="stable") # draw high values on top
|
|
354
|
+
px, py, colors = px[order], py[order], colors[order]
|
|
355
|
+
draw_markers(ctx, px, py, self.marker, self.size, colors, self.outline)
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
# ---------------------------------------------------------------------- bars
|
|
359
|
+
class Bars(Artist):
|
|
360
|
+
def __init__(self, pos, length, width, base, colors, orientation="v", alpha=1.0,
|
|
361
|
+
outline="auto", label=None):
|
|
362
|
+
self.pos = _f(pos)
|
|
363
|
+
self.length = _f(length)
|
|
364
|
+
n = len(self.pos)
|
|
365
|
+
self.width = np.broadcast_to(_f(width), (n,)) if np.size(width) > 1 else np.full(n, width)
|
|
366
|
+
self.base = np.broadcast_to(_f(base), (n,)) if np.size(base) > 1 else np.full(n, base)
|
|
367
|
+
self.base = np.asarray(self.base, dtype=np.float64)
|
|
368
|
+
self.width = np.asarray(self.width, dtype=np.float64)
|
|
369
|
+
self.colors = colors # list of RGB per bar
|
|
370
|
+
self.orientation = orientation
|
|
371
|
+
self.alpha = alpha
|
|
372
|
+
self.outline = outline
|
|
373
|
+
self.label = label
|
|
374
|
+
self.zorder = 2
|
|
375
|
+
if orientation == "v":
|
|
376
|
+
self.sticky_y = tuple(np.unique(self.base))
|
|
377
|
+
else:
|
|
378
|
+
self.sticky_x = tuple(np.unique(self.base))
|
|
379
|
+
|
|
380
|
+
def _extent(self):
|
|
381
|
+
a = self.pos - self.width / 2
|
|
382
|
+
b = self.pos + self.width / 2
|
|
383
|
+
lo = np.minimum(self.base, self.base + self.length)
|
|
384
|
+
hi = np.maximum(self.base, self.base + self.length)
|
|
385
|
+
return a, b, lo, hi
|
|
386
|
+
|
|
387
|
+
def bounds(self, xlog, ylog):
|
|
388
|
+
a, b, lo, hi = self._extent()
|
|
389
|
+
if self.orientation == "v":
|
|
390
|
+
return _bounds4(a, b, lo, hi, xlog, ylog)
|
|
391
|
+
return _bounds4(lo, hi, a, b, xlog, ylog)
|
|
392
|
+
|
|
393
|
+
def points(self):
|
|
394
|
+
a, b, lo, hi = self._extent()
|
|
395
|
+
top = self.base + self.length
|
|
396
|
+
if self.orientation == "v":
|
|
397
|
+
return np.concatenate([self.pos, a, b]), np.concatenate([top, top, top])
|
|
398
|
+
return np.concatenate([top, top, top]), np.concatenate([self.pos, a, b])
|
|
399
|
+
|
|
400
|
+
def legend_entries(self):
|
|
401
|
+
if not self.label:
|
|
402
|
+
return []
|
|
403
|
+
return [dict(kind="patch", label=self.label, color=self.colors[0], alpha=self.alpha,
|
|
404
|
+
outline=self.outline)]
|
|
405
|
+
|
|
406
|
+
def draw(self, ctx):
|
|
407
|
+
st = ctx.style
|
|
408
|
+
a, b, _, _ = self._extent()
|
|
409
|
+
tops = self.base + self.length
|
|
410
|
+
for i in range(len(self.pos)):
|
|
411
|
+
if not (np.isfinite(self.length[i]) and np.isfinite(self.pos[i])):
|
|
412
|
+
continue
|
|
413
|
+
color = self.colors[i % len(self.colors)]
|
|
414
|
+
minimum = 1 if self.length[i] != 0 else 0
|
|
415
|
+
if self.orientation == "v":
|
|
416
|
+
x0, x1 = ctx.span(float(ctx.tx(a[i])), float(ctx.tx(b[i])), 1)
|
|
417
|
+
y0, y1 = ctx.span(float(ctx.ty(self.base[i])), float(ctx.ty(tops[i])), minimum)
|
|
418
|
+
else:
|
|
419
|
+
x0, x1 = ctx.span(float(ctx.tx(self.base[i])), float(ctx.tx(tops[i])), minimum)
|
|
420
|
+
y0, y1 = ctx.span(float(ctx.ty(a[i])), float(ctx.ty(b[i])), 1)
|
|
421
|
+
draw_box(ctx.canvas, st, x0, y0, x1, y1, color, self.alpha, self.outline,
|
|
422
|
+
shading=st.bar_shading)
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def _bounds4(x0, x1, y0, y1, xlog, ylog):
|
|
426
|
+
xr = _finite_range(np.concatenate([_f(x0), _f(x1)]), xlog)
|
|
427
|
+
yr = _finite_range(np.concatenate([_f(y0), _f(y1)]), ylog)
|
|
428
|
+
if xr is None and yr is None:
|
|
429
|
+
return None
|
|
430
|
+
return (xr[0] if xr else None, xr[1] if xr else None,
|
|
431
|
+
yr[0] if yr else None, yr[1] if yr else None)
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def outline_color(style, color, outline):
|
|
435
|
+
if outline is None:
|
|
436
|
+
return None
|
|
437
|
+
if isinstance(outline, str) and outline == "auto":
|
|
438
|
+
return style.shade(color, -0.55)
|
|
439
|
+
return style.color(outline)
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def draw_box(canvas, style, x0, y0, x1, y1, color, alpha=1.0, outline="auto", shading=False):
|
|
443
|
+
"""Filled rectangle with optional pixel-art bevel shading and outline."""
|
|
444
|
+
if x1 <= x0 or y1 <= y0:
|
|
445
|
+
return
|
|
446
|
+
canvas.fill_rect(x0, y0, x1, y1, color, alpha)
|
|
447
|
+
w, h = x1 - x0, y1 - y0
|
|
448
|
+
oc = outline_color(style, color, outline)
|
|
449
|
+
if shading and w >= 4 and h >= 3 and alpha >= 1:
|
|
450
|
+
hi = style.shade(color, 0.45)
|
|
451
|
+
lo = style.shade(color, -0.35)
|
|
452
|
+
canvas.fill_rect(x0 + 1, y0 + 1, x0 + 2, y1 - 1, hi)
|
|
453
|
+
canvas.fill_rect(x0 + 1, y0 + 1, x1 - 1, y0 + 2, hi)
|
|
454
|
+
canvas.fill_rect(x1 - 2, y0 + 2, x1 - 1, y1 - 1, lo)
|
|
455
|
+
if oc is not None and w >= 3 and h >= 2:
|
|
456
|
+
canvas.rect(x0, y0, x1, y1, oc)
|
|
457
|
+
elif oc is not None and alpha < 1:
|
|
458
|
+
canvas.rect(x0, y0, x1, y1, color)
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
# ---------------------------------------------------------------------- fills
|
|
462
|
+
class Polygon(Artist):
|
|
463
|
+
"""Filled polygon (used by ``fill`` and ``fill_between``)."""
|
|
464
|
+
|
|
465
|
+
def __init__(self, x, y, color, alpha=1.0, edge=None, label=None, sticky_y=()):
|
|
466
|
+
self.x, self.y = _f(x), _f(y)
|
|
467
|
+
self.color = color
|
|
468
|
+
self.alpha = alpha
|
|
469
|
+
self.edge = edge
|
|
470
|
+
self.label = label
|
|
471
|
+
self.zorder = 1.8
|
|
472
|
+
self.sticky_y = sticky_y
|
|
473
|
+
|
|
474
|
+
def bounds(self, xlog, ylog):
|
|
475
|
+
return _xy_bounds(self.x, self.y, xlog, ylog)
|
|
476
|
+
|
|
477
|
+
def points(self):
|
|
478
|
+
return self.x, self.y
|
|
479
|
+
|
|
480
|
+
def legend_entries(self):
|
|
481
|
+
if not self.label:
|
|
482
|
+
return []
|
|
483
|
+
return [dict(kind="patch", label=self.label, color=self.color, alpha=self.alpha,
|
|
484
|
+
outline=None)]
|
|
485
|
+
|
|
486
|
+
def draw(self, ctx):
|
|
487
|
+
px, py = ctx.tx(self.x), ctx.ty(self.y)
|
|
488
|
+
ctx.canvas.fill_polygon(px, py, self.color, self.alpha)
|
|
489
|
+
if self.edge is not None:
|
|
490
|
+
ctx.canvas.polyline(np.append(px, px[:1]), np.append(py, py[:1]), self.edge)
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
class FillBetween(Artist):
|
|
494
|
+
def __init__(self, x, y1, y2, color, alpha=1.0, edge=None, label=None):
|
|
495
|
+
self.x = _f(x)
|
|
496
|
+
n = len(self.x)
|
|
497
|
+
self.y1 = np.broadcast_to(_f(y1), (n,)) if np.size(y1) > 1 else np.full(n, float(y1))
|
|
498
|
+
self.y2 = np.broadcast_to(_f(y2), (n,)) if np.size(y2) > 1 else np.full(n, float(y2))
|
|
499
|
+
self.color = color
|
|
500
|
+
self.alpha = alpha
|
|
501
|
+
self.edge = edge
|
|
502
|
+
self.label = label
|
|
503
|
+
self.zorder = 1.8
|
|
504
|
+
sticky = []
|
|
505
|
+
if np.size(y2) == 1:
|
|
506
|
+
sticky.append(float(y2))
|
|
507
|
+
if np.size(y1) == 1:
|
|
508
|
+
sticky.append(float(y1))
|
|
509
|
+
self.sticky_y = tuple(sticky)
|
|
510
|
+
|
|
511
|
+
def bounds(self, xlog, ylog):
|
|
512
|
+
return _xy_bounds(np.concatenate([self.x, self.x]),
|
|
513
|
+
np.concatenate([self.y1, self.y2]), xlog, ylog)
|
|
514
|
+
|
|
515
|
+
def points(self):
|
|
516
|
+
return np.concatenate([self.x, self.x]), np.concatenate([self.y1, self.y2])
|
|
517
|
+
|
|
518
|
+
def legend_entries(self):
|
|
519
|
+
if not self.label:
|
|
520
|
+
return []
|
|
521
|
+
return [dict(kind="patch", label=self.label, color=self.color, alpha=self.alpha,
|
|
522
|
+
outline=None)]
|
|
523
|
+
|
|
524
|
+
def draw(self, ctx):
|
|
525
|
+
ok = np.isfinite(self.x) & np.isfinite(self.y1) & np.isfinite(self.y2)
|
|
526
|
+
# split into contiguous finite runs so NaNs produce gaps
|
|
527
|
+
idx = np.flatnonzero(ok)
|
|
528
|
+
if idx.size == 0:
|
|
529
|
+
return
|
|
530
|
+
runs = np.split(idx, np.flatnonzero(np.diff(idx) > 1) + 1)
|
|
531
|
+
for r in runs:
|
|
532
|
+
if r.size < 2:
|
|
533
|
+
continue
|
|
534
|
+
px = ctx.tx(self.x[r])
|
|
535
|
+
p1, p2 = ctx.ty(self.y1[r]), ctx.ty(self.y2[r])
|
|
536
|
+
ctx.canvas.fill_polygon(np.concatenate([px, px[::-1]]),
|
|
537
|
+
np.concatenate([p1, p2[::-1]]), self.color, self.alpha)
|
|
538
|
+
if self.edge is not None:
|
|
539
|
+
ctx.canvas.polyline(px, p1, self.edge)
|
|
540
|
+
ctx.canvas.polyline(px, p2, self.edge)
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
# ---------------------------------------------------------------------- error bars
|
|
544
|
+
class ErrorBars(Artist):
|
|
545
|
+
def __init__(self, x, y, xerr, yerr, color, capsize=1, marker="o", markersize=1,
|
|
546
|
+
linestyle="none", label=None):
|
|
547
|
+
self.x, self.y = _f(x), _f(y)
|
|
548
|
+
self.xerr = _err(xerr, len(self.x))
|
|
549
|
+
self.yerr = _err(yerr, len(self.x))
|
|
550
|
+
self.color = color
|
|
551
|
+
self.capsize = capsize
|
|
552
|
+
self.marker = marker
|
|
553
|
+
self.markersize = markersize
|
|
554
|
+
self.linestyle = linestyle
|
|
555
|
+
self.label = label
|
|
556
|
+
self.zorder = 2.5
|
|
557
|
+
|
|
558
|
+
def bounds(self, xlog, ylog):
|
|
559
|
+
xs, ys = [self.x], [self.y]
|
|
560
|
+
if self.xerr is not None:
|
|
561
|
+
xs += [self.x - self.xerr[0], self.x + self.xerr[1]]
|
|
562
|
+
if self.yerr is not None:
|
|
563
|
+
ys += [self.y - self.yerr[0], self.y + self.yerr[1]]
|
|
564
|
+
return _bounds4(np.concatenate(xs), np.concatenate(xs), np.concatenate(ys),
|
|
565
|
+
np.concatenate(ys), xlog, ylog)
|
|
566
|
+
|
|
567
|
+
def points(self):
|
|
568
|
+
return self.x, self.y
|
|
569
|
+
|
|
570
|
+
def legend_entries(self):
|
|
571
|
+
if not self.label:
|
|
572
|
+
return []
|
|
573
|
+
return [dict(kind="line", label=self.label, color=self.color, linestyle=self.linestyle,
|
|
574
|
+
width=1, marker=self.marker or "+")]
|
|
575
|
+
|
|
576
|
+
def draw(self, ctx):
|
|
577
|
+
cv, c, cap = ctx.canvas, self.color, self.capsize
|
|
578
|
+
px, py = ctx.tx(self.x), ctx.ty(self.y)
|
|
579
|
+
st = ctx.style
|
|
580
|
+
if self.linestyle not in ("none", "", None):
|
|
581
|
+
cv.polyline(px, py, c, 1, self.linestyle)
|
|
582
|
+
nan = np.full_like(px, np.nan)
|
|
583
|
+
if self.yerr is not None:
|
|
584
|
+
ylo, yhi = ctx.ty(self.y - self.yerr[0]), ctx.ty(self.y + self.yerr[1])
|
|
585
|
+
cv.polyline(np.column_stack([px, px, nan]).ravel(),
|
|
586
|
+
np.column_stack([ylo, yhi, nan]).ravel(), c)
|
|
587
|
+
if cap:
|
|
588
|
+
for yy in (ylo, yhi):
|
|
589
|
+
cv.polyline(np.column_stack([px - cap, px + cap, nan]).ravel(),
|
|
590
|
+
np.column_stack([yy, yy, nan]).ravel(), c)
|
|
591
|
+
if self.xerr is not None:
|
|
592
|
+
xlo, xhi = ctx.tx(self.x - self.xerr[0]), ctx.tx(self.x + self.xerr[1])
|
|
593
|
+
cv.polyline(np.column_stack([xlo, xhi, nan]).ravel(),
|
|
594
|
+
np.column_stack([py, py, nan]).ravel(), c)
|
|
595
|
+
if cap:
|
|
596
|
+
for xx in (xlo, xhi):
|
|
597
|
+
cv.polyline(np.column_stack([xx, xx, nan]).ravel(),
|
|
598
|
+
np.column_stack([py - cap, py + cap, nan]).ravel(), c)
|
|
599
|
+
if self.marker:
|
|
600
|
+
outline = st.color(st.marker_outline) if st.marker_outline is not None else None
|
|
601
|
+
draw_markers(ctx, px, py, self.marker, self.markersize, c, outline)
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def _err(e, n):
|
|
605
|
+
if e is None:
|
|
606
|
+
return None
|
|
607
|
+
e = np.asarray(e, dtype=np.float64)
|
|
608
|
+
if e.ndim == 0:
|
|
609
|
+
e = np.full(n, float(e))
|
|
610
|
+
if e.ndim == 1:
|
|
611
|
+
return np.abs(e), np.abs(e)
|
|
612
|
+
return np.abs(e[0]), np.abs(e[1])
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
class Stems(Artist):
|
|
616
|
+
def __init__(self, x, y, bottom, color, marker="o", markersize=1, label=None):
|
|
617
|
+
self.x, self.y = _f(x), _f(y)
|
|
618
|
+
self.bottom = float(bottom)
|
|
619
|
+
self.color = color
|
|
620
|
+
self.marker = marker
|
|
621
|
+
self.markersize = markersize
|
|
622
|
+
self.label = label
|
|
623
|
+
self.sticky_y = (self.bottom,)
|
|
624
|
+
|
|
625
|
+
def bounds(self, xlog, ylog):
|
|
626
|
+
return _bounds4(self.x, self.x, np.append(self.y, self.bottom),
|
|
627
|
+
np.append(self.y, self.bottom), xlog, ylog)
|
|
628
|
+
|
|
629
|
+
def points(self):
|
|
630
|
+
return self.x, self.y
|
|
631
|
+
|
|
632
|
+
def legend_entries(self):
|
|
633
|
+
if not self.label:
|
|
634
|
+
return []
|
|
635
|
+
return [dict(kind="marker", label=self.label, color=self.color, marker=self.marker)]
|
|
636
|
+
|
|
637
|
+
def draw(self, ctx):
|
|
638
|
+
px, py = ctx.tx(self.x), ctx.ty(self.y)
|
|
639
|
+
pb = np.full_like(py, float(ctx.ty(self.bottom)))
|
|
640
|
+
nan = np.full_like(px, np.nan)
|
|
641
|
+
ctx.canvas.polyline(np.column_stack([px, px, nan]).ravel(),
|
|
642
|
+
np.column_stack([pb, py, nan]).ravel(), self.color)
|
|
643
|
+
if self.marker:
|
|
644
|
+
st = ctx.style
|
|
645
|
+
outline = st.color(st.marker_outline) if st.marker_outline is not None else None
|
|
646
|
+
draw_markers(ctx, px, py, self.marker, self.markersize, self.color, outline)
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
# ---------------------------------------------------------------------- images
|
|
650
|
+
class Image(Artist):
|
|
651
|
+
"""Raster data drawn with nearest-neighbour lookup on (possibly irregular) cell edges."""
|
|
652
|
+
|
|
653
|
+
zorder = 1
|
|
654
|
+
|
|
655
|
+
def __init__(self, data, x_edges, y_edges, ramp: Ramp | None, norm: Norm | None,
|
|
656
|
+
dither=True, label=None):
|
|
657
|
+
self.data = np.asarray(data)
|
|
658
|
+
self.x_edges = _f(x_edges)
|
|
659
|
+
self.y_edges = _f(y_edges)
|
|
660
|
+
self.ramp = ramp
|
|
661
|
+
self.norm = norm
|
|
662
|
+
self.dither = dither
|
|
663
|
+
self.label = label
|
|
664
|
+
self.sticky_x = (self.x_edges[0], self.x_edges[-1])
|
|
665
|
+
self.sticky_y = (self.y_edges[0], self.y_edges[-1])
|
|
666
|
+
self.levels = None
|
|
667
|
+
|
|
668
|
+
def bounds(self, xlog, ylog):
|
|
669
|
+
return _bounds4(self.x_edges, self.x_edges, self.y_edges, self.y_edges, xlog, ylog)
|
|
670
|
+
|
|
671
|
+
def _lookup(self, ctx):
|
|
672
|
+
"""Pixel region covered by the image and the data indices of each pixel."""
|
|
673
|
+
x0, y0, x1, y1 = ctx.rect
|
|
674
|
+
cols = np.arange(x0, x1)
|
|
675
|
+
rows = np.arange(y0, y1)
|
|
676
|
+
dx = ctx.inv_x(cols)
|
|
677
|
+
dy = ctx.inv_y(rows)
|
|
678
|
+
j, jok = _edge_index(self.x_edges, dx)
|
|
679
|
+
i, iok = _edge_index(self.y_edges, dy)
|
|
680
|
+
return x0, y0, i, iok, j, jok
|
|
681
|
+
|
|
682
|
+
def sample(self, ctx):
|
|
683
|
+
x0, y0, i, iok, j, jok = self._lookup(ctx)
|
|
684
|
+
vals = self.data[i[:, None], j[None, :]]
|
|
685
|
+
valid = iok[:, None] & jok[None, :]
|
|
686
|
+
return x0, y0, vals, valid
|
|
687
|
+
|
|
688
|
+
def draw(self, ctx):
|
|
689
|
+
x0, y0, vals, valid = self.sample(ctx)
|
|
690
|
+
if not valid.any():
|
|
691
|
+
return
|
|
692
|
+
if vals.ndim == 3:
|
|
693
|
+
rgb = vals[..., :3]
|
|
694
|
+
if vals.shape[-1] == 4:
|
|
695
|
+
a = vals[..., 3]
|
|
696
|
+
valid = valid & (a > (0.5 if a.dtype.kind == "f" else 127))
|
|
697
|
+
st = ctx.style
|
|
698
|
+
img = pixelate(rgb, palette=st.palette, bits=st.bits or 8, dither=self.dither)
|
|
699
|
+
else:
|
|
700
|
+
vals = vals.astype(np.float64)
|
|
701
|
+
valid = valid & np.isfinite(vals)
|
|
702
|
+
t = self.norm(vals)
|
|
703
|
+
valid = valid & np.isfinite(t)
|
|
704
|
+
img = self.ramp.map(t, self.dither, x0, y0)
|
|
705
|
+
ctx.canvas.blit(img, x0, y0, mask=valid)
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
def _edge_index(edges: np.ndarray, v: np.ndarray):
|
|
709
|
+
"""Cell index for values ``v`` given monotonic cell ``edges``."""
|
|
710
|
+
increasing = edges[-1] >= edges[0]
|
|
711
|
+
e = edges if increasing else edges[::-1]
|
|
712
|
+
idx = np.searchsorted(e, v, side="right") - 1
|
|
713
|
+
ok = (idx >= 0) & (idx < len(e) - 1) & np.isfinite(v)
|
|
714
|
+
idx = np.clip(idx, 0, len(e) - 2)
|
|
715
|
+
if not increasing:
|
|
716
|
+
idx = len(e) - 2 - idx
|
|
717
|
+
return idx, ok
|
|
718
|
+
|
|
719
|
+
|
|
720
|
+
class FilledContour(Artist):
|
|
721
|
+
"""Filled contour bands rasterized at pixel resolution with bilinear interpolation."""
|
|
722
|
+
|
|
723
|
+
zorder = 1
|
|
724
|
+
|
|
725
|
+
def __init__(self, x, y, z, levels, ramp: Ramp, dither=True, label=None):
|
|
726
|
+
self.x, self.y = _f(x), _f(y)
|
|
727
|
+
self.z = np.asarray(z, dtype=np.float64)
|
|
728
|
+
self.levels = np.asarray(levels, dtype=np.float64)
|
|
729
|
+
self.ramp = ramp
|
|
730
|
+
self.dither = dither
|
|
731
|
+
self.label = label
|
|
732
|
+
self.norm = Norm(self.levels[0], self.levels[-1])
|
|
733
|
+
self.sticky_x = (self.x.min(), self.x.max())
|
|
734
|
+
self.sticky_y = (self.y.min(), self.y.max())
|
|
735
|
+
|
|
736
|
+
def bounds(self, xlog, ylog):
|
|
737
|
+
return _bounds4(self.x, self.x, self.y, self.y, xlog, ylog)
|
|
738
|
+
|
|
739
|
+
def band_value(self, k: int) -> float:
|
|
740
|
+
n = len(self.levels) - 1
|
|
741
|
+
return (k + 0.5) / n if n > 0 else 0.5
|
|
742
|
+
|
|
743
|
+
def draw(self, ctx):
|
|
744
|
+
x0, y0, x1, y1 = ctx.rect
|
|
745
|
+
dx = ctx.inv_x(np.arange(x0, x1))
|
|
746
|
+
dy = ctx.inv_y(np.arange(y0, y1))
|
|
747
|
+
fj = _frac_index(self.x, dx)
|
|
748
|
+
fi = _frac_index(self.y, dy)
|
|
749
|
+
z = _bilinear(self.z, fi, fj)
|
|
750
|
+
n = len(self.levels) - 1
|
|
751
|
+
band = np.digitize(z, self.levels) - 1
|
|
752
|
+
valid = np.isfinite(z) & (band >= 0) & (band < n)
|
|
753
|
+
# values exactly on the top level belong to the last band
|
|
754
|
+
top = np.isclose(z, self.levels[-1])
|
|
755
|
+
band = np.where(top, n - 1, band)
|
|
756
|
+
valid |= top
|
|
757
|
+
t = (np.clip(band, 0, n - 1) + 0.5) / max(n, 1)
|
|
758
|
+
img = self.ramp.map(t, self.dither, x0, y0)
|
|
759
|
+
ctx.canvas.blit(img, x0, y0, mask=valid)
|
|
760
|
+
|
|
761
|
+
|
|
762
|
+
def _frac_index(coords: np.ndarray, v: np.ndarray) -> np.ndarray:
|
|
763
|
+
"""Fractional index of ``v`` along monotonic ``coords``; NaN outside."""
|
|
764
|
+
if coords[0] > coords[-1]:
|
|
765
|
+
coords = coords[::-1]
|
|
766
|
+
f = np.interp(v, coords, np.arange(len(coords))[::-1].astype(float),
|
|
767
|
+
left=np.nan, right=np.nan)
|
|
768
|
+
else:
|
|
769
|
+
f = np.interp(v, coords, np.arange(len(coords), dtype=float), left=np.nan, right=np.nan)
|
|
770
|
+
return f
|
|
771
|
+
|
|
772
|
+
|
|
773
|
+
def _bilinear(z: np.ndarray, fi: np.ndarray, fj: np.ndarray) -> np.ndarray:
|
|
774
|
+
ny, nx = z.shape
|
|
775
|
+
ii = np.clip(np.nan_to_num(fi, nan=0.0), 0, ny - 1)
|
|
776
|
+
jj = np.clip(np.nan_to_num(fj, nan=0.0), 0, nx - 1)
|
|
777
|
+
i0 = np.minimum(np.floor(ii).astype(int), max(ny - 2, 0))
|
|
778
|
+
j0 = np.minimum(np.floor(jj).astype(int), max(nx - 2, 0))
|
|
779
|
+
i1 = np.minimum(i0 + 1, ny - 1)
|
|
780
|
+
j1 = np.minimum(j0 + 1, nx - 1)
|
|
781
|
+
ti = (ii - i0)[:, None]
|
|
782
|
+
tj = (jj - j0)[None, :]
|
|
783
|
+
z00 = z[i0[:, None], j0[None, :]]
|
|
784
|
+
z01 = z[i0[:, None], j1[None, :]]
|
|
785
|
+
z10 = z[i1[:, None], j0[None, :]]
|
|
786
|
+
z11 = z[i1[:, None], j1[None, :]]
|
|
787
|
+
out = (z00 * (1 - ti) * (1 - tj) + z01 * (1 - ti) * tj + z10 * ti * (1 - tj)
|
|
788
|
+
+ z11 * ti * tj)
|
|
789
|
+
out[np.isnan(fi), :] = np.nan
|
|
790
|
+
out[:, np.isnan(fj)] = np.nan
|
|
791
|
+
return out
|
|
792
|
+
|
|
793
|
+
|
|
794
|
+
# marching squares: case -> list of (edge_a, edge_b)
|
|
795
|
+
_MS_TABLE = {
|
|
796
|
+
1: [(3, 0)], 2: [(0, 1)], 3: [(3, 1)], 4: [(1, 2)], 5: [(3, 0), (1, 2)], 6: [(0, 2)],
|
|
797
|
+
7: [(3, 2)], 8: [(2, 3)], 9: [(0, 2)], 10: [(0, 1), (2, 3)], 11: [(1, 2)], 12: [(1, 3)],
|
|
798
|
+
13: [(0, 1)], 14: [(3, 0)],
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
|
|
802
|
+
def marching_squares(x, y, z, level):
|
|
803
|
+
"""Contour line segments of ``z`` at ``level`` as NaN-separated x/y arrays."""
|
|
804
|
+
z = np.asarray(z, dtype=np.float64)
|
|
805
|
+
c0, c1 = z[:-1, :-1], z[:-1, 1:]
|
|
806
|
+
c2, c3 = z[1:, 1:], z[1:, :-1]
|
|
807
|
+
case = ((c0 > level) * 1 + (c1 > level) * 2 + (c2 > level) * 4 + (c3 > level) * 8)
|
|
808
|
+
ok = np.isfinite(c0) & np.isfinite(c1) & np.isfinite(c2) & np.isfinite(c3)
|
|
809
|
+
case = np.where(ok, case, 0)
|
|
810
|
+
ii, jj = np.mgrid[0 : z.shape[0] - 1, 0 : z.shape[1] - 1]
|
|
811
|
+
|
|
812
|
+
def interp(a, b):
|
|
813
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
814
|
+
t = (level - a) / (b - a)
|
|
815
|
+
return np.clip(np.nan_to_num(t, nan=0.5), 0, 1)
|
|
816
|
+
|
|
817
|
+
# edge points in fractional (i, j) index space
|
|
818
|
+
edges = [
|
|
819
|
+
(ii, jj + interp(c0, c1)),
|
|
820
|
+
(ii + interp(c1, c2), jj + 1),
|
|
821
|
+
(ii + 1, jj + interp(c3, c2)),
|
|
822
|
+
(ii + interp(c0, c3), jj),
|
|
823
|
+
]
|
|
824
|
+
xs, ys = [], []
|
|
825
|
+
for k, pairs in _MS_TABLE.items():
|
|
826
|
+
sel = case == k
|
|
827
|
+
if not sel.any():
|
|
828
|
+
continue
|
|
829
|
+
for ea, eb in pairs:
|
|
830
|
+
ia, ja = edges[ea][0][sel], edges[ea][1][sel]
|
|
831
|
+
ib, jb = edges[eb][0][sel], edges[eb][1][sel]
|
|
832
|
+
nan = np.full(ia.shape, np.nan)
|
|
833
|
+
xs.append(np.column_stack([ja, jb, nan]).ravel())
|
|
834
|
+
ys.append(np.column_stack([ia, ib, nan]).ravel())
|
|
835
|
+
if not xs:
|
|
836
|
+
return np.array([]), np.array([])
|
|
837
|
+
fj = np.concatenate(xs)
|
|
838
|
+
fi = np.concatenate(ys)
|
|
839
|
+
gx = np.interp(fj, np.arange(len(x)), x)
|
|
840
|
+
gy = np.interp(fi, np.arange(len(y)), y)
|
|
841
|
+
gx[np.isnan(fj)] = np.nan
|
|
842
|
+
gy[np.isnan(fi)] = np.nan
|
|
843
|
+
return gx, gy
|
|
844
|
+
|
|
845
|
+
|
|
846
|
+
class ContourLines(Artist):
|
|
847
|
+
def __init__(self, x, y, z, levels, colors, linestyles, width=1, label=None):
|
|
848
|
+
self.x, self.y = _f(x), _f(y)
|
|
849
|
+
self.levels = np.asarray(levels, dtype=np.float64)
|
|
850
|
+
self.colors = colors
|
|
851
|
+
self.linestyles = linestyles
|
|
852
|
+
self.width = width
|
|
853
|
+
self.label = label
|
|
854
|
+
self.segments = [marching_squares(self.x, self.y, z, lv) for lv in self.levels]
|
|
855
|
+
self.sticky_x = (self.x.min(), self.x.max())
|
|
856
|
+
self.sticky_y = (self.y.min(), self.y.max())
|
|
857
|
+
self.zorder = 2
|
|
858
|
+
|
|
859
|
+
def bounds(self, xlog, ylog):
|
|
860
|
+
return _bounds4(self.x, self.x, self.y, self.y, xlog, ylog)
|
|
861
|
+
|
|
862
|
+
def legend_entries(self):
|
|
863
|
+
if not self.label:
|
|
864
|
+
return []
|
|
865
|
+
return [dict(kind="line", label=self.label, color=self.colors[-1], linestyle="-",
|
|
866
|
+
width=self.width, marker=None)]
|
|
867
|
+
|
|
868
|
+
def draw(self, ctx):
|
|
869
|
+
for k, (sx, sy) in enumerate(self.segments):
|
|
870
|
+
if sx.size == 0:
|
|
871
|
+
continue
|
|
872
|
+
ctx.canvas.polyline(ctx.tx(sx), ctx.ty(sy), self.colors[k], self.width,
|
|
873
|
+
self.linestyles[k])
|
|
874
|
+
|
|
875
|
+
|
|
876
|
+
# ---------------------------------------------------------------------- quiver
|
|
877
|
+
class Quiver(Artist):
|
|
878
|
+
def __init__(self, x, y, u, v, colors, scale=None, pivot="tail", label=None):
|
|
879
|
+
self.x, self.y, self.u, self.v = _f(x), _f(y), _f(u), _f(v)
|
|
880
|
+
self.colors = colors # RGB or (n, 3) array
|
|
881
|
+
self.scale = scale
|
|
882
|
+
self.pivot = pivot
|
|
883
|
+
self.label = label
|
|
884
|
+
self.zorder = 2.5
|
|
885
|
+
|
|
886
|
+
def bounds(self, xlog, ylog):
|
|
887
|
+
return _xy_bounds(self.x, self.y, xlog, ylog)
|
|
888
|
+
|
|
889
|
+
def points(self):
|
|
890
|
+
return self.x, self.y
|
|
891
|
+
|
|
892
|
+
def legend_entries(self):
|
|
893
|
+
if not self.label:
|
|
894
|
+
return []
|
|
895
|
+
c = self.colors if not isinstance(self.colors, np.ndarray) else tuple(self.colors[-1])
|
|
896
|
+
return [dict(kind="line", label=self.label, color=c, linestyle="-", width=1,
|
|
897
|
+
marker=None)]
|
|
898
|
+
|
|
899
|
+
def draw(self, ctx):
|
|
900
|
+
px, py = ctx.tx(self.x), ctx.ty(self.y)
|
|
901
|
+
mag = np.hypot(self.u, self.v)
|
|
902
|
+
ok = np.isfinite(px) & np.isfinite(py) & np.isfinite(mag)
|
|
903
|
+
if not ok.any():
|
|
904
|
+
return
|
|
905
|
+
scale = self.scale
|
|
906
|
+
if scale is None:
|
|
907
|
+
spacing = math.sqrt(ctx.width * ctx.height / max(ok.sum(), 1))
|
|
908
|
+
scale = 0.9 * spacing / max(np.nanmax(mag[ok]), 1e-12)
|
|
909
|
+
ddx, ddy = self.u * scale, -self.v * scale
|
|
910
|
+
if self.pivot == "middle":
|
|
911
|
+
sx, sy = px - ddx / 2, py - ddy / 2
|
|
912
|
+
elif self.pivot == "tip":
|
|
913
|
+
sx, sy = px - ddx, py - ddy
|
|
914
|
+
else:
|
|
915
|
+
sx, sy = px, py
|
|
916
|
+
ex, ey = sx + ddx, sy + ddy
|
|
917
|
+
per_point = isinstance(self.colors, np.ndarray) and self.colors.ndim == 2
|
|
918
|
+
for k in np.flatnonzero(ok):
|
|
919
|
+
c = tuple(int(v) for v in self.colors[k]) if per_point else self.colors
|
|
920
|
+
draw_arrow(ctx.canvas, sx[k], sy[k], ex[k], ey[k], c)
|
|
921
|
+
|
|
922
|
+
|
|
923
|
+
def draw_arrow(canvas: Canvas, x0, y0, x1, y1, color, head: float | None = None):
|
|
924
|
+
length = math.hypot(x1 - x0, y1 - y0)
|
|
925
|
+
if length < 1.0:
|
|
926
|
+
canvas.put([round(x0)], [round(y0)], color)
|
|
927
|
+
return
|
|
928
|
+
canvas.line(x0, y0, x1, y1, color)
|
|
929
|
+
h = head if head is not None else min(3.0, max(1.5, length * 0.4))
|
|
930
|
+
ux, uy = (x1 - x0) / length, (y1 - y0) / length
|
|
931
|
+
for sgn in (-1, 1):
|
|
932
|
+
hx = x1 - h * ux + sgn * h * 0.65 * uy
|
|
933
|
+
hy = y1 - h * uy - sgn * h * 0.65 * ux
|
|
934
|
+
canvas.line(x1, y1, hx, hy, color)
|
|
935
|
+
|
|
936
|
+
|
|
937
|
+
# ---------------------------------------------------------------------- pie
|
|
938
|
+
class Pie(Artist):
|
|
939
|
+
def __init__(self, values, labels, colors, autopct=None, startangle=90.0, counterclock=True,
|
|
940
|
+
depth=0, outline=None, label_color=None):
|
|
941
|
+
v = _f(values)
|
|
942
|
+
if np.any(v < 0):
|
|
943
|
+
raise ValueError("pie values must be non-negative")
|
|
944
|
+
self.fracs = v / v.sum() if v.sum() > 0 else v
|
|
945
|
+
self.labels = labels
|
|
946
|
+
self.colors = colors
|
|
947
|
+
self.autopct = autopct
|
|
948
|
+
self.startangle = startangle
|
|
949
|
+
self.counterclock = counterclock
|
|
950
|
+
self.depth = depth
|
|
951
|
+
self.outline = outline
|
|
952
|
+
self.label_color = label_color
|
|
953
|
+
|
|
954
|
+
def legend_entries(self):
|
|
955
|
+
if not self.labels:
|
|
956
|
+
return []
|
|
957
|
+
return [dict(kind="patch", label=lb, color=self.colors[i % len(self.colors)], alpha=1.0,
|
|
958
|
+
outline="auto") for i, lb in enumerate(self.labels)]
|
|
959
|
+
|
|
960
|
+
def wedge_index(self, dx, dy):
|
|
961
|
+
ang = np.degrees(np.arctan2(-dy, dx)) # screen y grows downwards
|
|
962
|
+
rel = (ang - self.startangle) * (1 if self.counterclock else -1)
|
|
963
|
+
rel = np.mod(rel, 360.0) / 360.0
|
|
964
|
+
cum = np.cumsum(self.fracs)
|
|
965
|
+
return np.minimum(np.searchsorted(cum, rel, side="right"), len(self.fracs) - 1)
|
|
966
|
+
|
|
967
|
+
def draw(self, ctx):
|
|
968
|
+
st = ctx.style
|
|
969
|
+
font = st.get_tick_font()
|
|
970
|
+
x0, y0, x1, y1 = ctx.rect
|
|
971
|
+
label_w = 0
|
|
972
|
+
if self.labels:
|
|
973
|
+
label_w = max(font.measure(st.text(s))[0] for s in self.labels) + 3
|
|
974
|
+
label_h = font.line_height + 2 if self.labels else 0
|
|
975
|
+
depth = self.depth
|
|
976
|
+
if depth == "auto":
|
|
977
|
+
depth = max(3, int(round((y1 - y0) * 0.05)))
|
|
978
|
+
depth = int(depth or 0)
|
|
979
|
+
tilt = 0.6 if depth > 0 else 1.0 # 3-D pies are viewed at an angle
|
|
980
|
+
r = max(min((x1 - x0) / 2 - label_w,
|
|
981
|
+
((y1 - y0 - depth) / 2 - label_h) / tilt) - 1, 3)
|
|
982
|
+
cx = (x0 + x1 - 1) / 2
|
|
983
|
+
cy = (y0 + y1 - 1 - depth) / 2
|
|
984
|
+
n = int(math.ceil(r))
|
|
985
|
+
yy, xx = np.mgrid[-n : n + 1, -n : n + 1]
|
|
986
|
+
disc = xx * xx + (yy / tilt) ** 2 <= r * r + r * 0.8
|
|
987
|
+
idx = self.wedge_index(xx, yy / tilt)
|
|
988
|
+
cols = np.array([self.colors[i % len(self.colors)] for i in range(len(self.fracs))],
|
|
989
|
+
dtype=np.uint8)
|
|
990
|
+
ix, iy = int(round(cx)) - n, int(round(cy)) - n
|
|
991
|
+
edge = st.color(self.outline) if self.outline is not None else None
|
|
992
|
+
# 3-D extrusion: a darker side wall below the front half of the pie
|
|
993
|
+
if depth > 0:
|
|
994
|
+
dark = np.array([st.shade(c, -0.45) for c in cols], dtype=np.uint8)
|
|
995
|
+
size = 2 * n + 1
|
|
996
|
+
side = np.full((size + depth, size), -1)
|
|
997
|
+
front = disc & (yy >= -1)
|
|
998
|
+
for d in range(depth, 0, -1):
|
|
999
|
+
side[d : d + size][front] = idx[front]
|
|
1000
|
+
wall = side >= 0
|
|
1001
|
+
wall[:size] &= ~disc
|
|
1002
|
+
ctx.canvas.blit(dark[np.maximum(side, 0)], ix, iy, mask=wall)
|
|
1003
|
+
if edge is not None:
|
|
1004
|
+
left = np.roll(side, 1, axis=1)
|
|
1005
|
+
seams = wall & (side != left) & (left >= 0)
|
|
1006
|
+
below = np.zeros_like(wall)
|
|
1007
|
+
below[:-1] = wall[1:]
|
|
1008
|
+
outline = wall & (~below | ~np.roll(wall, 1, axis=1) | ~np.roll(wall, -1, axis=1))
|
|
1009
|
+
ctx.canvas.fill_mask(seams | outline, ix, iy, edge)
|
|
1010
|
+
ctx.canvas.blit(cols[idx], ix, iy, mask=disc)
|
|
1011
|
+
if edge is not None:
|
|
1012
|
+
# wedge boundaries and rim
|
|
1013
|
+
boundary = disc & ((idx != np.roll(idx, 1, axis=1)) | (idx != np.roll(idx, 1, axis=0)))
|
|
1014
|
+
if np.count_nonzero(self.fracs) > 1:
|
|
1015
|
+
ctx.canvas.fill_mask(boundary & disc, ix, iy, edge)
|
|
1016
|
+
rim = disc & ~(np.roll(disc, 1, 0) & np.roll(disc, -1, 0) & np.roll(disc, 1, 1)
|
|
1017
|
+
& np.roll(disc, -1, 1))
|
|
1018
|
+
ctx.canvas.fill_mask(rim, ix, iy, edge)
|
|
1019
|
+
# labels
|
|
1020
|
+
start = 0.0
|
|
1021
|
+
for i, f in enumerate(self.fracs):
|
|
1022
|
+
mid = (start + f / 2) * 360.0
|
|
1023
|
+
start += f
|
|
1024
|
+
if f == 0:
|
|
1025
|
+
continue
|
|
1026
|
+
ang = math.radians(self.startangle + (mid if self.counterclock else -mid))
|
|
1027
|
+
ca, sn = math.cos(ang), -math.sin(ang)
|
|
1028
|
+
sa = sn * tilt
|
|
1029
|
+
if self.labels:
|
|
1030
|
+
lx = cx + r * ca + 3 * ca
|
|
1031
|
+
ly = cy + r * sa + 3 * sn + (depth if sn > 0 else 0)
|
|
1032
|
+
ha = "left" if ca > 0.15 else ("right" if ca < -0.15 else "center")
|
|
1033
|
+
va = "center" if abs(sn) < 0.5 else ("bottom" if sn < 0 else "top")
|
|
1034
|
+
ctx.canvas.text(round(lx), round(ly), st.text(self.labels[i]), font,
|
|
1035
|
+
self.label_color or st.fg, ha=ha, va=va,
|
|
1036
|
+
shadow=st.color(st.text_shadow) if st.text_shadow else None)
|
|
1037
|
+
if self.autopct:
|
|
1038
|
+
s = (self.autopct(f * 100) if callable(self.autopct)
|
|
1039
|
+
else self.autopct % (f * 100))
|
|
1040
|
+
tw, th = font.measure(s)
|
|
1041
|
+
if f * 2 * math.pi * r * 0.6 > tw:
|
|
1042
|
+
c = tuple(int(v) for v in cols[i])
|
|
1043
|
+
txt = st.colors.snap((0, 0, 0)) if _bright(c) else st.colors.snap(
|
|
1044
|
+
(255, 255, 255))
|
|
1045
|
+
ctx.canvas.text(round(cx + 0.6 * r * ca), round(cy + 0.6 * r * sa), s, font,
|
|
1046
|
+
txt, ha="center", va="center")
|
|
1047
|
+
|
|
1048
|
+
|
|
1049
|
+
def _bright(rgb) -> bool:
|
|
1050
|
+
r, g, b = rgb
|
|
1051
|
+
return 0.2126 * r + 0.7152 * g + 0.0722 * b > 140
|
|
1052
|
+
|
|
1053
|
+
|
|
1054
|
+
# ---------------------------------------------------------------------- statistics
|
|
1055
|
+
def box_stats(data, whis=1.5):
|
|
1056
|
+
d = _f(data)
|
|
1057
|
+
d = d[np.isfinite(d)]
|
|
1058
|
+
if d.size == 0:
|
|
1059
|
+
return None
|
|
1060
|
+
q1, med, q3 = np.percentile(d, [25, 50, 75])
|
|
1061
|
+
iqr = q3 - q1
|
|
1062
|
+
lo_lim, hi_lim = q1 - whis * iqr, q3 + whis * iqr
|
|
1063
|
+
inside = d[(d >= lo_lim) & (d <= hi_lim)]
|
|
1064
|
+
wlo = inside.min() if inside.size else q1
|
|
1065
|
+
whi = inside.max() if inside.size else q3
|
|
1066
|
+
fliers = d[(d < wlo) | (d > whi)]
|
|
1067
|
+
return dict(q1=q1, med=med, q3=q3, wlo=wlo, whi=whi, fliers=fliers, mean=d.mean())
|
|
1068
|
+
|
|
1069
|
+
|
|
1070
|
+
class BoxPlot(Artist):
|
|
1071
|
+
def __init__(self, datasets, positions, widths, colors, showfliers=True, label=None):
|
|
1072
|
+
self.stats = [box_stats(d) for d in datasets]
|
|
1073
|
+
self.positions = _f(positions)
|
|
1074
|
+
self.widths = np.broadcast_to(_f(widths), self.positions.shape)
|
|
1075
|
+
self.colors = colors
|
|
1076
|
+
self.showfliers = showfliers
|
|
1077
|
+
self.label = label
|
|
1078
|
+
|
|
1079
|
+
def bounds(self, xlog, ylog):
|
|
1080
|
+
ys = []
|
|
1081
|
+
for s in self.stats:
|
|
1082
|
+
if s is None:
|
|
1083
|
+
continue
|
|
1084
|
+
ys += [s["wlo"], s["whi"]]
|
|
1085
|
+
if self.showfliers and s["fliers"].size:
|
|
1086
|
+
ys += [s["fliers"].min(), s["fliers"].max()]
|
|
1087
|
+
p, w = self.positions, self.widths
|
|
1088
|
+
return _bounds4(p - w / 2, p + w / 2, np.array(ys), np.array(ys), xlog, ylog)
|
|
1089
|
+
|
|
1090
|
+
def points(self):
|
|
1091
|
+
xs, ys = [], []
|
|
1092
|
+
for p, s in zip(self.positions, self.stats):
|
|
1093
|
+
if s is not None:
|
|
1094
|
+
xs += [p, p]
|
|
1095
|
+
ys += [s["wlo"], s["whi"]]
|
|
1096
|
+
return np.array(xs), np.array(ys)
|
|
1097
|
+
|
|
1098
|
+
def legend_entries(self):
|
|
1099
|
+
if not self.label:
|
|
1100
|
+
return []
|
|
1101
|
+
return [dict(kind="patch", label=self.label, color=self.colors[0], alpha=1.0,
|
|
1102
|
+
outline="auto")]
|
|
1103
|
+
|
|
1104
|
+
def draw(self, ctx):
|
|
1105
|
+
st = ctx.style
|
|
1106
|
+
fg = st.fg
|
|
1107
|
+
cv = ctx.canvas
|
|
1108
|
+
for k, (p, w, s) in enumerate(zip(self.positions, self.widths, self.stats)):
|
|
1109
|
+
if s is None:
|
|
1110
|
+
continue
|
|
1111
|
+
color = self.colors[k % len(self.colors)]
|
|
1112
|
+
edge = st.shade(color, -0.55) if st.bar_shading else fg
|
|
1113
|
+
x0, x1 = ctx.span(float(ctx.tx(p - w / 2)), float(ctx.tx(p + w / 2)), 3)
|
|
1114
|
+
ya, yb = ctx.span(float(ctx.ty(s["q1"])), float(ctx.ty(s["q3"])), 1)
|
|
1115
|
+
xc = float(ctx.tx(p))
|
|
1116
|
+
cap_w = max((x1 - x0) // 4, 1)
|
|
1117
|
+
for v_end, v_box in ((s["whi"], s["q3"]), (s["wlo"], s["q1"])):
|
|
1118
|
+
ye, yq = float(ctx.ty(v_end)), float(ctx.ty(v_box))
|
|
1119
|
+
cv.line(xc, ye, xc, yq, fg)
|
|
1120
|
+
cv.line(xc - cap_w, ye, xc + cap_w, ye, fg)
|
|
1121
|
+
draw_box(cv, st, x0, ya - 1, x1, yb + 1, color, 1.0, "auto" if st.bar_shading else fg,
|
|
1122
|
+
shading=st.bar_shading)
|
|
1123
|
+
ym = float(ctx.ty(s["med"]))
|
|
1124
|
+
med_c = st.colors.snap((255, 255, 255)) if not _bright(color) else st.colors.snap(
|
|
1125
|
+
(0, 0, 0))
|
|
1126
|
+
cv.line(x0 + 1, ym, x1 - 2, ym, med_c if edge != med_c else fg)
|
|
1127
|
+
if self.showfliers and s["fliers"].size:
|
|
1128
|
+
outline = st.color(st.marker_outline) if st.marker_outline is not None else None
|
|
1129
|
+
draw_markers(ctx, np.full(s["fliers"].shape, xc), ctx.ty(s["fliers"]), ".", 1,
|
|
1130
|
+
color, outline)
|
|
1131
|
+
|
|
1132
|
+
|
|
1133
|
+
def gaussian_kde(data: np.ndarray, points: np.ndarray, bw: float | None = None) -> np.ndarray:
|
|
1134
|
+
"""Gaussian kernel density estimate (Scott's rule bandwidth)."""
|
|
1135
|
+
d = data[np.isfinite(data)]
|
|
1136
|
+
if d.size > 2000:
|
|
1137
|
+
d = np.random.default_rng(0).choice(d, 2000, replace=False)
|
|
1138
|
+
if d.size == 0:
|
|
1139
|
+
return np.zeros_like(points)
|
|
1140
|
+
sd = d.std(ddof=1) if d.size > 1 else 0.0
|
|
1141
|
+
if bw is None:
|
|
1142
|
+
bw = sd * d.size ** (-1 / 5) if sd > 0 else 1.0
|
|
1143
|
+
z = (points[:, None] - d[None, :]) / bw
|
|
1144
|
+
return np.exp(-0.5 * z * z).sum(axis=1) / (d.size * bw * math.sqrt(2 * math.pi))
|
|
1145
|
+
|
|
1146
|
+
|
|
1147
|
+
class Violins(Artist):
|
|
1148
|
+
def __init__(self, datasets, positions, widths, colors, show_box=True, label=None):
|
|
1149
|
+
self.data = [_f(d) for d in datasets]
|
|
1150
|
+
self.positions = _f(positions)
|
|
1151
|
+
self.widths = np.broadcast_to(_f(widths), self.positions.shape)
|
|
1152
|
+
self.colors = colors
|
|
1153
|
+
self.show_box = show_box
|
|
1154
|
+
self.label = label
|
|
1155
|
+
|
|
1156
|
+
def bounds(self, xlog, ylog):
|
|
1157
|
+
ys = np.concatenate([d[np.isfinite(d)] for d in self.data]) if self.data else np.array([])
|
|
1158
|
+
p, w = self.positions, self.widths
|
|
1159
|
+
return _bounds4(p - w / 2, p + w / 2, ys, ys, xlog, ylog)
|
|
1160
|
+
|
|
1161
|
+
def points(self):
|
|
1162
|
+
xs, ys = [], []
|
|
1163
|
+
for p, d in zip(self.positions, self.data):
|
|
1164
|
+
d = d[np.isfinite(d)]
|
|
1165
|
+
if d.size:
|
|
1166
|
+
xs += [p, p]
|
|
1167
|
+
ys += [d.min(), d.max()]
|
|
1168
|
+
return np.array(xs), np.array(ys)
|
|
1169
|
+
|
|
1170
|
+
def legend_entries(self):
|
|
1171
|
+
if not self.label:
|
|
1172
|
+
return []
|
|
1173
|
+
return [dict(kind="patch", label=self.label, color=self.colors[0], alpha=1.0,
|
|
1174
|
+
outline="auto")]
|
|
1175
|
+
|
|
1176
|
+
def draw(self, ctx):
|
|
1177
|
+
st = ctx.style
|
|
1178
|
+
cv = ctx.canvas
|
|
1179
|
+
x0, y0, x1, y1 = ctx.rect
|
|
1180
|
+
for k, (p, w, d) in enumerate(zip(self.positions, self.widths, self.data)):
|
|
1181
|
+
d = d[np.isfinite(d)]
|
|
1182
|
+
if d.size == 0:
|
|
1183
|
+
continue
|
|
1184
|
+
color = self.colors[k % len(self.colors)]
|
|
1185
|
+
edge = st.shade(color, -0.55)
|
|
1186
|
+
ra, rb = ctx.span(float(ctx.ty(d.max())), float(ctx.ty(d.min())), 1)
|
|
1187
|
+
ra, rb = max(ra, y0), min(rb + 1, y1)
|
|
1188
|
+
if rb <= ra:
|
|
1189
|
+
continue
|
|
1190
|
+
rows = np.arange(ra, rb)
|
|
1191
|
+
dens = gaussian_kde(d, ctx.inv_y(rows))
|
|
1192
|
+
half = (float(ctx.tx(p + w / 2)) - float(ctx.tx(p - w / 2))) / 2
|
|
1193
|
+
hw = np.round(dens / max(dens.max(), 1e-300) * half).astype(int)
|
|
1194
|
+
xc = int(round(float(ctx.tx(p))))
|
|
1195
|
+
mask = np.zeros((len(rows), 2 * int(math.ceil(half)) + 1), dtype=bool)
|
|
1196
|
+
cols = np.arange(mask.shape[1]) - mask.shape[1] // 2
|
|
1197
|
+
mask[:] = np.abs(cols)[None, :] <= hw[:, None]
|
|
1198
|
+
ox = xc - mask.shape[1] // 2
|
|
1199
|
+
cv.fill_mask(mask, ox, ra, color)
|
|
1200
|
+
inner = mask.copy()
|
|
1201
|
+
inner[:, 1:-1] = mask[:, :-2] & mask[:, 2:] & mask[:, 1:-1]
|
|
1202
|
+
inner[:, [0, -1]] = False
|
|
1203
|
+
inner[1:-1] &= mask[:-2, :] & mask[2:, :]
|
|
1204
|
+
inner[[0, -1], :] = False
|
|
1205
|
+
cv.fill_mask(mask & ~inner, ox, ra, edge)
|
|
1206
|
+
if self.show_box:
|
|
1207
|
+
s = box_stats(d)
|
|
1208
|
+
cv.line(xc, ctx.ty(s["q1"]), xc, ctx.ty(s["q3"]), edge, width=3 if half > 4 else 1)
|
|
1209
|
+
cv.put([xc], [int(round(float(ctx.ty(s["med"]))))],
|
|
1210
|
+
st.colors.snap((255, 255, 255)))
|
|
1211
|
+
|
|
1212
|
+
|
|
1213
|
+
# ---------------------------------------------------------------------- text
|
|
1214
|
+
class Text(Artist):
|
|
1215
|
+
zorder = 5
|
|
1216
|
+
|
|
1217
|
+
def __init__(self, x, y, s, color, ha="left", va="baseline", coords="data", font=None,
|
|
1218
|
+
box=False, shadow=None):
|
|
1219
|
+
self.x, self.y, self.s = x, y, s
|
|
1220
|
+
self.color = color
|
|
1221
|
+
self.ha, self.va = ha, va
|
|
1222
|
+
self.coords = coords
|
|
1223
|
+
self.font = font
|
|
1224
|
+
self.box = box
|
|
1225
|
+
self.shadow = shadow
|
|
1226
|
+
|
|
1227
|
+
def anchor(self, ctx):
|
|
1228
|
+
if self.coords == "axes":
|
|
1229
|
+
x0, y0, x1, y1 = ctx.rect
|
|
1230
|
+
return x0 + self.x * (x1 - x0 - 1), y1 - 1 - self.y * (y1 - y0 - 1)
|
|
1231
|
+
if self.coords == "pixels":
|
|
1232
|
+
return ctx.rect[0] + self.x, ctx.rect[1] + self.y
|
|
1233
|
+
return float(ctx.tx(self.x)), float(ctx.ty(self.y))
|
|
1234
|
+
|
|
1235
|
+
def draw(self, ctx):
|
|
1236
|
+
st = ctx.style
|
|
1237
|
+
font = self.font or st.get_tick_font()
|
|
1238
|
+
x, y = self.anchor(ctx)
|
|
1239
|
+
if not (np.isfinite(x) and np.isfinite(y)):
|
|
1240
|
+
return
|
|
1241
|
+
s = st.text(self.s)
|
|
1242
|
+
if self.box:
|
|
1243
|
+
tw, th = font.measure(s)
|
|
1244
|
+
bx = {"left": x, "center": x - tw // 2, "right": x - tw + 1}[self.ha]
|
|
1245
|
+
cap = th - font.descent
|
|
1246
|
+
by = {"top": y, "center": y - cap // 2, "baseline": y - cap + 1,
|
|
1247
|
+
"bottom": y - th + 1}[self.va]
|
|
1248
|
+
bx, by = int(round(bx)), int(round(by))
|
|
1249
|
+
fill = st.legend_fill or st.panel_fill or st.background
|
|
1250
|
+
fill = fill[0] if isinstance(fill, tuple) and isinstance(fill[0], str) else fill
|
|
1251
|
+
ctx.canvas.fill_rect(bx - 2, by - 2, bx + tw + 2, by + th + 1, st.color(fill))
|
|
1252
|
+
ctx.canvas.rect(bx - 2, by - 2, bx + tw + 2, by + th + 1, st.fg)
|
|
1253
|
+
shadow = self.shadow
|
|
1254
|
+
if shadow is None and st.text_shadow is not None:
|
|
1255
|
+
shadow = st.color(st.text_shadow)
|
|
1256
|
+
ctx.canvas.text(int(round(x)), int(round(y)), s, font, self.color, self.ha, self.va,
|
|
1257
|
+
shadow=shadow)
|
|
1258
|
+
|
|
1259
|
+
|
|
1260
|
+
class Annotation(Text):
|
|
1261
|
+
def __init__(self, s, xy, xytext, color, arrow=True, coords="data", **kw):
|
|
1262
|
+
super().__init__(xytext[0], xytext[1], s, color, coords=coords, **kw)
|
|
1263
|
+
self.xy = xy
|
|
1264
|
+
self.arrow = arrow
|
|
1265
|
+
|
|
1266
|
+
def bounds(self, xlog, ylog):
|
|
1267
|
+
if self.coords != "data":
|
|
1268
|
+
return None
|
|
1269
|
+
return _xy_bounds([self.xy[0]], [self.xy[1]], xlog, ylog)
|
|
1270
|
+
|
|
1271
|
+
def draw(self, ctx):
|
|
1272
|
+
st = ctx.style
|
|
1273
|
+
font = self.font or st.get_tick_font()
|
|
1274
|
+
tx, ty = self.anchor(ctx)
|
|
1275
|
+
px, py = float(ctx.tx(self.xy[0])), float(ctx.ty(self.xy[1]))
|
|
1276
|
+
if self.arrow and all(np.isfinite([tx, ty, px, py])):
|
|
1277
|
+
tw, th = font.measure(st.text(self.s))
|
|
1278
|
+
bx0 = {"left": tx, "center": tx - tw / 2, "right": tx - tw}[self.ha]
|
|
1279
|
+
cap = th - font.descent
|
|
1280
|
+
by0 = {"top": ty, "center": ty - cap / 2, "baseline": ty - cap,
|
|
1281
|
+
"bottom": ty - th}[self.va]
|
|
1282
|
+
sx = min(max(px, bx0 - 2), bx0 + tw + 1)
|
|
1283
|
+
sy = min(max(py, by0 - 2), by0 + th + 1)
|
|
1284
|
+
if math.hypot(px - sx, py - sy) > 3:
|
|
1285
|
+
# stop just short of the target point
|
|
1286
|
+
d = math.hypot(px - sx, py - sy)
|
|
1287
|
+
ex, ey = px - (px - sx) / d * 2, py - (py - sy) / d * 2
|
|
1288
|
+
draw_arrow(ctx.canvas, sx, sy, ex, ey, self.color)
|
|
1289
|
+
super().draw(ctx)
|
|
1290
|
+
|
|
1291
|
+
|
|
1292
|
+
def legend_handle(canvas: Canvas, style, entry: dict, x: int, y: int, w: int, h: int):
|
|
1293
|
+
"""Draw a legend key glyph in the box ``[x, x+w) x [y, y+h)``."""
|
|
1294
|
+
kind = entry["kind"]
|
|
1295
|
+
color = entry["color"]
|
|
1296
|
+
cy = y + h // 2
|
|
1297
|
+
if kind == "line":
|
|
1298
|
+
ls = entry.get("linestyle") or "-"
|
|
1299
|
+
if ls not in ("none", ""):
|
|
1300
|
+
pattern = dash_pattern(ls)
|
|
1301
|
+
if pattern is not None and len(pattern) > w // 2:
|
|
1302
|
+
ls = (1, 1, 0)
|
|
1303
|
+
canvas.polyline([x, x + w - 1], [cy, cy], color, entry.get("width", 1), ls)
|
|
1304
|
+
if entry.get("marker"):
|
|
1305
|
+
m = marker_mask(entry["marker"], 1)
|
|
1306
|
+
canvas.fill_mask(m, x + w // 2 - m.shape[1] // 2, cy - m.shape[0] // 2, color)
|
|
1307
|
+
elif kind == "marker":
|
|
1308
|
+
m = marker_mask(entry["marker"], 1)
|
|
1309
|
+
canvas.fill_mask(m, x + w // 2 - m.shape[1] // 2, cy - m.shape[0] // 2, color)
|
|
1310
|
+
else:
|
|
1311
|
+
bh = min(h, 5)
|
|
1312
|
+
draw_box(canvas, style, x + 1, cy - bh // 2, x + w - 1, cy - bh // 2 + bh, color,
|
|
1313
|
+
entry.get("alpha", 1.0), entry.get("outline", "auto"), shading=False)
|