mgplot 0.2.24__py3-none-any.whl → 0.2.26__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/axis_utils.py +64 -7
- mgplot/bar_plot.py +96 -33
- mgplot/fill_between_plot.py +8 -1
- mgplot/finalise_plot.py +5 -2
- mgplot/growth_plot.py +8 -1
- mgplot/keyword_checking.py +4 -1
- mgplot/line_plot.py +8 -2
- mgplot/run_plot.py +6 -1
- {mgplot-0.2.24.dist-info → mgplot-0.2.26.dist-info}/METADATA +91 -3
- {mgplot-0.2.24.dist-info → mgplot-0.2.26.dist-info}/RECORD +12 -12
- {mgplot-0.2.24.dist-info → mgplot-0.2.26.dist-info}/WHEEL +0 -0
- {mgplot-0.2.24.dist-info → mgplot-0.2.26.dist-info}/licenses/LICENSE +0 -0
mgplot/axis_utils.py
CHANGED
|
@@ -8,8 +8,9 @@ such as days, months, quarters, and years.
|
|
|
8
8
|
"""
|
|
9
9
|
|
|
10
10
|
import calendar
|
|
11
|
+
from collections.abc import Callable
|
|
11
12
|
from enum import Enum
|
|
12
|
-
from typing import Final
|
|
13
|
+
from typing import Any, Final
|
|
13
14
|
|
|
14
15
|
from matplotlib.axes import Axes
|
|
15
16
|
from pandas import Index, Period, PeriodIndex, RangeIndex, period_range
|
|
@@ -33,6 +34,32 @@ def map_stringindex(data: DataT) -> None | tuple[DataT, list[str]]:
|
|
|
33
34
|
|
|
34
35
|
|
|
35
36
|
_AXES_PERIOD_ATTR: Final[str] = "_mgplot_period"
|
|
37
|
+
_AXES_LABEL_OPTS_ATTR: Final[str] = "_mgplot_label_opts"
|
|
38
|
+
DEFAULT_REFRESH_TICKS: Final[int] = 10
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def register_label_options(
|
|
42
|
+
axes: Axes,
|
|
43
|
+
*,
|
|
44
|
+
max_ticks: int | None = None,
|
|
45
|
+
rotation: float | None = None,
|
|
46
|
+
tick_relabel: Callable[[str], str] | None = None,
|
|
47
|
+
) -> None:
|
|
48
|
+
"""Merge non-None tick-label options into the options stashed on an Axes.
|
|
49
|
+
|
|
50
|
+
Stashed options (max_ticks, rotation, tick_relabel) are re-read by
|
|
51
|
+
refresh_period_labels(), so settings made at plot time survive the
|
|
52
|
+
label refresh that finalise_plot() performs just before saving.
|
|
53
|
+
"""
|
|
54
|
+
options = {"max_ticks": max_ticks, "rotation": rotation, "tick_relabel": tick_relabel}
|
|
55
|
+
stash: dict[str, Any] = getattr(axes, _AXES_LABEL_OPTS_ATTR, {})
|
|
56
|
+
stash.update({k: v for k, v in options.items() if v is not None})
|
|
57
|
+
setattr(axes, _AXES_LABEL_OPTS_ATTR, stash)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def get_label_options(axes: Axes) -> dict[str, Any]:
|
|
61
|
+
"""Return the stashed tick-label options for an axes (empty dict if none)."""
|
|
62
|
+
return getattr(axes, _AXES_LABEL_OPTS_ATTR, {})
|
|
36
63
|
|
|
37
64
|
|
|
38
65
|
def register_period_axes(axes: Axes, p: PeriodIndex) -> None:
|
|
@@ -355,12 +382,18 @@ def make_labels(p: PeriodIndex, max_ticks: int) -> dict[Period, str]:
|
|
|
355
382
|
return labels
|
|
356
383
|
|
|
357
384
|
|
|
358
|
-
def make_ilabels(
|
|
385
|
+
def make_ilabels(
|
|
386
|
+
p: PeriodIndex,
|
|
387
|
+
max_ticks: int,
|
|
388
|
+
tick_relabel: Callable[[str], str] | None = None,
|
|
389
|
+
) -> tuple[list[int], list[str]]:
|
|
359
390
|
"""From a PeriodIndex, create a list of integer ticks and ticklabels.
|
|
360
391
|
|
|
361
392
|
Args:
|
|
362
393
|
p: PeriodIndex - the PeriodIndex
|
|
363
394
|
max_ticks: int - the maximum number of ticks [suggestive]
|
|
395
|
+
tick_relabel: optional callable applied to each generated label
|
|
396
|
+
string (after the contextual labellers have run).
|
|
364
397
|
|
|
365
398
|
Returns a tuple:
|
|
366
399
|
list of integer ticks
|
|
@@ -370,21 +403,30 @@ def make_ilabels(p: PeriodIndex, max_ticks: int) -> tuple[list[int], list[str]]:
|
|
|
370
403
|
labels = make_labels(p, max_ticks)
|
|
371
404
|
ticks = [x.ordinal for x in sorted(labels.keys())]
|
|
372
405
|
ticklabels = [labels[x] for x in sorted(labels.keys())]
|
|
406
|
+
if tick_relabel is not None:
|
|
407
|
+
ticklabels = [tick_relabel(label) for label in ticklabels]
|
|
373
408
|
|
|
374
409
|
return ticks, ticklabels
|
|
375
410
|
|
|
376
411
|
|
|
377
|
-
def refresh_period_labels(axes: Axes, max_ticks: int =
|
|
412
|
+
def refresh_period_labels(axes: Axes, max_ticks: int | None = None) -> None:
|
|
378
413
|
"""Regenerate x-axis tick labels from the stashed period range and current xlim.
|
|
379
414
|
|
|
380
415
|
No-op when the axes has no period stash. Uses the wider of the stash and
|
|
381
416
|
the current xlim so that artists added after the most recent set_labels()
|
|
382
417
|
call (e.g. axvspan/axvline in finalise_plot) still get covered by ticks.
|
|
418
|
+
|
|
419
|
+
Label options (max_ticks, rotation, tick_relabel) stashed by set_labels()
|
|
420
|
+
are honoured, so a refresh reproduces what the plot function originally
|
|
421
|
+
built. An explicit max_ticks argument overrides the stashed value.
|
|
383
422
|
"""
|
|
384
423
|
stash = get_period_axes(axes)
|
|
385
424
|
if stash is None:
|
|
386
425
|
return
|
|
387
426
|
freq, stash_min, stash_max = stash
|
|
427
|
+
options = get_label_options(axes)
|
|
428
|
+
if max_ticks is None:
|
|
429
|
+
max_ticks = options.get("max_ticks", DEFAULT_REFRESH_TICKS)
|
|
388
430
|
xlim = axes.get_xlim()
|
|
389
431
|
x_min = min(stash_min, int(xlim[0]))
|
|
390
432
|
x_max = max(stash_max, int(xlim[1]))
|
|
@@ -395,12 +437,19 @@ def refresh_period_labels(axes: Axes, max_ticks: int = 10) -> None:
|
|
|
395
437
|
freq=freq,
|
|
396
438
|
)
|
|
397
439
|
|
|
398
|
-
ticks, ticklabels = make_ilabels(full_range, max_ticks)
|
|
440
|
+
ticks, ticklabels = make_ilabels(full_range, max_ticks, options.get("tick_relabel"))
|
|
399
441
|
axes.set_xticks(ticks)
|
|
400
|
-
axes.set_xticklabels(ticklabels, rotation=0, ha="center")
|
|
442
|
+
axes.set_xticklabels(ticklabels, rotation=options.get("rotation", 0), ha="center")
|
|
401
443
|
|
|
402
444
|
|
|
403
|
-
def set_labels(
|
|
445
|
+
def set_labels(
|
|
446
|
+
axes: Axes,
|
|
447
|
+
p: PeriodIndex,
|
|
448
|
+
max_ticks: int = 10,
|
|
449
|
+
*,
|
|
450
|
+
rotation: float | None = None,
|
|
451
|
+
tick_relabel: Callable[[str], str] | None = None,
|
|
452
|
+
) -> None:
|
|
404
453
|
"""Set the x-axis labels for a date-like PeriodIndex.
|
|
405
454
|
|
|
406
455
|
Registers the PeriodIndex on the axes (see register_period_axes()). When
|
|
@@ -408,11 +457,19 @@ def set_labels(axes: Axes, p: PeriodIndex, max_ticks: int = 10) -> None:
|
|
|
408
457
|
the union of everything plotted so far, so ticks always span the full
|
|
409
458
|
extent of all plotted data.
|
|
410
459
|
|
|
460
|
+
The label options are stashed on the axes so that later refreshes
|
|
461
|
+
(including the one in finalise_plot()) reproduce them.
|
|
462
|
+
|
|
411
463
|
Args:
|
|
412
464
|
axes: Axes - the axes to set the labels on
|
|
413
465
|
p: PeriodIndex - the PeriodIndex (registers freq and ordinal range)
|
|
414
466
|
max_ticks: int - the maximum number of ticks [suggestive]
|
|
467
|
+
rotation: optional rotation (degrees) for the tick labels
|
|
468
|
+
tick_relabel: optional callable applied to each label string after
|
|
469
|
+
the contextual labellers have run (e.g. shorten years to two
|
|
470
|
+
digits).
|
|
415
471
|
|
|
416
472
|
"""
|
|
417
473
|
register_period_axes(axes, p)
|
|
418
|
-
|
|
474
|
+
register_label_options(axes, max_ticks=max_ticks, rotation=rotation, tick_relabel=tick_relabel)
|
|
475
|
+
refresh_period_labels(axes)
|
mgplot/bar_plot.py
CHANGED
|
@@ -6,11 +6,10 @@ rectangular bars. As a result, bar plots and line plots typically
|
|
|
6
6
|
cannot be plotted on the same axes.
|
|
7
7
|
"""
|
|
8
8
|
|
|
9
|
-
from collections.abc import Sequence
|
|
9
|
+
from collections.abc import Callable, Sequence
|
|
10
10
|
from typing import Any, Final, NotRequired, TypedDict, Unpack
|
|
11
11
|
|
|
12
12
|
import matplotlib.patheffects as pe
|
|
13
|
-
import matplotlib.pyplot as plt
|
|
14
13
|
import numpy as np
|
|
15
14
|
from matplotlib.axes import Axes
|
|
16
15
|
from pandas import DataFrame, Period, Series
|
|
@@ -43,7 +42,9 @@ class BarKwargs(BaseKwargs):
|
|
|
43
42
|
# --- options for the entire bar plot
|
|
44
43
|
ax: NotRequired[Axes | None]
|
|
45
44
|
stacked: NotRequired[bool]
|
|
45
|
+
horizontal: NotRequired[bool]
|
|
46
46
|
max_ticks: NotRequired[int]
|
|
47
|
+
tick_relabel: NotRequired[Callable[[str], str]]
|
|
47
48
|
plot_from: NotRequired[int | Period]
|
|
48
49
|
label_rotation: NotRequired[int | float]
|
|
49
50
|
# --- options for each bar ...
|
|
@@ -70,7 +71,7 @@ class AnnoKwargs(TypedDict, total=False):
|
|
|
70
71
|
fontname: str
|
|
71
72
|
color: str
|
|
72
73
|
rotation: int | float
|
|
73
|
-
foreground: str # used for stroke effect on text
|
|
74
|
+
foreground: str | Sequence[str] # used for stroke effect on text (per-bar if a sequence)
|
|
74
75
|
above: bool
|
|
75
76
|
rounding: bool | int # if True, uses default rounding; if int, uses that value
|
|
76
77
|
|
|
@@ -80,10 +81,15 @@ def annotate_bars(
|
|
|
80
81
|
offset: float,
|
|
81
82
|
base: np.ndarray,
|
|
82
83
|
axes: Axes,
|
|
84
|
+
*,
|
|
85
|
+
horizontal: bool = False,
|
|
83
86
|
**anno_kwargs: Unpack[AnnoKwargs],
|
|
84
87
|
) -> None:
|
|
85
88
|
"""Bar plot annotations.
|
|
86
89
|
|
|
90
|
+
Annotations are placed along the value axis: the y-axis for vertical
|
|
91
|
+
bars, the x-axis when horizontal=True.
|
|
92
|
+
|
|
87
93
|
Note: "annotate", "fontsize", "fontname", "color", and "rotation" are expected in anno_kwargs.
|
|
88
94
|
"""
|
|
89
95
|
# --- only annotate in limited circumstances
|
|
@@ -115,18 +121,32 @@ def annotate_bars(
|
|
|
115
121
|
position = base[index - zero_correction] + (adjustment if value >= 0 else -adjustment)
|
|
116
122
|
if above:
|
|
117
123
|
position += value
|
|
124
|
+
if horizontal:
|
|
125
|
+
placement: dict[str, Any] = {
|
|
126
|
+
"x": position,
|
|
127
|
+
"y": index + offset,
|
|
128
|
+
"ha": "left" if value >= 0 else "right",
|
|
129
|
+
"va": "center",
|
|
130
|
+
}
|
|
131
|
+
else:
|
|
132
|
+
placement = {
|
|
133
|
+
"x": index + offset,
|
|
134
|
+
"y": position,
|
|
135
|
+
"ha": "center",
|
|
136
|
+
"va": "bottom" if value >= 0 else "top",
|
|
137
|
+
}
|
|
118
138
|
text = axes.text(
|
|
119
|
-
x=index + offset,
|
|
120
|
-
y=position,
|
|
121
139
|
s=f"{value:.{rounding}f}",
|
|
122
|
-
|
|
123
|
-
va="bottom" if value >= 0 else "top",
|
|
140
|
+
**placement,
|
|
124
141
|
**annotate_style,
|
|
125
142
|
)
|
|
126
143
|
if not above and "foreground" in anno_kwargs:
|
|
127
144
|
# apply a stroke-effect to within bar annotations
|
|
128
145
|
# to make them more readable with very small bars.
|
|
129
|
-
|
|
146
|
+
foreground = anno_kwargs.get("foreground")
|
|
147
|
+
if isinstance(foreground, Sequence) and not isinstance(foreground, str):
|
|
148
|
+
foreground = foreground[index - zero_correction] # per-bar colours
|
|
149
|
+
text.set_path_effects([pe.withStroke(linewidth=2, foreground=foreground)])
|
|
130
150
|
|
|
131
151
|
|
|
132
152
|
class GroupedKwargs(TypedDict):
|
|
@@ -138,7 +158,14 @@ class GroupedKwargs(TypedDict):
|
|
|
138
158
|
zorder: Sequence[int | float | None]
|
|
139
159
|
|
|
140
160
|
|
|
141
|
-
def grouped(
|
|
161
|
+
def grouped(
|
|
162
|
+
axes: Axes,
|
|
163
|
+
df: DataFrame,
|
|
164
|
+
anno_args: AnnoKwargs,
|
|
165
|
+
*,
|
|
166
|
+
horizontal: bool = False,
|
|
167
|
+
**kwargs: Unpack[GroupedKwargs],
|
|
168
|
+
) -> None:
|
|
142
169
|
"""Plot a grouped bar plot."""
|
|
143
170
|
series_count = len(df.columns)
|
|
144
171
|
|
|
@@ -154,20 +181,22 @@ def grouped(axes: Axes, df: DataFrame, anno_args: AnnoKwargs, **kwargs: Unpack[G
|
|
|
154
181
|
left = -DEFAULT_BAR_OFFSET + ((1 - width) / 2.0) + (adjusted_width / 2.0)
|
|
155
182
|
offset = left + (i * adjusted_width)
|
|
156
183
|
foreground = kwargs["color"][i]
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
184
|
+
common: dict[str, Any] = {
|
|
185
|
+
"color": foreground,
|
|
186
|
+
"zorder": kwargs["zorder"][i],
|
|
187
|
+
"label": col if kwargs["label_series"][i] else f"_{col}_",
|
|
188
|
+
}
|
|
189
|
+
if horizontal:
|
|
190
|
+
axes.barh(y=series.index + offset, width=series, height=adjusted_width, **common)
|
|
191
|
+
else:
|
|
192
|
+
axes.bar(x=series.index + offset, height=series, width=adjusted_width, **common)
|
|
165
193
|
anno_args["foreground"] = foreground
|
|
166
194
|
annotate_bars(
|
|
167
195
|
series=series,
|
|
168
196
|
offset=offset,
|
|
169
197
|
base=np.zeros(len(series)),
|
|
170
198
|
axes=axes,
|
|
199
|
+
horizontal=horizontal,
|
|
171
200
|
**anno_args,
|
|
172
201
|
)
|
|
173
202
|
|
|
@@ -181,7 +210,14 @@ class StackedKwargs(TypedDict):
|
|
|
181
210
|
zorder: Sequence[int | float | None]
|
|
182
211
|
|
|
183
212
|
|
|
184
|
-
def stacked(
|
|
213
|
+
def stacked(
|
|
214
|
+
axes: Axes,
|
|
215
|
+
df: DataFrame,
|
|
216
|
+
anno_args: AnnoKwargs,
|
|
217
|
+
*,
|
|
218
|
+
horizontal: bool = False,
|
|
219
|
+
**kwargs: Unpack[StackedKwargs],
|
|
220
|
+
) -> None:
|
|
185
221
|
"""Plot a stacked bar plot."""
|
|
186
222
|
row_count = len(df)
|
|
187
223
|
base_plus: np.ndarray = np.zeros(shape=row_count, dtype=np.float64)
|
|
@@ -190,21 +226,22 @@ def stacked(axes: Axes, df: DataFrame, anno_args: AnnoKwargs, **kwargs: Unpack[S
|
|
|
190
226
|
series = df[col]
|
|
191
227
|
base = np.where(series >= 0, base_plus, base_minus)
|
|
192
228
|
foreground = kwargs["color"][i]
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
229
|
+
common: dict[str, Any] = {
|
|
230
|
+
"color": foreground,
|
|
231
|
+
"zorder": kwargs["zorder"][i],
|
|
232
|
+
"label": col if kwargs["label_series"][i] else f"_{col}_",
|
|
233
|
+
}
|
|
234
|
+
if horizontal:
|
|
235
|
+
axes.barh(y=series.index, width=series, left=base, height=kwargs["width"][i], **common)
|
|
236
|
+
else:
|
|
237
|
+
axes.bar(x=series.index, height=series, bottom=base, width=kwargs["width"][i], **common)
|
|
202
238
|
anno_args["foreground"] = foreground
|
|
203
239
|
annotate_bars(
|
|
204
240
|
series=series,
|
|
205
241
|
offset=0,
|
|
206
242
|
base=base,
|
|
207
243
|
axes=axes,
|
|
244
|
+
horizontal=horizontal,
|
|
208
245
|
**anno_args,
|
|
209
246
|
)
|
|
210
247
|
base_plus += np.where(series >= 0, series, 0)
|
|
@@ -253,12 +290,29 @@ def bar_plot(data: DataT, **kwargs: Unpack[BarKwargs]) -> Axes:
|
|
|
253
290
|
# --- set up the default arguments
|
|
254
291
|
chart_defaults: dict[str, bool | int] = {
|
|
255
292
|
"stacked": False,
|
|
293
|
+
"horizontal": False,
|
|
256
294
|
"max_ticks": DEFAULT_MAX_TICKS,
|
|
257
295
|
"label_series": item_count > 1,
|
|
258
296
|
"label_rotation": 0,
|
|
259
297
|
}
|
|
260
298
|
chart_args = {k: kwargs_d.get(k, v) for k, v in chart_defaults.items()}
|
|
261
299
|
|
|
300
|
+
# --- horizontal bars are for categorical data, not PeriodIndex timeseries
|
|
301
|
+
horizontal = bool(chart_args["horizontal"])
|
|
302
|
+
if horizontal and saved_pi is not None:
|
|
303
|
+
print(f"Warning: horizontal=True is not supported with a PeriodIndex in {ME}(); plotting vertical.")
|
|
304
|
+
horizontal = False
|
|
305
|
+
|
|
306
|
+
# --- single series + one colour per bar => per-bar colours
|
|
307
|
+
user_color = kwargs_d.get("color")
|
|
308
|
+
if (
|
|
309
|
+
item_count == 1
|
|
310
|
+
and isinstance(user_color, Sequence)
|
|
311
|
+
and not isinstance(user_color, str)
|
|
312
|
+
and len(user_color) == len(df)
|
|
313
|
+
):
|
|
314
|
+
kwargs_d["color"] = [list(user_color)] # one series whose colour is a per-bar list
|
|
315
|
+
|
|
262
316
|
bar_defaults = {
|
|
263
317
|
"color": get_color_list(item_count),
|
|
264
318
|
"width": get_setting("bar_width"),
|
|
@@ -280,16 +334,25 @@ def bar_plot(data: DataT, **kwargs: Unpack[BarKwargs]) -> Axes:
|
|
|
280
334
|
# --- plot the data
|
|
281
335
|
axes, remaining_kwargs = get_axes(**dict(remaining_kwargs))
|
|
282
336
|
if chart_args["stacked"]:
|
|
283
|
-
stacked(axes, df, anno_args, **bar_args)
|
|
337
|
+
stacked(axes, df, anno_args, horizontal=horizontal, **bar_args)
|
|
284
338
|
else:
|
|
285
|
-
grouped(axes, df, anno_args, **bar_args)
|
|
339
|
+
grouped(axes, df, anno_args, horizontal=horizontal, **bar_args)
|
|
286
340
|
|
|
287
341
|
# --- handle index labels and rotation
|
|
288
342
|
if saved_strings is not None:
|
|
289
|
-
|
|
290
|
-
|
|
343
|
+
if horizontal:
|
|
344
|
+
axes.set_yticks(range(len(saved_strings[1])))
|
|
345
|
+
axes.set_yticklabels(saved_strings[1], rotation=chart_args["label_rotation"])
|
|
346
|
+
else:
|
|
347
|
+
axes.set_xticks(range(len(saved_strings[1])))
|
|
348
|
+
axes.set_xticklabels(saved_strings[1], rotation=chart_args["label_rotation"])
|
|
291
349
|
elif saved_pi is not None:
|
|
292
|
-
set_labels(
|
|
293
|
-
|
|
350
|
+
set_labels(
|
|
351
|
+
axes,
|
|
352
|
+
saved_pi[1],
|
|
353
|
+
chart_args["max_ticks"],
|
|
354
|
+
rotation=chart_args["label_rotation"],
|
|
355
|
+
tick_relabel=kwargs_d.get("tick_relabel"),
|
|
356
|
+
)
|
|
294
357
|
|
|
295
358
|
return axes
|
mgplot/fill_between_plot.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"""Plot a filled region between two bounds."""
|
|
2
2
|
|
|
3
|
+
from collections.abc import Callable
|
|
3
4
|
from typing import Final, NotRequired, Unpack
|
|
4
5
|
|
|
5
6
|
from matplotlib.axes import Axes
|
|
@@ -29,6 +30,7 @@ class FillBetweenKwargs(BaseKwargs):
|
|
|
29
30
|
zorder: NotRequired[int | float]
|
|
30
31
|
plot_from: NotRequired[int | None]
|
|
31
32
|
max_ticks: NotRequired[int]
|
|
33
|
+
tick_relabel: NotRequired[Callable[[str], str]]
|
|
32
34
|
|
|
33
35
|
|
|
34
36
|
def fill_between_plot(data: DataFrame, **kwargs: Unpack[FillBetweenKwargs]) -> Axes:
|
|
@@ -100,6 +102,11 @@ def fill_between_plot(data: DataFrame, **kwargs: Unpack[FillBetweenKwargs]) -> A
|
|
|
100
102
|
|
|
101
103
|
# --- set axis labels
|
|
102
104
|
if saved_pi is not None:
|
|
103
|
-
set_labels(
|
|
105
|
+
set_labels(
|
|
106
|
+
axes,
|
|
107
|
+
saved_pi[1],
|
|
108
|
+
kwargs_d.get("max_ticks", get_setting("max_ticks")),
|
|
109
|
+
tick_relabel=kwargs_d.get("tick_relabel"),
|
|
110
|
+
)
|
|
104
111
|
|
|
105
112
|
return axes
|
mgplot/finalise_plot.py
CHANGED
|
@@ -458,6 +458,9 @@ def finalise_plot(axes: Axes, **kwargs: Unpack[FinaliseKwargs]) -> None:
|
|
|
458
458
|
if not axes_only and kwargs.get("show"):
|
|
459
459
|
plt.show()
|
|
460
460
|
|
|
461
|
-
# And close
|
|
461
|
+
# And close - the figure this axes belongs to, not pyplot's current figure
|
|
462
462
|
if not axes_only and not kwargs.get("dont_close", False):
|
|
463
|
-
|
|
463
|
+
root = fig
|
|
464
|
+
while isinstance(root, SubFigure):
|
|
465
|
+
root = root.figure
|
|
466
|
+
plt.close(root)
|
mgplot/growth_plot.py
CHANGED
|
@@ -6,6 +6,7 @@ Key functions:
|
|
|
6
6
|
- series_growth_plot()
|
|
7
7
|
"""
|
|
8
8
|
|
|
9
|
+
from collections.abc import Callable
|
|
9
10
|
from typing import NotRequired, Unpack, cast
|
|
10
11
|
|
|
11
12
|
from matplotlib.axes import Axes
|
|
@@ -42,6 +43,7 @@ class GrowthKwargs(BaseKwargs):
|
|
|
42
43
|
plot_from: NotRequired[int | Period]
|
|
43
44
|
label_series: NotRequired[bool]
|
|
44
45
|
max_ticks: NotRequired[int]
|
|
46
|
+
tick_relabel: NotRequired[Callable[[str], str]]
|
|
45
47
|
# --- options passed to the line plot
|
|
46
48
|
line_width: NotRequired[float | int]
|
|
47
49
|
line_color: NotRequired[str]
|
|
@@ -219,7 +221,12 @@ def growth_plot(
|
|
|
219
221
|
|
|
220
222
|
# --- fix the x-axis labels
|
|
221
223
|
if saved_pi is not None:
|
|
222
|
-
set_labels(
|
|
224
|
+
set_labels(
|
|
225
|
+
axes,
|
|
226
|
+
saved_pi[1],
|
|
227
|
+
kwargsd.get("max_ticks", 10),
|
|
228
|
+
tick_relabel=kwargsd.get("tick_relabel"),
|
|
229
|
+
)
|
|
223
230
|
|
|
224
231
|
# --- and done ...
|
|
225
232
|
return axes
|
mgplot/keyword_checking.py
CHANGED
|
@@ -11,7 +11,7 @@ It is designed to be used interactively and in scripts.
|
|
|
11
11
|
"""
|
|
12
12
|
|
|
13
13
|
import textwrap
|
|
14
|
-
from collections.abc import Mapping, Sequence
|
|
14
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
15
15
|
from collections.abc import Set as AbstractSet
|
|
16
16
|
from types import UnionType
|
|
17
17
|
from typing import Any, Final, NotRequired, ReadOnly, TypedDict, Union, get_args, get_origin
|
|
@@ -184,6 +184,9 @@ def check(value: Any, expected: type) -> bool:
|
|
|
184
184
|
good = check_set(value, expected)
|
|
185
185
|
case _ if origin in (UnionType, Union):
|
|
186
186
|
good = check_union(value, expected)
|
|
187
|
+
case _ if origin is Callable:
|
|
188
|
+
# signatures are not checked, only callability
|
|
189
|
+
good = callable(value)
|
|
187
190
|
case _:
|
|
188
191
|
good = isinstance(value, expected) if hasattr(expected, "__origin__") else True
|
|
189
192
|
print(f"Keyword checking: {value} not checked against {expected}")
|
mgplot/line_plot.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"""Plot a series or a dataframe with lines."""
|
|
2
2
|
|
|
3
3
|
import math
|
|
4
|
-
from collections.abc import Sequence
|
|
4
|
+
from collections.abc import Callable, Sequence
|
|
5
5
|
from typing import Any, Final, NotRequired, TypedDict, Unpack
|
|
6
6
|
|
|
7
7
|
from matplotlib.axes import Axes
|
|
@@ -47,6 +47,7 @@ class LineKwargs(BaseKwargs):
|
|
|
47
47
|
plot_from: NotRequired[int | Period | None]
|
|
48
48
|
label_series: NotRequired[bool | Sequence[bool] | None]
|
|
49
49
|
max_ticks: NotRequired[int]
|
|
50
|
+
tick_relabel: NotRequired[Callable[[str], str]]
|
|
50
51
|
|
|
51
52
|
|
|
52
53
|
class AnnotateKwargs(TypedDict):
|
|
@@ -223,6 +224,11 @@ def line_plot(data: DataT, **kwargs: Unpack[LineKwargs]) -> Axes:
|
|
|
223
224
|
|
|
224
225
|
# --- set the labels
|
|
225
226
|
if saved_pi is not None:
|
|
226
|
-
set_labels(
|
|
227
|
+
set_labels(
|
|
228
|
+
axes,
|
|
229
|
+
saved_pi[1],
|
|
230
|
+
kwargs_d.get("max_ticks", get_setting("max_ticks")),
|
|
231
|
+
tick_relabel=kwargs_d.get("tick_relabel"),
|
|
232
|
+
)
|
|
227
233
|
|
|
228
234
|
return axes
|
mgplot/run_plot.py
CHANGED
|
@@ -208,6 +208,11 @@ def run_plot(data: DataT, **kwargs: Unpack[RunKwargs]) -> Axes:
|
|
|
208
208
|
|
|
209
209
|
# --- set axis labels
|
|
210
210
|
if saved_pi is not None:
|
|
211
|
-
set_labels(
|
|
211
|
+
set_labels(
|
|
212
|
+
axes,
|
|
213
|
+
saved_pi[1],
|
|
214
|
+
kwargs.get("max_ticks", get_setting("max_ticks")),
|
|
215
|
+
tick_relabel=kwargs.get("tick_relabel"),
|
|
216
|
+
)
|
|
212
217
|
|
|
213
218
|
return axes
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: mgplot
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.26
|
|
4
4
|
Summary: mgplot is a time-series/PeriodIndex frontend for matplotlib
|
|
5
5
|
Project-URL: Repository, https://github.com/bpalmer4/mgplot
|
|
6
6
|
Project-URL: Homepage, https://github.com/bpalmer4/mgplot
|
|
@@ -68,8 +68,9 @@ All plot functions take a pandas Series or DataFrame with a PeriodIndex
|
|
|
68
68
|
as the first argument and return a matplotlib Axes object. Keyword
|
|
69
69
|
arguments control styling and behavior:
|
|
70
70
|
|
|
71
|
-
- `bar_plot()` --
|
|
72
|
-
PeriodIndex labeling
|
|
71
|
+
- `bar_plot()` -- bar plot (grouped or stacked) with intelligent
|
|
72
|
+
PeriodIndex labeling; `horizontal=True` plots categorical data as
|
|
73
|
+
horizontal bars (categories on the y-axis, values along the x-axis)
|
|
73
74
|
- `fill_between_plot()` -- shaded region between two bounds (requires
|
|
74
75
|
2-column DataFrame)
|
|
75
76
|
- `growth_plot()` -- plots annual and periodic growth rates (requires
|
|
@@ -85,6 +86,25 @@ arguments control styling and behavior:
|
|
|
85
86
|
- `summary_plot()` -- latest data point against historical range with
|
|
86
87
|
z-score visualization
|
|
87
88
|
|
|
89
|
+
For ranked-category charts (states, industries, expenditure classes),
|
|
90
|
+
use `horizontal=True` with a string-indexed Series or DataFrame:
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
vacancies = vacancies.sort_values() # smallest at the bottom
|
|
94
|
+
mg.bar_plot_finalise(
|
|
95
|
+
vacancies,
|
|
96
|
+
horizontal=True,
|
|
97
|
+
annotate=True, # value labels at the bar ends
|
|
98
|
+
above=True,
|
|
99
|
+
x0=True, # zero line on the value axis
|
|
100
|
+
title="Job vacancies by industry",
|
|
101
|
+
xlabel="'000",
|
|
102
|
+
)
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
`horizontal=True` is for categorical data: with a PeriodIndex it warns
|
|
106
|
+
and falls back to a vertical plot.
|
|
107
|
+
|
|
88
108
|
Finalising Plots
|
|
89
109
|
----------------
|
|
90
110
|
Once a plot is generated, finalise it with titles, labels, and save to file:
|
|
@@ -94,6 +114,74 @@ ax = mg.line_plot(data)
|
|
|
94
114
|
mg.finalise_plot(ax, title="My Chart", ylabel="Units", tag="my_chart")
|
|
95
115
|
```
|
|
96
116
|
|
|
117
|
+
Axis Tick Labels
|
|
118
|
+
----------------
|
|
119
|
+
For PeriodIndex data, x-axis tick labels are generated contextually:
|
|
120
|
+
the tick density is chosen to fit within `max_ticks`, and labels show
|
|
121
|
+
the period with years marked at transitions (e.g. a monthly axis shows
|
|
122
|
+
`Feb Mar ... 2024 ... Feb`, a quarterly axis shows `Q2 Q3 2025 Q2`).
|
|
123
|
+
|
|
124
|
+
Three keyword arguments control the labels on the period-indexed plot
|
|
125
|
+
functions (`line_plot`, `bar_plot`, `growth_plot`, `fill_between_plot`,
|
|
126
|
+
`run_plot`, and their `*_finalise` variants):
|
|
127
|
+
|
|
128
|
+
- `max_ticks` -- the maximum number of ticks (suggestive, not exact).
|
|
129
|
+
The global default is `mg.get_setting("max_ticks")`.
|
|
130
|
+
- `tick_relabel` -- a callable applied to each generated label string,
|
|
131
|
+
after the contextual labelling has run. Use it to restyle labels
|
|
132
|
+
without losing the transition logic.
|
|
133
|
+
- `label_rotation` -- (`bar_plot` only) rotates the x-axis tick labels.
|
|
134
|
+
|
|
135
|
+
For example, to convert 4-digit year labels to 2-digit years:
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
import re
|
|
139
|
+
|
|
140
|
+
def two_digit_years(label: str) -> str:
|
|
141
|
+
"""Shorten 4-digit years to 2 digits (e.g. 2024 -> 24)."""
|
|
142
|
+
return re.sub(r"\b(?:19|20)(\d{2})\b", r"\1", label)
|
|
143
|
+
|
|
144
|
+
# default labels: 2010 2012 2014 ... 2024 2026
|
|
145
|
+
# with tick_relabel: 10 12 14 ... 24 26
|
|
146
|
+
mg.line_plot_finalise(data, title="My Chart", tick_relabel=two_digit_years)
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
Because `tick_relabel` operates on the label strings, this works
|
|
150
|
+
unchanged on quarterly or monthly axes too: a label such as `2024`
|
|
151
|
+
marking a year transition becomes `24`, while the `Q2`/`Mar` labels
|
|
152
|
+
between transitions pass through untouched.
|
|
153
|
+
|
|
154
|
+
These options are stashed on the matplotlib Axes when the plot is drawn,
|
|
155
|
+
and `finalise_plot()` honours them when it refreshes the tick labels
|
|
156
|
+
just before saving. Editing tick labels directly on the Axes (e.g. with
|
|
157
|
+
`set_xticklabels()`) does not survive that refresh -- use `tick_relabel`
|
|
158
|
+
instead.
|
|
159
|
+
|
|
160
|
+
Multi-Panel Figures
|
|
161
|
+
-------------------
|
|
162
|
+
`finalise_plot()` works on a single Axes. For a figure with several
|
|
163
|
+
panels, finalise each panel with `axes_only=True` (axes-level styling
|
|
164
|
+
only: titles, labels, legends), then make the last call a normal
|
|
165
|
+
`finalise_plot()` carrying the figure-level arguments (`suptitle`,
|
|
166
|
+
`lfooter`, `rfooter`, `figsize`, ...), which also saves and closes
|
|
167
|
+
the figure:
|
|
168
|
+
|
|
169
|
+
```python
|
|
170
|
+
fig, (ax_left, ax_right) = plt.subplots(1, 2)
|
|
171
|
+
mg.line_plot(left_data, ax=ax_left)
|
|
172
|
+
mg.line_plot(right_data, ax=ax_right)
|
|
173
|
+
mg.finalise_plot(ax_left, title="Left Panel", ylabel="Index", axes_only=True)
|
|
174
|
+
mg.finalise_plot(
|
|
175
|
+
ax_right,
|
|
176
|
+
title="Right Panel",
|
|
177
|
+
ylabel="Index",
|
|
178
|
+
suptitle="Both Panels Together", # also used for the filename
|
|
179
|
+
lfooter="Australia. Seasonally adjusted.",
|
|
180
|
+
rfooter="Source: ABS",
|
|
181
|
+
figsize=(9, 4.5),
|
|
182
|
+
)
|
|
183
|
+
```
|
|
184
|
+
|
|
97
185
|
Convenience Finalisers
|
|
98
186
|
----------------------
|
|
99
187
|
For every plot function, there is a `*_finalise()` variant that combines
|
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
mgplot/__init__.py,sha256=J3CQX5UXrGXrfs-YWpbzHA_sz1HJ5438xNM0V36x1vo,3164
|
|
2
|
-
mgplot/axis_utils.py,sha256=
|
|
3
|
-
mgplot/bar_plot.py,sha256=
|
|
2
|
+
mgplot/axis_utils.py,sha256=LWKpSRwnxcwQiq83-W4tBCMj8j9SPsfvcWioA0lapdU,15960
|
|
3
|
+
mgplot/bar_plot.py,sha256=FobAsadYSEf-U0RZFgZutTzse4Rgr0TDFyWUMM68JVs,12513
|
|
4
4
|
mgplot/colors.py,sha256=f5q4z7kORUu66uAxNeK9KAZ64gv_7h_x2qH53BvzwPw,4848
|
|
5
|
-
mgplot/fill_between_plot.py,sha256=
|
|
6
|
-
mgplot/finalise_plot.py,sha256=
|
|
5
|
+
mgplot/fill_between_plot.py,sha256=XJvtkBeOkohHyayQnu84jURapB5RsMAR-3SaskHkHfM,3361
|
|
6
|
+
mgplot/finalise_plot.py,sha256=WHk06vOZwMjP0cwA-FXl7sLn10hLZNQLBWqMXPgwF4o,15627
|
|
7
7
|
mgplot/finalisers.py,sha256=Wozq4XOmnMdhEB9LJqHao9TrleOfhNV54kRa_bgN-e8,10547
|
|
8
|
-
mgplot/growth_plot.py,sha256=
|
|
9
|
-
mgplot/keyword_checking.py,sha256=
|
|
10
|
-
mgplot/line_plot.py,sha256=
|
|
8
|
+
mgplot/growth_plot.py,sha256=QALNYyINd_u7BL3q-My16eRuhq0LzGfawu-_MsVOXl0,8708
|
|
9
|
+
mgplot/keyword_checking.py,sha256=8CFexwEK_Uyv3_8hAnJ2ewk0tEjNjkwzKfX2uFw2UpM,11446
|
|
10
|
+
mgplot/line_plot.py,sha256=pQ7ANKRE3m9UcQl1I4QqLaCZQaPjilqfA6X1_tKxNug,7827
|
|
11
11
|
mgplot/lint-all.sh,sha256=O7ns09v0cQNQ6POWtXtYn6VdtYURHTjy06vntR8tr_U,465
|
|
12
12
|
mgplot/multi_plot.py,sha256=8tiUXe1UJGyPvHp3ox2CQ5b-KjdSV9y5avI_70uJFMk,10699
|
|
13
13
|
mgplot/postcovid_plot.py,sha256=TR3BY_1CbIR2IRvlqqbqhhacEyUMDZIEL-mcLs9FV3U,8716
|
|
14
14
|
mgplot/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
|
15
15
|
mgplot/revision_plot.py,sha256=T4CeQBLVUiJI3wu7IMeWxk1XzALaiLIMK71cB6E5kkg,2071
|
|
16
|
-
mgplot/run_plot.py,sha256=
|
|
16
|
+
mgplot/run_plot.py,sha256=tG5YbAZ11WEBw9Jxanpp1W5E-q3sMUd5VjD7yIxrgY8,7355
|
|
17
17
|
mgplot/seastrend_plot.py,sha256=hi9t0cY0bHdIOU5abLMX7qvAp_hlVLlJFyEKNBzg6Ts,2000
|
|
18
18
|
mgplot/settings.py,sha256=co0cElVIdmkfftQrMg4MviyV5TSmvNOzaUN_h_RrjOY,5583
|
|
19
19
|
mgplot/summary_plot.py,sha256=Kg7VD8KFIls4KlD4jeaaXnDw51BZ3p_wMAUpjG49zGQ,11102
|
|
20
20
|
mgplot/utilities.py,sha256=Rouc76vwjL49nVgAzymzoOyX6GrBqp-sjELHalBD_Qo,8445
|
|
21
|
-
mgplot-0.2.
|
|
22
|
-
mgplot-0.2.
|
|
23
|
-
mgplot-0.2.
|
|
24
|
-
mgplot-0.2.
|
|
21
|
+
mgplot-0.2.26.dist-info/METADATA,sha256=yKmPAjfQee0xcWo8P5QZoadTse2gMbJ-_UXK875lDJg,7923
|
|
22
|
+
mgplot-0.2.26.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
|
|
23
|
+
mgplot-0.2.26.dist-info/licenses/LICENSE,sha256=6ZyruOwF8J7mY25-vZHdOibtY8cSNLz0vWeH59TLhtw,1082
|
|
24
|
+
mgplot-0.2.26.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|