mgplot 0.2.28__py3-none-any.whl → 0.2.30__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/finalise_plot.py +165 -6
- {mgplot-0.2.28.dist-info → mgplot-0.2.30.dist-info}/METADATA +1 -1
- {mgplot-0.2.28.dist-info → mgplot-0.2.30.dist-info}/RECORD +5 -5
- {mgplot-0.2.28.dist-info → mgplot-0.2.30.dist-info}/WHEEL +1 -1
- {mgplot-0.2.28.dist-info → mgplot-0.2.30.dist-info}/licenses/LICENSE +0 -0
mgplot/finalise_plot.py
CHANGED
|
@@ -7,8 +7,12 @@ from pathlib import Path
|
|
|
7
7
|
from typing import Any, Final, NotRequired, Unpack
|
|
8
8
|
|
|
9
9
|
import matplotlib.pyplot as plt
|
|
10
|
+
import numpy as np
|
|
10
11
|
from matplotlib.axes import Axes
|
|
11
12
|
from matplotlib.figure import Figure, SubFigure
|
|
13
|
+
from matplotlib.lines import Line2D
|
|
14
|
+
from matplotlib.patches import Rectangle
|
|
15
|
+
from matplotlib.transforms import blended_transform_factory
|
|
12
16
|
from pandas import Period, PeriodIndex
|
|
13
17
|
|
|
14
18
|
from mgplot.annotation_utils import resolve_annotation_collisions
|
|
@@ -28,6 +32,12 @@ ZERO_LINE_WIDTH: Final[float] = 0.66
|
|
|
28
32
|
ZERO_LINE_COLOR: Final[str] = "#555555"
|
|
29
33
|
ZERO_AXIS_ADJUSTMENT: Final[float] = 0.02
|
|
30
34
|
DEFAULT_FILE_TITLE_NAME: Final[str] = "plot"
|
|
35
|
+
# --- annotated axvline text
|
|
36
|
+
VLINE_TEXT_FONTSIZE: Final[str] = "xx-small"
|
|
37
|
+
VLINE_TEXT_ROTATION: Final[int] = 90
|
|
38
|
+
VLINE_TEXT_OFFSET: Final[float] = 3.0 # points, to the right of the line
|
|
39
|
+
VLINE_TEXT_PAD: Final[float] = 0.01 # axes fraction, in from the top/bottom
|
|
40
|
+
VLINE_AUTO_BAND: Final[float] = 0.02 # fraction of the x-span sampled either side
|
|
31
41
|
|
|
32
42
|
|
|
33
43
|
class FinaliseKwargs(BaseKwargs):
|
|
@@ -38,9 +48,9 @@ class FinaliseKwargs(BaseKwargs):
|
|
|
38
48
|
title: NotRequired[str | None]
|
|
39
49
|
xlabel: NotRequired[str | None]
|
|
40
50
|
ylabel: NotRequired[str | None]
|
|
41
|
-
xlim: NotRequired[tuple[float, float] | None]
|
|
51
|
+
xlim: NotRequired[tuple[float | int | Period, float | int | Period] | None]
|
|
42
52
|
ylim: NotRequired[tuple[float, float] | None]
|
|
43
|
-
xticks: NotRequired[list[float] | None]
|
|
53
|
+
xticks: NotRequired[list[float | int | Period] | None]
|
|
44
54
|
yticks: NotRequired[list[float] | None]
|
|
45
55
|
xscale: NotRequired[str | None]
|
|
46
56
|
yscale: NotRequired[str | None]
|
|
@@ -179,7 +189,7 @@ def apply_value_kwargs(axes: Axes, value_kwargs_: Sequence[str], **kwargs: Unpac
|
|
|
179
189
|
|
|
180
190
|
# --- loop over potential value settings
|
|
181
191
|
for setting in value_kwargs_:
|
|
182
|
-
value = kwargs.get(setting)
|
|
192
|
+
value = _convert_period_value(axes, setting, kwargs.get(setting))
|
|
183
193
|
if setting in kwargs:
|
|
184
194
|
# deliberately set, so we will action
|
|
185
195
|
axes.set(**{setting: value})
|
|
@@ -238,6 +248,150 @@ def _convert_period_coords(axes: Axes, method_name: str, item: dict[str, Any]) -
|
|
|
238
248
|
return converted
|
|
239
249
|
|
|
240
250
|
|
|
251
|
+
# Value-kwargs whose entries are x-axis coordinates — like axvline/axvspan, a
|
|
252
|
+
# Period passed here must be converted to its ordinal on a period-mapped axes.
|
|
253
|
+
_PERIOD_X_VALUE_KWARGS: Final[tuple[str, ...]] = ("xlim", "xticks")
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _convert_period_value(axes: Axes, setting: str, value: object) -> object:
|
|
257
|
+
"""Return value with any Period x-coordinates replaced by ordinals.
|
|
258
|
+
|
|
259
|
+
xlim is a 2-tuple and xticks a list; either may contain Periods when the
|
|
260
|
+
caller describes the axis in calendar terms. On a period-mapped axes the
|
|
261
|
+
Period freq must match the axes' stashed freq (see register_period_axes).
|
|
262
|
+
Non-x settings, None, and non-Period entries pass through unchanged.
|
|
263
|
+
"""
|
|
264
|
+
if setting not in _PERIOD_X_VALUE_KWARGS or not isinstance(value, (tuple, list)):
|
|
265
|
+
return value
|
|
266
|
+
stash = get_period_axes(axes)
|
|
267
|
+
stashed_freq = stash[0] if stash is not None else None
|
|
268
|
+
converted: list[object] = []
|
|
269
|
+
for val in value:
|
|
270
|
+
if isinstance(val, Period):
|
|
271
|
+
if stashed_freq is not None and val.freqstr != stashed_freq:
|
|
272
|
+
raise ValueError(
|
|
273
|
+
f"{setting} Period freq {val.freqstr!r} does not match axes freq {stashed_freq!r}",
|
|
274
|
+
)
|
|
275
|
+
if stashed_freq is not None:
|
|
276
|
+
# Widen the stash so the later label refresh covers this coordinate.
|
|
277
|
+
register_period_axes(axes, PeriodIndex([val]))
|
|
278
|
+
converted.append(val.ordinal)
|
|
279
|
+
else:
|
|
280
|
+
converted.append(val)
|
|
281
|
+
return tuple(converted) if isinstance(value, tuple) else converted
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
# --- annotated vertical lines
|
|
285
|
+
# "text", "loc" and "text_kwargs" in an axvline dict describe its label rather
|
|
286
|
+
# than the line, and are popped before the dict is splatted into ax.axvline().
|
|
287
|
+
_VLINE_LOCATIONS: Final[tuple[str, ...]] = ("auto", "top", "bottom")
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _pop_vline_text(item: dict[str, Any]) -> tuple[str, str, dict[str, Any]] | None:
|
|
291
|
+
"""Remove the label keys from an axvline dict and return them, or None if unlabelled.
|
|
292
|
+
|
|
293
|
+
Raises on a bad loc, a non-dict text_kwargs, or label options given
|
|
294
|
+
without any text to place -- each of which is a typo, not a choice.
|
|
295
|
+
"""
|
|
296
|
+
text = item.pop("text", None)
|
|
297
|
+
loc = item.pop("loc", "auto")
|
|
298
|
+
text_kwargs = item.pop("text_kwargs", {})
|
|
299
|
+
|
|
300
|
+
if text is None or not str(text).strip():
|
|
301
|
+
if loc != "auto" or text_kwargs:
|
|
302
|
+
raise ValueError("axvline 'loc'/'text_kwargs' given without any 'text' to place")
|
|
303
|
+
return None
|
|
304
|
+
if loc not in _VLINE_LOCATIONS:
|
|
305
|
+
raise ValueError(f"axvline 'loc' must be one of {_VLINE_LOCATIONS}, got {loc!r}")
|
|
306
|
+
if not isinstance(text_kwargs, dict):
|
|
307
|
+
raise TypeError(f"axvline 'text_kwargs' must be a dict, got {type(text_kwargs)}")
|
|
308
|
+
return str(text), loc, text_kwargs
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _data_y_extent(axes: Axes, x: float) -> tuple[float, float] | None:
|
|
312
|
+
"""Return the (min, max) y of plotted data in a narrow x-band around x.
|
|
313
|
+
|
|
314
|
+
A rotated label occupies only a sliver of the x-axis, so a narrow band is
|
|
315
|
+
what the eye actually judges. Lines are matched by transform identity:
|
|
316
|
+
axhline/axvline use blended transforms, so this skips them and measures
|
|
317
|
+
only real data. Rectangles cover bar plots; axvspan/axhspan patches are
|
|
318
|
+
likewise blended and skipped. Returns None when nothing is measurable.
|
|
319
|
+
"""
|
|
320
|
+
left, right = axes.get_xlim()
|
|
321
|
+
half = abs(right - left) * VLINE_AUTO_BAND
|
|
322
|
+
low, high = x - half, x + half
|
|
323
|
+
found: list[float] = []
|
|
324
|
+
|
|
325
|
+
for line in axes.get_lines():
|
|
326
|
+
if not isinstance(line, Line2D) or line.get_transform() is not axes.transData:
|
|
327
|
+
continue
|
|
328
|
+
xdata = np.asarray(line.get_xdata(), dtype=float)
|
|
329
|
+
ydata = np.asarray(line.get_ydata(), dtype=float)
|
|
330
|
+
if xdata.size != ydata.size or xdata.size == 0:
|
|
331
|
+
continue
|
|
332
|
+
wanted = (xdata >= low) & (xdata <= high) & ~np.isnan(ydata)
|
|
333
|
+
if wanted.any():
|
|
334
|
+
found.extend((float(ydata[wanted].min()), float(ydata[wanted].max())))
|
|
335
|
+
|
|
336
|
+
for patch in axes.patches:
|
|
337
|
+
if not isinstance(patch, Rectangle) or patch.get_data_transform() is not axes.transData:
|
|
338
|
+
continue
|
|
339
|
+
x0, width = patch.get_x(), patch.get_width()
|
|
340
|
+
y0, height = patch.get_y(), patch.get_height()
|
|
341
|
+
if min(x0, x0 + width) > high or max(x0, x0 + width) < low:
|
|
342
|
+
continue
|
|
343
|
+
found.extend((min(y0, y0 + height), max(y0, y0 + height)))
|
|
344
|
+
|
|
345
|
+
if not found:
|
|
346
|
+
return None
|
|
347
|
+
return min(found), max(found)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _auto_vline_loc(axes: Axes, x: float) -> str:
|
|
351
|
+
"""Pick the end of the axes with more room between the data and the limit."""
|
|
352
|
+
extent = _data_y_extent(axes, x)
|
|
353
|
+
if extent is None:
|
|
354
|
+
return "top" # nothing measurable (empty band, or an unrecognised artist)
|
|
355
|
+
data_low, data_high = extent
|
|
356
|
+
bottom_lim, top_lim = axes.get_ylim()
|
|
357
|
+
if top_lim >= bottom_lim:
|
|
358
|
+
top_gap, bottom_gap = top_lim - data_high, data_low - bottom_lim
|
|
359
|
+
else: # inverted y-axis: values decrease going up the display
|
|
360
|
+
top_gap, bottom_gap = data_low - top_lim, bottom_lim - data_high
|
|
361
|
+
return "top" if top_gap >= bottom_gap else "bottom"
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _annotate_vline(axes: Axes, item: dict[str, Any], line: Line2D, spec: tuple[str, str, dict]) -> None:
|
|
365
|
+
"""Place a rotated text label just to the right of a vertical line.
|
|
366
|
+
|
|
367
|
+
The label is anchored with x in data coordinates and y in axes
|
|
368
|
+
coordinates, so it stays pinned to the top/bottom of the plot regardless
|
|
369
|
+
of any later change to the y-limits.
|
|
370
|
+
"""
|
|
371
|
+
text, loc, text_kwargs = spec
|
|
372
|
+
x = item.get("x", 0) # matches the matplotlib default for axvline
|
|
373
|
+
if loc == "auto":
|
|
374
|
+
loc = _auto_vline_loc(axes, float(x))
|
|
375
|
+
y, valign = (1.0 - VLINE_TEXT_PAD, "top") if loc == "top" else (VLINE_TEXT_PAD, "bottom")
|
|
376
|
+
|
|
377
|
+
options: dict[str, Any] = {
|
|
378
|
+
"rotation": VLINE_TEXT_ROTATION,
|
|
379
|
+
"fontsize": VLINE_TEXT_FONTSIZE,
|
|
380
|
+
"color": line.get_color(),
|
|
381
|
+
"ha": "left",
|
|
382
|
+
"va": valign,
|
|
383
|
+
}
|
|
384
|
+
options.update(text_kwargs)
|
|
385
|
+
axes.annotate(
|
|
386
|
+
text,
|
|
387
|
+
xy=(x, y),
|
|
388
|
+
xycoords=blended_transform_factory(axes.transData, axes.transAxes),
|
|
389
|
+
xytext=(VLINE_TEXT_OFFSET, 0),
|
|
390
|
+
textcoords="offset points",
|
|
391
|
+
**options,
|
|
392
|
+
)
|
|
393
|
+
|
|
394
|
+
|
|
241
395
|
def _apply_splat(axes: Axes, method_name: str, value: _SplatValue) -> None:
|
|
242
396
|
"""Apply a single splat kwarg, which may be a dict or sequence of dicts."""
|
|
243
397
|
if value is None or value is False:
|
|
@@ -253,10 +407,15 @@ def _apply_splat(axes: Axes, method_name: str, value: _SplatValue) -> None:
|
|
|
253
407
|
if isinstance(value, Sequence):
|
|
254
408
|
method = getattr(axes, method_name)
|
|
255
409
|
for item in value:
|
|
256
|
-
if isinstance(item, dict):
|
|
257
|
-
method(**_convert_period_coords(axes, method_name, item))
|
|
258
|
-
else:
|
|
410
|
+
if not isinstance(item, dict):
|
|
259
411
|
print(f"Warning: expected dict in {method_name} sequence, but got {type(item)}.")
|
|
412
|
+
continue
|
|
413
|
+
converted = _convert_period_coords(axes, method_name, item)
|
|
414
|
+
# _convert_period_coords always copies, so popping is safe here
|
|
415
|
+
spec = _pop_vline_text(converted) if method_name == "axvline" else None
|
|
416
|
+
artist = method(**converted)
|
|
417
|
+
if spec is not None and isinstance(artist, Line2D):
|
|
418
|
+
_annotate_vline(axes, converted, artist, spec)
|
|
260
419
|
else:
|
|
261
420
|
print(f"Warning: expected dict or sequence of dicts for {method_name}, but got {type(value)}.")
|
|
262
421
|
|
|
@@ -4,7 +4,7 @@ mgplot/axis_utils.py,sha256=-wnjUTL2MdwEntLEVihDABOxLSbux0aSyATCnIsVumg,16041
|
|
|
4
4
|
mgplot/bar_plot.py,sha256=FobAsadYSEf-U0RZFgZutTzse4Rgr0TDFyWUMM68JVs,12513
|
|
5
5
|
mgplot/colors.py,sha256=f5q4z7kORUu66uAxNeK9KAZ64gv_7h_x2qH53BvzwPw,4848
|
|
6
6
|
mgplot/fill_between_plot.py,sha256=XJvtkBeOkohHyayQnu84jURapB5RsMAR-3SaskHkHfM,3361
|
|
7
|
-
mgplot/finalise_plot.py,sha256=
|
|
7
|
+
mgplot/finalise_plot.py,sha256=ttuzI6q4hnS1w-nDfQY7DXc3Dti1y4PdH3ihSYSeppc,22935
|
|
8
8
|
mgplot/finalisers.py,sha256=Wozq4XOmnMdhEB9LJqHao9TrleOfhNV54kRa_bgN-e8,10547
|
|
9
9
|
mgplot/growth_plot.py,sha256=QALNYyINd_u7BL3q-My16eRuhq0LzGfawu-_MsVOXl0,8708
|
|
10
10
|
mgplot/keyword_checking.py,sha256=8CFexwEK_Uyv3_8hAnJ2ewk0tEjNjkwzKfX2uFw2UpM,11446
|
|
@@ -19,7 +19,7 @@ mgplot/seastrend_plot.py,sha256=hi9t0cY0bHdIOU5abLMX7qvAp_hlVLlJFyEKNBzg6Ts,2000
|
|
|
19
19
|
mgplot/settings.py,sha256=RhxgX4d-CgRpvs-ALG_j8tg3wwHSyfvFNdL0aMjofA0,5584
|
|
20
20
|
mgplot/summary_plot.py,sha256=Kg7VD8KFIls4KlD4jeaaXnDw51BZ3p_wMAUpjG49zGQ,11102
|
|
21
21
|
mgplot/utilities.py,sha256=PfzThb_nXYIMhnprQzNcaBqUZV8ysHJte0TU7TIis00,8450
|
|
22
|
-
mgplot-0.2.
|
|
23
|
-
mgplot-0.2.
|
|
24
|
-
mgplot-0.2.
|
|
25
|
-
mgplot-0.2.
|
|
22
|
+
mgplot-0.2.30.dist-info/METADATA,sha256=JdoL-6YU9Zt1heiQW4Aw31dqNIOizHlvi7mAPZxT3B8,7923
|
|
23
|
+
mgplot-0.2.30.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
24
|
+
mgplot-0.2.30.dist-info/licenses/LICENSE,sha256=6ZyruOwF8J7mY25-vZHdOibtY8cSNLz0vWeH59TLhtw,1082
|
|
25
|
+
mgplot-0.2.30.dist-info/RECORD,,
|
|
File without changes
|