mgplot 0.2.26__py3-none-any.whl → 0.2.28__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.
- mgplot/annotation_utils.py +324 -0
- mgplot/axis_utils.py +2 -1
- mgplot/finalise_plot.py +3 -0
- mgplot/line_plot.py +33 -8
- mgplot/revision_plot.py +2 -0
- mgplot/settings.py +2 -2
- mgplot/utilities.py +2 -2
- {mgplot-0.2.26.dist-info → mgplot-0.2.28.dist-info}/METADATA +1 -1
- {mgplot-0.2.26.dist-info → mgplot-0.2.28.dist-info}/RECORD +11 -10
- {mgplot-0.2.26.dist-info → mgplot-0.2.28.dist-info}/WHEEL +0 -0
- {mgplot-0.2.26.dist-info → mgplot-0.2.28.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
"""Resolve collisions among end-of-line annotation labels.
|
|
2
|
+
|
|
3
|
+
line_plot() draws a value label at the right-hand end of each plotted line and
|
|
4
|
+
registers the label Text artists, their owning Line2D, and the near-end
|
|
5
|
+
threshold on the Axes (register_annotations). finalise_plot() then calls
|
|
6
|
+
resolve_annotation_collisions() as a late step -- once the figure has its final
|
|
7
|
+
size and axis limits -- so the label bounding boxes can be measured in display
|
|
8
|
+
(pixel) coordinates and nudged so they do not overlap each other or the lines.
|
|
9
|
+
|
|
10
|
+
Algorithm (everything is computed in display/pixel coordinates):
|
|
11
|
+
|
|
12
|
+
* Each label is classified by the x of its line end: "at-end" (the rightmost
|
|
13
|
+
data point on the whole axes), "near-end" (within ``near_end`` * data-width of
|
|
14
|
+
the right edge) or "interior".
|
|
15
|
+
* Every label is first tried at its own line end. An overlapping label is
|
|
16
|
+
nudged vertically by at most its own height to find a slot clear of both the
|
|
17
|
+
plotted lines (over the label's horizontal span) and the other labels. A
|
|
18
|
+
label that finds such a slot keeps that local position.
|
|
19
|
+
* A near-end / at-end label that cannot be cleared within that nudge is snapped
|
|
20
|
+
across to the rightmost data point and stacked vertically with the other
|
|
21
|
+
end-of-axes labels.
|
|
22
|
+
* An interior label that cannot be cleared keeps the candidate position with the
|
|
23
|
+
most clearance -- overlap is accepted rather than moving it off its line end.
|
|
24
|
+
* Line avoidance never applies to a label sitting at the last data point: its
|
|
25
|
+
text extends into the right margin where there is no line to clear.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from math import inf
|
|
29
|
+
from typing import Any, Final
|
|
30
|
+
|
|
31
|
+
import numpy as np
|
|
32
|
+
from matplotlib.axes import Axes
|
|
33
|
+
from matplotlib.backend_bases import RendererBase
|
|
34
|
+
from matplotlib.figure import Figure, SubFigure
|
|
35
|
+
from matplotlib.lines import Line2D
|
|
36
|
+
from matplotlib.text import Text
|
|
37
|
+
from matplotlib.transforms import Transform
|
|
38
|
+
|
|
39
|
+
# A line in display coordinates: (x-pixels, y-pixels) as parallel arrays.
|
|
40
|
+
LineDisp = tuple[np.ndarray, np.ndarray]
|
|
41
|
+
|
|
42
|
+
# --- constants
|
|
43
|
+
_AXES_ANNO_ATTR: Final[str] = "_mgplot_annotations"
|
|
44
|
+
_GAP_PX: Final[float] = 2.0 # minimum separation between artists (pixels)
|
|
45
|
+
_STEP_PX: Final[float] = 1.0 # search step when looking for a clear slot
|
|
46
|
+
_SNAP_LIMIT_PX: Final[float] = 1.0e4 # effectively-unbounded search at the right edge
|
|
47
|
+
_SPAN_SAMPLES: Final[int] = 5 # samples of a line across a label's x-span
|
|
48
|
+
_X_EPS: Final[float] = 1.0e-9 # fraction-of-span tolerance for "at the last point"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# --- registration (mirrors the period-axes stash in axis_utils)
|
|
52
|
+
def register_annotations(
|
|
53
|
+
axes: Axes,
|
|
54
|
+
pairs: list[tuple[Text, Line2D | None]],
|
|
55
|
+
lines: list[Line2D],
|
|
56
|
+
near_end: float,
|
|
57
|
+
) -> None:
|
|
58
|
+
"""Stash end-of-line annotation artists on an Axes for later de-collision.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
axes: the Axes the labels were drawn on.
|
|
62
|
+
pairs: (label Text, the Line2D it annotates) for each annotated series.
|
|
63
|
+
lines: every data Line2D on the axes (obstacles for interior labels).
|
|
64
|
+
near_end: labels whose line end is within this fraction of the data
|
|
65
|
+
width from the right edge are snapped to the edge when they cannot
|
|
66
|
+
be placed locally.
|
|
67
|
+
|
|
68
|
+
"""
|
|
69
|
+
if not pairs:
|
|
70
|
+
return
|
|
71
|
+
stash: dict[str, Any] = getattr(axes, _AXES_ANNO_ATTR, None) or {"pairs": [], "lines": []}
|
|
72
|
+
stash["pairs"].extend(pairs)
|
|
73
|
+
known = {id(ln) for ln in stash["lines"]}
|
|
74
|
+
stash["lines"].extend(ln for ln in lines if id(ln) not in known)
|
|
75
|
+
stash["near_end"] = near_end
|
|
76
|
+
setattr(axes, _AXES_ANNO_ATTR, stash)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def get_annotations(axes: Axes) -> dict[str, Any] | None:
|
|
80
|
+
"""Return the stashed annotation artists for an axes, or None."""
|
|
81
|
+
return getattr(axes, _AXES_ANNO_ATTR, None)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
# --- private helpers (all in display coordinates)
|
|
85
|
+
def _line_ys_in_span(x0: float, x1: float, line_disps: list[LineDisp]) -> list[float]:
|
|
86
|
+
"""Return display y-values of each line sampled across the [x0, x1] strip."""
|
|
87
|
+
ys: list[float] = []
|
|
88
|
+
sample_x = np.linspace(x0, x1, _SPAN_SAMPLES)
|
|
89
|
+
for px, py in line_disps:
|
|
90
|
+
sx = sample_x[(sample_x >= px[0]) & (sample_x <= px[-1])]
|
|
91
|
+
if sx.size:
|
|
92
|
+
ys.extend(np.interp(sx, px, py).tolist())
|
|
93
|
+
return ys
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _hits_line(lab: dict[str, Any], yc: float, line_disps: list[LineDisp]) -> bool:
|
|
97
|
+
"""Return True if a label centred at yc overlaps any line within its x-span."""
|
|
98
|
+
half = lab["h"] / 2.0 + _GAP_PX
|
|
99
|
+
return any(yc - half <= y <= yc + half for y in _line_ys_in_span(lab["x0"], lab["x1"], line_disps))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _hits_label(lab: dict[str, Any], yc: float, placed: list[dict[str, Any]]) -> bool:
|
|
103
|
+
"""Return True if a label centred at yc overlaps any already-placed label."""
|
|
104
|
+
for p in placed:
|
|
105
|
+
if lab["x1"] <= p["x0"] or p["x1"] <= lab["x0"]:
|
|
106
|
+
continue # no horizontal overlap
|
|
107
|
+
if abs(yc - p["yc"]) < (lab["h"] + p["h"]) / 2.0 + _GAP_PX:
|
|
108
|
+
return True
|
|
109
|
+
return False
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _clearance(
|
|
113
|
+
lab: dict[str, Any],
|
|
114
|
+
yc: float,
|
|
115
|
+
placed: list[dict[str, Any]],
|
|
116
|
+
line_disps: list[LineDisp],
|
|
117
|
+
) -> float:
|
|
118
|
+
"""Signed gap (px) from a label at yc to its nearest obstacle (higher is better)."""
|
|
119
|
+
half = lab["h"] / 2.0
|
|
120
|
+
gap = inf
|
|
121
|
+
for y in _line_ys_in_span(lab["x0"], lab["x1"], line_disps):
|
|
122
|
+
gap = min(gap, abs(yc - y) - half)
|
|
123
|
+
for p in placed:
|
|
124
|
+
if lab["x1"] <= p["x0"] or p["x1"] <= lab["x0"]:
|
|
125
|
+
continue
|
|
126
|
+
gap = min(gap, abs(yc - p["yc"]) - (lab["h"] + p["h"]) / 2.0)
|
|
127
|
+
return gap
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _place_interior(lab: dict[str, Any], placed: list[dict[str, Any]], line_disps: list[LineDisp]) -> None:
|
|
131
|
+
"""Place an interior label: nudge <= its height, else accept most clearance."""
|
|
132
|
+
base = lab["yc"]
|
|
133
|
+
if not _hits_line(lab, base, line_disps) and not _hits_label(lab, base, placed):
|
|
134
|
+
return
|
|
135
|
+
best_yc, best_clear = base, _clearance(lab, base, placed, line_disps)
|
|
136
|
+
off = _STEP_PX
|
|
137
|
+
while off <= lab["h"]:
|
|
138
|
+
for cand in (base + off, base - off):
|
|
139
|
+
if not _hits_line(lab, cand, line_disps) and not _hits_label(lab, cand, placed):
|
|
140
|
+
lab["yc"] = cand
|
|
141
|
+
return
|
|
142
|
+
clear = _clearance(lab, cand, placed, line_disps)
|
|
143
|
+
if clear > best_clear:
|
|
144
|
+
best_clear, best_yc = clear, cand
|
|
145
|
+
off += _STEP_PX
|
|
146
|
+
lab["yc"] = best_yc # cannot clear within +/- height: accept the best overlap
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _free_slot(lab: dict[str, Any], base: float, placed: list[dict[str, Any]]) -> float:
|
|
150
|
+
"""Nearest y to base with no label overlap (used at the snapped right edge)."""
|
|
151
|
+
if not _hits_label(lab, base, placed):
|
|
152
|
+
return base
|
|
153
|
+
off = _STEP_PX
|
|
154
|
+
while off <= _SNAP_LIMIT_PX:
|
|
155
|
+
for cand in (base + off, base - off):
|
|
156
|
+
if not _hits_label(lab, cand, placed):
|
|
157
|
+
return cand
|
|
158
|
+
off += _STEP_PX
|
|
159
|
+
return base
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _place_cluster(
|
|
163
|
+
lab: dict[str, Any],
|
|
164
|
+
placed: list[dict[str, Any]],
|
|
165
|
+
line_disps: list[LineDisp],
|
|
166
|
+
right_disp_x: float,
|
|
167
|
+
) -> None:
|
|
168
|
+
"""Place a near-/at-end label: try local, else snap to the edge and stack."""
|
|
169
|
+
base = lab["yc"]
|
|
170
|
+
if not lab["at_end"]:
|
|
171
|
+
# try to keep it at its own line end, nudging by at most its height
|
|
172
|
+
if not _hits_line(lab, base, line_disps) and not _hits_label(lab, base, placed):
|
|
173
|
+
return
|
|
174
|
+
off = _STEP_PX
|
|
175
|
+
while off <= lab["h"]:
|
|
176
|
+
for cand in (base + off, base - off):
|
|
177
|
+
if not _hits_line(lab, cand, line_disps) and not _hits_label(lab, cand, placed):
|
|
178
|
+
lab["yc"] = cand
|
|
179
|
+
return
|
|
180
|
+
off += _STEP_PX
|
|
181
|
+
# snap across to the rightmost data point and stack clear of placed labels
|
|
182
|
+
delta = right_disp_x - lab["x0"]
|
|
183
|
+
lab["x0"] += delta
|
|
184
|
+
lab["x1"] += delta
|
|
185
|
+
lab["snapped"] = True
|
|
186
|
+
lab["yc"] = _free_slot(lab, base, placed)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _root_figure(axes: Axes) -> Figure:
|
|
190
|
+
"""Return the top-level Figure for an axes (drilling through any SubFigure)."""
|
|
191
|
+
fig = axes.figure
|
|
192
|
+
while isinstance(fig, SubFigure):
|
|
193
|
+
fig = fig.figure
|
|
194
|
+
return fig
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _get_renderer(fig: Figure) -> RendererBase | None:
|
|
198
|
+
"""Return a renderer for measuring text extents, or None if unavailable."""
|
|
199
|
+
# Agg exposes canvas.get_renderer(); other backends expose Figure._get_renderer().
|
|
200
|
+
renderer = getattr(fig.canvas, "get_renderer", lambda: None)()
|
|
201
|
+
if isinstance(renderer, RendererBase):
|
|
202
|
+
return renderer
|
|
203
|
+
renderer = getattr(fig, "_get_renderer", lambda: None)()
|
|
204
|
+
return renderer if isinstance(renderer, RendererBase) else None
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _line_geometry(
|
|
208
|
+
all_lines: list[Line2D],
|
|
209
|
+
trans: Transform,
|
|
210
|
+
) -> tuple[list[LineDisp | None], dict[int, int], float, float, float] | None:
|
|
211
|
+
"""Build display-coord line geometry and the axes' data x-extent.
|
|
212
|
+
|
|
213
|
+
Returns (line_disps, line_index, right_x, span, right_disp_x), or None when
|
|
214
|
+
no line carries plottable data. Time-series x is monotonic increasing, so
|
|
215
|
+
each line's display arrays are ready for np.interp() sampling.
|
|
216
|
+
"""
|
|
217
|
+
line_disps: list[LineDisp | None] = []
|
|
218
|
+
xmaxs: list[float] = []
|
|
219
|
+
xmins: list[float] = []
|
|
220
|
+
for ln in all_lines:
|
|
221
|
+
xd = np.asarray(ln.get_xdata(), dtype=float)
|
|
222
|
+
yd = np.asarray(ln.get_ydata(), dtype=float)
|
|
223
|
+
ok = ~(np.isnan(xd) | np.isnan(yd))
|
|
224
|
+
if not ok.any():
|
|
225
|
+
line_disps.append(None)
|
|
226
|
+
continue
|
|
227
|
+
xmaxs.append(float(xd[ok].max()))
|
|
228
|
+
xmins.append(float(xd[ok].min()))
|
|
229
|
+
pts = trans.transform(np.column_stack([xd[ok], yd[ok]]))
|
|
230
|
+
line_disps.append((pts[:, 0], pts[:, 1]))
|
|
231
|
+
if not xmaxs:
|
|
232
|
+
return None
|
|
233
|
+
right_x = max(xmaxs)
|
|
234
|
+
span = right_x - min(xmins) if right_x > min(xmins) else 1.0
|
|
235
|
+
right_disp_x = float(trans.transform((right_x, 0.0))[0])
|
|
236
|
+
line_index = {id(ln): i for i, ln in enumerate(all_lines)}
|
|
237
|
+
return line_disps, line_index, right_x, span, right_disp_x
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _build_labels(
|
|
241
|
+
pairs: list[tuple[Text, Line2D | None]],
|
|
242
|
+
renderer: RendererBase,
|
|
243
|
+
line_index: dict[int, int],
|
|
244
|
+
edge: tuple[float, float, float],
|
|
245
|
+
) -> list[dict[str, Any]]:
|
|
246
|
+
"""Measure each annotation and record its display box and edge classification.
|
|
247
|
+
|
|
248
|
+
``edge`` is (right_x, span, near_end) in data coordinates / fraction.
|
|
249
|
+
"""
|
|
250
|
+
right_x, span, near_end = edge
|
|
251
|
+
labels: list[dict[str, Any]] = []
|
|
252
|
+
for text, own in pairs:
|
|
253
|
+
if not text.get_text().strip():
|
|
254
|
+
continue
|
|
255
|
+
bb = text.get_window_extent(renderer=renderer)
|
|
256
|
+
x_data = float(text.get_position()[0])
|
|
257
|
+
labels.append(
|
|
258
|
+
{
|
|
259
|
+
"t": text,
|
|
260
|
+
"x_data": x_data,
|
|
261
|
+
"x0": bb.x0,
|
|
262
|
+
"x1": bb.x1,
|
|
263
|
+
"yc": (bb.y0 + bb.y1) / 2.0,
|
|
264
|
+
"h": bb.height,
|
|
265
|
+
"own": line_index.get(id(own), -1),
|
|
266
|
+
"at_end": abs(right_x - x_data) <= _X_EPS * span,
|
|
267
|
+
"near": (right_x - x_data) <= near_end * span,
|
|
268
|
+
"snapped": False,
|
|
269
|
+
},
|
|
270
|
+
)
|
|
271
|
+
return labels
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
# --- public entry point
|
|
275
|
+
def resolve_annotation_collisions(axes: Axes) -> None:
|
|
276
|
+
"""Reposition stashed end-of-line labels so they do not collide.
|
|
277
|
+
|
|
278
|
+
No-op when the axes has no registered annotations. Called by finalise_plot()
|
|
279
|
+
after the figure layout is final, so that text bounding boxes measured here
|
|
280
|
+
match what is saved.
|
|
281
|
+
"""
|
|
282
|
+
stash = get_annotations(axes)
|
|
283
|
+
if stash is None:
|
|
284
|
+
return
|
|
285
|
+
|
|
286
|
+
fig = _root_figure(axes)
|
|
287
|
+
fig.canvas.draw() # realise the final layout so extents are correct
|
|
288
|
+
renderer = _get_renderer(fig)
|
|
289
|
+
if renderer is None:
|
|
290
|
+
return
|
|
291
|
+
trans = axes.transData
|
|
292
|
+
|
|
293
|
+
geometry = _line_geometry(stash["lines"], trans)
|
|
294
|
+
if geometry is None:
|
|
295
|
+
return
|
|
296
|
+
line_disps, line_index, right_x, span, right_disp_x = geometry
|
|
297
|
+
|
|
298
|
+
labels = _build_labels(stash["pairs"], renderer, line_index, (right_x, span, stash["near_end"]))
|
|
299
|
+
if not labels:
|
|
300
|
+
return
|
|
301
|
+
|
|
302
|
+
def others(lab: dict[str, Any]) -> list[LineDisp]:
|
|
303
|
+
"""Return line geometry excluding the label's own line (it ends at the anchor)."""
|
|
304
|
+
return [ld for i, ld in enumerate(line_disps) if ld is not None and i != lab["own"]]
|
|
305
|
+
|
|
306
|
+
# --- place interior labels first, then the right-edge cluster
|
|
307
|
+
placed: list[dict[str, Any]] = []
|
|
308
|
+
interior = sorted((lab for lab in labels if not lab["near"]), key=lambda lab: lab["yc"])
|
|
309
|
+
cluster = sorted((lab for lab in labels if lab["near"]), key=lambda lab: (-lab["x_data"], lab["yc"]))
|
|
310
|
+
for lab in interior:
|
|
311
|
+
_place_interior(lab, placed, others(lab))
|
|
312
|
+
placed.append(lab)
|
|
313
|
+
for lab in cluster:
|
|
314
|
+
_place_cluster(lab, placed, others(lab), right_disp_x)
|
|
315
|
+
placed.append(lab)
|
|
316
|
+
|
|
317
|
+
# --- write the new positions back in data coordinates
|
|
318
|
+
inv = trans.inverted()
|
|
319
|
+
for lab in labels:
|
|
320
|
+
x_disp = right_disp_x if lab["snapped"] else float(trans.transform((lab["x_data"], 0.0))[0])
|
|
321
|
+
_, y_data = inv.transform((x_disp, lab["yc"]))
|
|
322
|
+
lab["t"].set_y(y_data)
|
|
323
|
+
if lab["snapped"]:
|
|
324
|
+
lab["t"].set_x(right_x)
|
mgplot/axis_utils.py
CHANGED
|
@@ -426,7 +426,8 @@ def refresh_period_labels(axes: Axes, max_ticks: int | None = None) -> None:
|
|
|
426
426
|
freq, stash_min, stash_max = stash
|
|
427
427
|
options = get_label_options(axes)
|
|
428
428
|
if max_ticks is None:
|
|
429
|
-
|
|
429
|
+
stashed = options.get("max_ticks", DEFAULT_REFRESH_TICKS)
|
|
430
|
+
max_ticks = stashed if isinstance(stashed, int) else DEFAULT_REFRESH_TICKS
|
|
430
431
|
xlim = axes.get_xlim()
|
|
431
432
|
x_min = min(stash_min, int(xlim[0]))
|
|
432
433
|
x_max = max(stash_max, int(xlim[1]))
|
mgplot/finalise_plot.py
CHANGED
|
@@ -11,6 +11,7 @@ from matplotlib.axes import Axes
|
|
|
11
11
|
from matplotlib.figure import Figure, SubFigure
|
|
12
12
|
from pandas import Period, PeriodIndex
|
|
13
13
|
|
|
14
|
+
from mgplot.annotation_utils import resolve_annotation_collisions
|
|
14
15
|
from mgplot.axis_utils import get_period_axes, refresh_period_labels, register_period_axes
|
|
15
16
|
from mgplot.keyword_checking import BaseKwargs, report_kwargs, validate_kwargs
|
|
16
17
|
from mgplot.settings import get_setting
|
|
@@ -448,6 +449,8 @@ def finalise_plot(axes: Axes, **kwargs: Unpack[FinaliseKwargs]) -> None:
|
|
|
448
449
|
# axvspan/axvline in late_kwargs may have widened xlim beyond what
|
|
449
450
|
# set_labels() last saw; regenerate ticks from the updated view.
|
|
450
451
|
refresh_period_labels(axes)
|
|
452
|
+
# de-collide end-of-line annotations now that the layout/limits are final
|
|
453
|
+
resolve_annotation_collisions(axes)
|
|
451
454
|
legend = axes.get_legend()
|
|
452
455
|
if legend and kwargs.get("remove_legend", False):
|
|
453
456
|
legend.remove()
|
mgplot/line_plot.py
CHANGED
|
@@ -2,12 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
import math
|
|
4
4
|
from collections.abc import Callable, Sequence
|
|
5
|
-
from typing import Any, Final, NotRequired, TypedDict, Unpack
|
|
5
|
+
from typing import TYPE_CHECKING, Any, Final, NotRequired, TypedDict, Unpack
|
|
6
6
|
|
|
7
7
|
from matplotlib.axes import Axes
|
|
8
|
+
from matplotlib.text import Text
|
|
8
9
|
from pandas import DataFrame, Period, PeriodIndex, Series
|
|
9
10
|
from pandas.api.types import is_numeric_dtype
|
|
10
11
|
|
|
12
|
+
from mgplot.annotation_utils import register_annotations
|
|
11
13
|
from mgplot.axis_utils import map_periodindex, set_labels
|
|
12
14
|
from mgplot.keyword_checking import BaseKwargs, report_kwargs, validate_kwargs
|
|
13
15
|
from mgplot.settings import DataT, get_setting
|
|
@@ -20,8 +22,12 @@ from mgplot.utilities import (
|
|
|
20
22
|
get_color_list,
|
|
21
23
|
)
|
|
22
24
|
|
|
25
|
+
if TYPE_CHECKING:
|
|
26
|
+
from matplotlib.lines import Line2D
|
|
27
|
+
|
|
23
28
|
# --- constants
|
|
24
29
|
ME: Final[str] = "line_plot"
|
|
30
|
+
DEFAULT_NEAR_END: Final[float] = 0.1 # fraction-of-width threshold for snapping labels to the edge
|
|
25
31
|
|
|
26
32
|
|
|
27
33
|
class LineKwargs(BaseKwargs):
|
|
@@ -44,6 +50,7 @@ class LineKwargs(BaseKwargs):
|
|
|
44
50
|
fontname: NotRequired[str | Sequence[str]]
|
|
45
51
|
rotation: NotRequired[Sequence[int | float] | int | float]
|
|
46
52
|
annotate_color: NotRequired[str | Sequence[str] | bool | Sequence[bool] | None]
|
|
53
|
+
near_end: NotRequired[float]
|
|
47
54
|
plot_from: NotRequired[int | Period | None]
|
|
48
55
|
label_series: NotRequired[bool | Sequence[bool] | None]
|
|
49
56
|
max_ticks: NotRequired[int]
|
|
@@ -65,16 +72,20 @@ def annotate_series(
|
|
|
65
72
|
series: Series,
|
|
66
73
|
axes: Axes,
|
|
67
74
|
**kwargs: Unpack[AnnotateKwargs],
|
|
68
|
-
) -> None:
|
|
69
|
-
"""Annotate the right-hand end-point of a line-plotted series.
|
|
75
|
+
) -> Text | None:
|
|
76
|
+
"""Annotate the right-hand end-point of a line-plotted series.
|
|
77
|
+
|
|
78
|
+
Returns the created Text artist (or None if there was nothing to annotate)
|
|
79
|
+
so the caller can register it for end-of-line collision resolution.
|
|
80
|
+
"""
|
|
70
81
|
# --- check the series has a value to annotate
|
|
71
82
|
latest: Series = series.dropna()
|
|
72
83
|
if latest.empty or not is_numeric_dtype(latest):
|
|
73
|
-
return
|
|
84
|
+
return None
|
|
74
85
|
x: int | float = latest.index[-1] # type: ignore[assignment]
|
|
75
86
|
y: int | float = latest.iloc[-1]
|
|
76
87
|
if y is None or math.isnan(y):
|
|
77
|
-
return
|
|
88
|
+
return None
|
|
78
89
|
|
|
79
90
|
# --- extract fontsize - could be None, bool, int or str.
|
|
80
91
|
fontsize = kwargs.get("fontsize", "small")
|
|
@@ -89,7 +100,7 @@ def annotate_series(
|
|
|
89
100
|
raise ValueError("color is required for annotation")
|
|
90
101
|
rounding = default_rounding(value=y, provided=kwargs.get("rounding"))
|
|
91
102
|
r_string = f" {y:.{rounding}f}" if rounding > 0 else f" {int(y)}"
|
|
92
|
-
axes.text(
|
|
103
|
+
return axes.text(
|
|
93
104
|
x=x,
|
|
94
105
|
y=y,
|
|
95
106
|
s=r_string,
|
|
@@ -186,6 +197,8 @@ def line_plot(data: DataT, **kwargs: Unpack[LineKwargs]) -> Axes:
|
|
|
186
197
|
num_data_points = len(df)
|
|
187
198
|
swce, kwargs_d = get_style_width_color_etc(item_count, num_data_points, **kwargs_d)
|
|
188
199
|
|
|
200
|
+
drawn_lines: list[Line2D] = [] # every data line - obstacles for label de-collision
|
|
201
|
+
annotations: list[tuple[Text, Line2D | None]] = [] # (label, the line it annotates)
|
|
189
202
|
for i, column in enumerate(df.columns):
|
|
190
203
|
series = df[column]
|
|
191
204
|
series = series.dropna() if "dropna" in swce and swce["dropna"][i] else series
|
|
@@ -193,7 +206,7 @@ def line_plot(data: DataT, **kwargs: Unpack[LineKwargs]) -> Axes:
|
|
|
193
206
|
print(f"Warning: No data to plot for {column} in line_plot().")
|
|
194
207
|
continue
|
|
195
208
|
|
|
196
|
-
axes.plot(
|
|
209
|
+
lines = axes.plot(
|
|
197
210
|
# using matplotlib, as pandas can set xlabel/ylabel
|
|
198
211
|
series.index, # x
|
|
199
212
|
series, # y
|
|
@@ -207,12 +220,13 @@ def line_plot(data: DataT, **kwargs: Unpack[LineKwargs]) -> Axes:
|
|
|
207
220
|
zorder=swce["zorder"][i],
|
|
208
221
|
label=(column if "label_series" in swce and swce["label_series"][i] else f"_{column}_"),
|
|
209
222
|
)
|
|
223
|
+
drawn_lines.extend(lines)
|
|
210
224
|
|
|
211
225
|
if swce["annotate"][i] is None or not swce["annotate"][i]:
|
|
212
226
|
continue
|
|
213
227
|
|
|
214
228
|
color = swce["color"][i] if swce["annotate_color"][i] is True else swce["annotate_color"][i]
|
|
215
|
-
annotate_series(
|
|
229
|
+
text = annotate_series(
|
|
216
230
|
series,
|
|
217
231
|
axes,
|
|
218
232
|
color=color,
|
|
@@ -221,6 +235,17 @@ def line_plot(data: DataT, **kwargs: Unpack[LineKwargs]) -> Axes:
|
|
|
221
235
|
fontname=swce["fontname"][i],
|
|
222
236
|
rotation=swce["rotation"][i],
|
|
223
237
|
)
|
|
238
|
+
if text is not None:
|
|
239
|
+
annotations.append((text, lines[0] if lines else None))
|
|
240
|
+
|
|
241
|
+
# --- register annotations so finalise_plot() can de-collide them
|
|
242
|
+
if annotations:
|
|
243
|
+
register_annotations(
|
|
244
|
+
axes,
|
|
245
|
+
annotations,
|
|
246
|
+
drawn_lines,
|
|
247
|
+
kwargs_d.get("near_end", DEFAULT_NEAR_END),
|
|
248
|
+
)
|
|
224
249
|
|
|
225
250
|
# --- set the labels
|
|
226
251
|
if saved_pi is not None:
|
mgplot/revision_plot.py
CHANGED
|
@@ -14,6 +14,7 @@ from mgplot.utilities import check_clean_timeseries
|
|
|
14
14
|
ME = "revision_plot"
|
|
15
15
|
DEFAULT_PLOT_FROM = -15
|
|
16
16
|
MIN_REVISION_COLUMNS = 2
|
|
17
|
+
DEFAULT_NEAR_END = 0.0 # revision vintages bunch at the right edge; don't snap labels to the border
|
|
17
18
|
|
|
18
19
|
|
|
19
20
|
# --- functions
|
|
@@ -54,6 +55,7 @@ def revision_plot(data: DataT, **kwargs: Unpack[LineKwargs]) -> Axes:
|
|
|
54
55
|
kwargs["annotate"] = kwargs.get("annotate", True)
|
|
55
56
|
kwargs["annotate_color"] = kwargs.get("annotate_color", "black")
|
|
56
57
|
kwargs["rounding"] = kwargs.get("rounding", 3)
|
|
58
|
+
kwargs["near_end"] = kwargs.get("near_end", DEFAULT_NEAR_END)
|
|
57
59
|
|
|
58
60
|
# --- plot
|
|
59
61
|
return line_plot(data, **kwargs)
|
mgplot/settings.py
CHANGED
|
@@ -62,8 +62,8 @@ mgplot_defaults = DefaultTypes(
|
|
|
62
62
|
"fontsize": "x-small",
|
|
63
63
|
},
|
|
64
64
|
colors={
|
|
65
|
-
1: ["
|
|
66
|
-
5: ["darkblue", "darkorange", "
|
|
65
|
+
1: ["blue"],
|
|
66
|
+
5: ["darkblue", "darkorange", "cornflowerblue", "brown", "gray"],
|
|
67
67
|
9: [
|
|
68
68
|
"darkblue",
|
|
69
69
|
"darkorange",
|
mgplot/utilities.py
CHANGED
|
@@ -14,7 +14,7 @@ import math
|
|
|
14
14
|
from typing import Any, Final
|
|
15
15
|
|
|
16
16
|
import numpy as np
|
|
17
|
-
from matplotlib import
|
|
17
|
+
from matplotlib import colormaps
|
|
18
18
|
from matplotlib.axes import Axes
|
|
19
19
|
from matplotlib.pyplot import subplots
|
|
20
20
|
from pandas import DataFrame, Period, PeriodIndex, RangeIndex, Series
|
|
@@ -186,7 +186,7 @@ def get_color_list(count: int) -> list[str]:
|
|
|
186
186
|
options = [k for k in colors if k > count]
|
|
187
187
|
return colors[min(options)][:count]
|
|
188
188
|
|
|
189
|
-
c =
|
|
189
|
+
c = colormaps["nipy_spectral"](np.linspace(0, 1, count))
|
|
190
190
|
return [f"#{int(x * 255):02x}{int(y * 255):02x}{int(z * 255):02x}" for x, y, z, _ in c]
|
|
191
191
|
|
|
192
192
|
|
|
@@ -1,24 +1,25 @@
|
|
|
1
1
|
mgplot/__init__.py,sha256=J3CQX5UXrGXrfs-YWpbzHA_sz1HJ5438xNM0V36x1vo,3164
|
|
2
|
-
mgplot/
|
|
2
|
+
mgplot/annotation_utils.py,sha256=TH4_YSU6DAUR7qI6L72d5fcQ_hfSTaCkAWw_eN6OUjE,12957
|
|
3
|
+
mgplot/axis_utils.py,sha256=-wnjUTL2MdwEntLEVihDABOxLSbux0aSyATCnIsVumg,16041
|
|
3
4
|
mgplot/bar_plot.py,sha256=FobAsadYSEf-U0RZFgZutTzse4Rgr0TDFyWUMM68JVs,12513
|
|
4
5
|
mgplot/colors.py,sha256=f5q4z7kORUu66uAxNeK9KAZ64gv_7h_x2qH53BvzwPw,4848
|
|
5
6
|
mgplot/fill_between_plot.py,sha256=XJvtkBeOkohHyayQnu84jURapB5RsMAR-3SaskHkHfM,3361
|
|
6
|
-
mgplot/finalise_plot.py,sha256=
|
|
7
|
+
mgplot/finalise_plot.py,sha256=V1kqIkGRD7Hxotb4rwdWD2N4HQ775oP63qJtg-5eddQ,15811
|
|
7
8
|
mgplot/finalisers.py,sha256=Wozq4XOmnMdhEB9LJqHao9TrleOfhNV54kRa_bgN-e8,10547
|
|
8
9
|
mgplot/growth_plot.py,sha256=QALNYyINd_u7BL3q-My16eRuhq0LzGfawu-_MsVOXl0,8708
|
|
9
10
|
mgplot/keyword_checking.py,sha256=8CFexwEK_Uyv3_8hAnJ2ewk0tEjNjkwzKfX2uFw2UpM,11446
|
|
10
|
-
mgplot/line_plot.py,sha256=
|
|
11
|
+
mgplot/line_plot.py,sha256=LWxG1SpjWxiKHiyIllmW-t5692azvKM3Zfn3tQRZPfU,8884
|
|
11
12
|
mgplot/lint-all.sh,sha256=O7ns09v0cQNQ6POWtXtYn6VdtYURHTjy06vntR8tr_U,465
|
|
12
13
|
mgplot/multi_plot.py,sha256=8tiUXe1UJGyPvHp3ox2CQ5b-KjdSV9y5avI_70uJFMk,10699
|
|
13
14
|
mgplot/postcovid_plot.py,sha256=TR3BY_1CbIR2IRvlqqbqhhacEyUMDZIEL-mcLs9FV3U,8716
|
|
14
15
|
mgplot/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
|
15
|
-
mgplot/revision_plot.py,sha256=
|
|
16
|
+
mgplot/revision_plot.py,sha256=GC4h-7VKBkA0wdvbzsRtOdexdjJBrqZ6cDtGaq-65LE,2238
|
|
16
17
|
mgplot/run_plot.py,sha256=tG5YbAZ11WEBw9Jxanpp1W5E-q3sMUd5VjD7yIxrgY8,7355
|
|
17
18
|
mgplot/seastrend_plot.py,sha256=hi9t0cY0bHdIOU5abLMX7qvAp_hlVLlJFyEKNBzg6Ts,2000
|
|
18
|
-
mgplot/settings.py,sha256=
|
|
19
|
+
mgplot/settings.py,sha256=RhxgX4d-CgRpvs-ALG_j8tg3wwHSyfvFNdL0aMjofA0,5584
|
|
19
20
|
mgplot/summary_plot.py,sha256=Kg7VD8KFIls4KlD4jeaaXnDw51BZ3p_wMAUpjG49zGQ,11102
|
|
20
|
-
mgplot/utilities.py,sha256=
|
|
21
|
-
mgplot-0.2.
|
|
22
|
-
mgplot-0.2.
|
|
23
|
-
mgplot-0.2.
|
|
24
|
-
mgplot-0.2.
|
|
21
|
+
mgplot/utilities.py,sha256=PfzThb_nXYIMhnprQzNcaBqUZV8ysHJte0TU7TIis00,8450
|
|
22
|
+
mgplot-0.2.28.dist-info/METADATA,sha256=q2AmSQopJUk5gsl79y07AUQu1Ai1sqcXOwRd0Dsmhgg,7923
|
|
23
|
+
mgplot-0.2.28.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
|
|
24
|
+
mgplot-0.2.28.dist-info/licenses/LICENSE,sha256=6ZyruOwF8J7mY25-vZHdOibtY8cSNLz0vWeH59TLhtw,1082
|
|
25
|
+
mgplot-0.2.28.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|