mgplot 0.2.35__py3-none-any.whl → 0.3.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.
- mgplot/__init__.py +5 -0
- mgplot/finalisers.py +31 -7
- mgplot/growth_plot.py +3 -2
- mgplot/multi_plot.py +4 -3
- mgplot/postcovid_plot.py +5 -9
- mgplot/scatter_plot.py +205 -0
- mgplot/utilities.py +7 -4
- {mgplot-0.2.35.dist-info → mgplot-0.3.0.dist-info}/METADATA +2 -1
- {mgplot-0.2.35.dist-info → mgplot-0.3.0.dist-info}/RECORD +11 -10
- {mgplot-0.2.35.dist-info → mgplot-0.3.0.dist-info}/WHEEL +0 -0
- {mgplot-0.2.35.dist-info → mgplot-0.3.0.dist-info}/licenses/LICENSE +0 -0
mgplot/__init__.py
CHANGED
|
@@ -30,6 +30,7 @@ from mgplot.finalisers import (
|
|
|
30
30
|
postcovid_plot_finalise,
|
|
31
31
|
revision_plot_finalise,
|
|
32
32
|
run_plot_finalise,
|
|
33
|
+
scatter_plot_finalise,
|
|
33
34
|
seastrend_plot_finalise,
|
|
34
35
|
series_growth_plot_finalise,
|
|
35
36
|
summary_plot_finalise,
|
|
@@ -46,6 +47,7 @@ from mgplot.multi_plot import multi_column, multi_start, plot_then_finalise
|
|
|
46
47
|
from mgplot.postcovid_plot import PostcovidKwargs, postcovid_plot
|
|
47
48
|
from mgplot.revision_plot import revision_plot
|
|
48
49
|
from mgplot.run_plot import RunKwargs, run_plot
|
|
50
|
+
from mgplot.scatter_plot import ScatterKwargs, scatter_plot
|
|
49
51
|
from mgplot.seastrend_plot import seastrend_plot
|
|
50
52
|
from mgplot.settings import (
|
|
51
53
|
chart_subdir,
|
|
@@ -73,6 +75,7 @@ __all__ = (
|
|
|
73
75
|
"LineKwargs",
|
|
74
76
|
"PostcovidKwargs",
|
|
75
77
|
"RunKwargs",
|
|
78
|
+
"ScatterKwargs",
|
|
76
79
|
"SeriesGrowthKwargs",
|
|
77
80
|
"SummaryKwargs",
|
|
78
81
|
"__author__",
|
|
@@ -104,6 +107,8 @@ __all__ = (
|
|
|
104
107
|
"revision_plot_finalise",
|
|
105
108
|
"run_plot",
|
|
106
109
|
"run_plot_finalise",
|
|
110
|
+
"scatter_plot",
|
|
111
|
+
"scatter_plot_finalise",
|
|
107
112
|
"seastrend_plot",
|
|
108
113
|
"seastrend_plot_finalise",
|
|
109
114
|
"series_growth_plot",
|
mgplot/finalisers.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
# mypy: disable-error-code="misc"
|
|
2
1
|
"""Simple convenience functions to finalise and produce plots.
|
|
3
2
|
|
|
4
3
|
Key functions are:
|
|
@@ -8,6 +7,7 @@ Key functions are:
|
|
|
8
7
|
- growth_plot_finalise()
|
|
9
8
|
- revision_plot_finalise()
|
|
10
9
|
- run_plot_finalise()
|
|
10
|
+
- scatter_plot_finalise()
|
|
11
11
|
- seastrend_plot_finalise()
|
|
12
12
|
- series_growth_plot_finalise()
|
|
13
13
|
- summary_plot_finalise()
|
|
@@ -38,6 +38,7 @@ from mgplot.multi_plot import plot_then_finalise
|
|
|
38
38
|
from mgplot.postcovid_plot import PostcovidKwargs, postcovid_plot
|
|
39
39
|
from mgplot.revision_plot import revision_plot
|
|
40
40
|
from mgplot.run_plot import RunKwargs, run_plot
|
|
41
|
+
from mgplot.scatter_plot import ScatterKwargs, scatter_plot
|
|
41
42
|
from mgplot.seastrend_plot import seastrend_plot
|
|
42
43
|
from mgplot.settings import DataT
|
|
43
44
|
from mgplot.summary_plot import SummaryKwargs, summary_plot
|
|
@@ -58,7 +59,7 @@ class FBPFKwargs(FillBetweenKwargs, FinaliseKwargs):
|
|
|
58
59
|
"""Combined kwargs TypedDict for fill_between_plot_finalise()."""
|
|
59
60
|
|
|
60
61
|
|
|
61
|
-
class GrowthPFKwargs(GrowthKwargs, FinaliseKwargs):
|
|
62
|
+
class GrowthPFKwargs(GrowthKwargs, FinaliseKwargs):
|
|
62
63
|
"""Combined kwargs for growth_plot_finalise()."""
|
|
63
64
|
|
|
64
65
|
|
|
@@ -78,6 +79,10 @@ class RunPFKwargs(RunKwargs, FinaliseKwargs):
|
|
|
78
79
|
"""Combined kwargs for run_plot_finalise()."""
|
|
79
80
|
|
|
80
81
|
|
|
82
|
+
class ScatterPFKwargs(ScatterKwargs, FinaliseKwargs):
|
|
83
|
+
"""Combined kwargs for scatter_plot_finalise()."""
|
|
84
|
+
|
|
85
|
+
|
|
81
86
|
class SFKwargs(LineKwargs, FinaliseKwargs):
|
|
82
87
|
"""Combined kwargs TypedDict for seastrend_plot_finalise()."""
|
|
83
88
|
|
|
@@ -86,7 +91,7 @@ class SGFPKwargs(SeriesGrowthKwargs, FinaliseKwargs):
|
|
|
86
91
|
"""Combined kwargs for series_growth_plot_finalise()."""
|
|
87
92
|
|
|
88
93
|
|
|
89
|
-
class SumPFKwargs(SummaryKwargs, FinaliseKwargs):
|
|
94
|
+
class SumPFKwargs(SummaryKwargs, FinaliseKwargs):
|
|
90
95
|
"""Combined kwargs for summary_plot_finalise()."""
|
|
91
96
|
|
|
92
97
|
|
|
@@ -102,6 +107,7 @@ def impose_legend[
|
|
|
102
107
|
| PCFKwargs
|
|
103
108
|
| RevPFKwargs
|
|
104
109
|
| RunPFKwargs
|
|
110
|
+
| ScatterPFKwargs
|
|
105
111
|
| SFKwargs
|
|
106
112
|
| SGFPKwargs
|
|
107
113
|
| SumPFKwargs
|
|
@@ -124,10 +130,8 @@ def impose_legend[
|
|
|
124
130
|
Updated kwargs with legend set appropriately.
|
|
125
131
|
|
|
126
132
|
"""
|
|
127
|
-
if
|
|
128
|
-
kwargs["legend"] =
|
|
129
|
-
else:
|
|
130
|
-
kwargs["legend"] = kwargs.get("legend", False) # type: ignore[typeddict-item,arg-type]
|
|
133
|
+
if "legend" not in kwargs:
|
|
134
|
+
kwargs["legend"] = force or (isinstance(data, DataFrame) and len(data.columns) > 1)
|
|
131
135
|
return kwargs
|
|
132
136
|
|
|
133
137
|
|
|
@@ -255,6 +259,26 @@ def run_plot_finalise(
|
|
|
255
259
|
plot_then_finalise(data=data, function=run_plot, **kwargs)
|
|
256
260
|
|
|
257
261
|
|
|
262
|
+
def scatter_plot_finalise(
|
|
263
|
+
data: DataFrame,
|
|
264
|
+
**kwargs: Unpack[ScatterPFKwargs],
|
|
265
|
+
) -> None:
|
|
266
|
+
"""Call scatter_plot() and finalise_plot().
|
|
267
|
+
|
|
268
|
+
Args:
|
|
269
|
+
data: DataFrame with two numeric columns (x first, y second).
|
|
270
|
+
kwargs: Combined scatter plot and finalise plot keyword arguments.
|
|
271
|
+
|
|
272
|
+
Note:
|
|
273
|
+
The legend is shown by default only when something labelled is drawn.
|
|
274
|
+
|
|
275
|
+
"""
|
|
276
|
+
validate_kwargs(schema=ScatterPFKwargs, caller="scatter_plot_finalise", **kwargs)
|
|
277
|
+
labelled = any(kwargs.get(k) for k in ("label", "report_corr", "diagonal", "highlight_latest"))
|
|
278
|
+
kwargs = impose_legend(kwargs=kwargs, force=labelled)
|
|
279
|
+
plot_then_finalise(data=data, function=scatter_plot, **kwargs)
|
|
280
|
+
|
|
281
|
+
|
|
258
282
|
def seastrend_plot_finalise(
|
|
259
283
|
data: DataT,
|
|
260
284
|
**kwargs: Unpack[SFKwargs],
|
mgplot/growth_plot.py
CHANGED
|
@@ -7,7 +7,7 @@ Key functions:
|
|
|
7
7
|
"""
|
|
8
8
|
|
|
9
9
|
from collections.abc import Callable
|
|
10
|
-
from typing import NotRequired, Unpack
|
|
10
|
+
from typing import NotRequired, Unpack
|
|
11
11
|
|
|
12
12
|
from matplotlib.axes import Axes
|
|
13
13
|
from numpy import nan
|
|
@@ -258,6 +258,7 @@ def series_growth_plot(
|
|
|
258
258
|
print(f"Did you intend to specify a value for the 'ylabel' in {me}()?")
|
|
259
259
|
ylabel = "Growth (%)" if ylabel is None else ylabel
|
|
260
260
|
growth = calc_growth(data)
|
|
261
|
-
|
|
261
|
+
growth_kwargs: GrowthKwargs = kwargs # ylabel removed above
|
|
262
|
+
ax = growth_plot(growth, **growth_kwargs)
|
|
262
263
|
ax.set_ylabel(ylabel)
|
|
263
264
|
return ax
|
mgplot/multi_plot.py
CHANGED
|
@@ -39,7 +39,7 @@ Note: rather than pass the kwargs dict directly, we will re-pack-it
|
|
|
39
39
|
"""
|
|
40
40
|
|
|
41
41
|
from collections.abc import Callable, Iterable
|
|
42
|
-
from typing import Any, Final
|
|
42
|
+
from typing import Any, Final
|
|
43
43
|
|
|
44
44
|
from pandas import DataFrame, Period
|
|
45
45
|
|
|
@@ -62,6 +62,7 @@ from mgplot.line_plot import LineKwargs, line_plot
|
|
|
62
62
|
from mgplot.postcovid_plot import PostcovidKwargs, postcovid_plot
|
|
63
63
|
from mgplot.revision_plot import revision_plot
|
|
64
64
|
from mgplot.run_plot import RunKwargs, run_plot
|
|
65
|
+
from mgplot.scatter_plot import ScatterKwargs, scatter_plot
|
|
65
66
|
from mgplot.seastrend_plot import seastrend_plot
|
|
66
67
|
from mgplot.settings import DataT
|
|
67
68
|
from mgplot.summary_plot import SummaryKwargs, summary_plot
|
|
@@ -75,6 +76,7 @@ EXPECTED_CALLABLES: dict[Callable, type[Any]] = {
|
|
|
75
76
|
postcovid_plot: PostcovidKwargs,
|
|
76
77
|
revision_plot: LineKwargs,
|
|
77
78
|
run_plot: RunKwargs,
|
|
79
|
+
scatter_plot: ScatterKwargs,
|
|
78
80
|
summary_plot: SummaryKwargs,
|
|
79
81
|
series_growth_plot: SeriesGrowthKwargs,
|
|
80
82
|
growth_plot: GrowthKwargs,
|
|
@@ -193,8 +195,7 @@ def plot_then_finalise(
|
|
|
193
195
|
# --- validate the original kwargs (could not do before now)
|
|
194
196
|
kw_types = (
|
|
195
197
|
# combine the expected kwargs types with the finalise kwargs types
|
|
196
|
-
dict(
|
|
197
|
-
| dict(cast("dict[str, Any]", FinaliseKwargs.__annotations__))
|
|
198
|
+
dict(expected.__annotations__) | dict(FinaliseKwargs.__annotations__)
|
|
198
199
|
)
|
|
199
200
|
validate_kwargs(schema=kw_types, caller=me, **kwargs)
|
|
200
201
|
|
mgplot/postcovid_plot.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"""Plot the linear pre-COVID trajectory against the current data."""
|
|
2
2
|
|
|
3
|
-
from typing import Literal, NotRequired, Unpack
|
|
3
|
+
from typing import Literal, NotRequired, Unpack
|
|
4
4
|
|
|
5
5
|
from matplotlib.axes import Axes
|
|
6
6
|
from numpy import array, polyfit
|
|
@@ -149,10 +149,8 @@ def postcovid_plot(data: DataT, **kwargs: Unpack[PostcovidKwargs]) -> Axes:
|
|
|
149
149
|
remove: list[Literal["plot_from", "start_r", "end_r"]] = ["plot_from", "start_r", "end_r"]
|
|
150
150
|
for key in remove:
|
|
151
151
|
kwargs.pop(key, None)
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
**cast("LineKwargs", kwargs),
|
|
155
|
-
)
|
|
152
|
+
line_kwargs: LineKwargs = kwargs # start_r, end_r and plot_from removed above
|
|
153
|
+
return line_plot(data, **line_kwargs)
|
|
156
154
|
|
|
157
155
|
# --- check the kwargs
|
|
158
156
|
report_kwargs(caller=ME, **kwargs)
|
|
@@ -204,10 +202,8 @@ def postcovid_plot(data: DataT, **kwargs: Unpack[PostcovidKwargs]) -> Axes:
|
|
|
204
202
|
kwargs["color"] = kwargs.pop("color", ("darkblue", "#dd0000"))
|
|
205
203
|
kwargs["dropna"] = kwargs.pop("dropna", False) # drop NaN values
|
|
206
204
|
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
**cast("LineKwargs", kwargs),
|
|
210
|
-
)
|
|
205
|
+
line_kwargs: LineKwargs = kwargs # start_r, end_r and plot_from removed above
|
|
206
|
+
return line_plot(combined_data, **line_kwargs)
|
|
211
207
|
|
|
212
208
|
|
|
213
209
|
if __name__ == "__main__":
|
mgplot/scatter_plot.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Plot one numeric column against another as a scatter plot.
|
|
2
|
+
|
|
3
|
+
Unlike the other mgplot plot functions, the index is not plotted. It is only
|
|
4
|
+
used to find the latest observation (for highlight_latest) and, when it is a
|
|
5
|
+
PeriodIndex or an integer index, to apply plot_from.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Any, Final, NotRequired, Unpack
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
from matplotlib.axes import Axes
|
|
12
|
+
from pandas import DataFrame, Period, PeriodIndex, Series
|
|
13
|
+
from pandas.api.types import is_integer_dtype, is_numeric_dtype
|
|
14
|
+
|
|
15
|
+
from mgplot.keyword_checking import BaseKwargs, report_kwargs, validate_kwargs
|
|
16
|
+
from mgplot.settings import get_setting
|
|
17
|
+
from mgplot.utilities import constrain_data, get_axes, get_color_list
|
|
18
|
+
|
|
19
|
+
# --- constants
|
|
20
|
+
ME: Final[str] = "scatter_plot"
|
|
21
|
+
REQUIRED_COLUMNS: Final[int] = 2 # x first, y second
|
|
22
|
+
DEFAULT_SIZE: Final[float] = 12 # marker area (matplotlib s=)
|
|
23
|
+
DEFAULT_ALPHA: Final[float] = 0.6
|
|
24
|
+
DEFAULT_MARKER: Final[str] = "o"
|
|
25
|
+
DEFAULT_POINTS_ZORDER: Final[float] = 1 # matplotlib's default for collections
|
|
26
|
+
LATEST_SIZE_MULTIPLE: Final[float] = 16 # highlighted point area relative to the others
|
|
27
|
+
DIAGONAL_LABEL: Final[str] = "45° (equal)"
|
|
28
|
+
DIAGONAL_COLOR: Final[str] = "darkred"
|
|
29
|
+
CORR_DECIMALS: Final[int] = 2
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ScatterKwargs(BaseKwargs):
|
|
33
|
+
"""Keyword arguments for the scatter_plot function."""
|
|
34
|
+
|
|
35
|
+
ax: NotRequired[Axes | None]
|
|
36
|
+
color: NotRequired[str]
|
|
37
|
+
size: NotRequired[float | int]
|
|
38
|
+
alpha: NotRequired[float]
|
|
39
|
+
marker: NotRequired[str]
|
|
40
|
+
label: NotRequired[str | None]
|
|
41
|
+
zorder: NotRequired[int | float]
|
|
42
|
+
dropna: NotRequired[bool]
|
|
43
|
+
plot_from: NotRequired[int | Period | None]
|
|
44
|
+
diagonal: NotRequired[bool | dict[str, Any]]
|
|
45
|
+
fit: NotRequired[bool | dict[str, Any]]
|
|
46
|
+
highlight_latest: NotRequired[bool | dict[str, Any]]
|
|
47
|
+
report_corr: NotRequired[bool]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
# --- private functions
|
|
51
|
+
def _check_data(data: object) -> DataFrame:
|
|
52
|
+
"""Confirm data is a DataFrame with exactly two numeric columns (x, y)."""
|
|
53
|
+
if not isinstance(data, DataFrame):
|
|
54
|
+
raise TypeError(
|
|
55
|
+
f"{ME}() expects a DataFrame with two numeric columns (x, y), not a {type(data).__name__}."
|
|
56
|
+
)
|
|
57
|
+
if len(data.columns) != REQUIRED_COLUMNS:
|
|
58
|
+
raise ValueError(
|
|
59
|
+
f"{ME}() expects exactly two columns (x first, y second), but got {len(data.columns)}."
|
|
60
|
+
)
|
|
61
|
+
non_numeric = [str(c) for c in data.columns if not is_numeric_dtype(data[c])]
|
|
62
|
+
if non_numeric:
|
|
63
|
+
raise ValueError(f"{ME}() expects numeric columns, but these are not: {', '.join(non_numeric)}.")
|
|
64
|
+
return data
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _constrain(df: DataFrame, kwargs_d: dict[str, Any]) -> tuple[DataFrame, dict[str, Any]]:
|
|
68
|
+
"""Apply plot_from, when provided, to the data."""
|
|
69
|
+
if kwargs_d.get("plot_from") is None:
|
|
70
|
+
kwargs_d.pop("plot_from", None)
|
|
71
|
+
return df, kwargs_d
|
|
72
|
+
if not isinstance(df.index, PeriodIndex) and not is_integer_dtype(df.index):
|
|
73
|
+
print(f"Warning: plot_from ignored in {ME}(); the index is neither a PeriodIndex nor integer.")
|
|
74
|
+
kwargs_d.pop("plot_from", None)
|
|
75
|
+
return df, kwargs_d
|
|
76
|
+
return constrain_data(df, **kwargs_d)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _style(spec: object, house: dict[str, Any]) -> dict[str, Any] | None:
|
|
80
|
+
"""Resolve an overlay spec: True -> house style, dict -> merged over house style, else None."""
|
|
81
|
+
if spec is True:
|
|
82
|
+
return dict(house)
|
|
83
|
+
if isinstance(spec, dict):
|
|
84
|
+
return house | spec
|
|
85
|
+
return None
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _points_label(label: object, x: Series, y: Series, *, report_corr: bool) -> str | None:
|
|
89
|
+
"""Return the legend label for the points, with the correlation appended if requested."""
|
|
90
|
+
text = label if isinstance(label, str) else None
|
|
91
|
+
if not report_corr:
|
|
92
|
+
return text
|
|
93
|
+
r = x.corr(y)
|
|
94
|
+
if not isinstance(r, float) or np.isnan(r):
|
|
95
|
+
print(f"Warning: correlation is undefined in {ME}(), so it has not been reported.")
|
|
96
|
+
return text
|
|
97
|
+
corr = f"r = {r:.{CORR_DECIMALS}f}"
|
|
98
|
+
return corr if text is None else f"{text} ({corr})"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _draw_diagonal(axes: Axes, spec: object) -> None:
|
|
102
|
+
"""Draw the y = x line across the range covering the data on both axes."""
|
|
103
|
+
style = _style(
|
|
104
|
+
spec,
|
|
105
|
+
{"color": DIAGONAL_COLOR, "ls": "--", "lw": get_setting("line_narrow"), "label": DIAGONAL_LABEL},
|
|
106
|
+
)
|
|
107
|
+
if style is None:
|
|
108
|
+
return
|
|
109
|
+
limits = axes.dataLim # covers everything already plotted on these axes
|
|
110
|
+
low = min(limits.x0, limits.y0)
|
|
111
|
+
high = max(limits.x1, limits.y1)
|
|
112
|
+
axes.plot([low, high], [low, high], **style)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _draw_fit(axes: Axes, x: Series, y: Series, spec: object, color: str) -> None:
|
|
116
|
+
"""Draw the OLS line of best fit across the x-range of the points."""
|
|
117
|
+
style = _style(spec, {"color": color, "lw": get_setting("line_normal")})
|
|
118
|
+
if style is None:
|
|
119
|
+
return
|
|
120
|
+
if x.nunique() < REQUIRED_COLUMNS:
|
|
121
|
+
print(f"Warning: a line of best fit needs at least two distinct x values in {ME}().")
|
|
122
|
+
return
|
|
123
|
+
slope, intercept = np.polyfit(x.to_numpy(dtype=float), y.to_numpy(dtype=float), 1)
|
|
124
|
+
ends = np.array([x.min(), x.max()], dtype=float)
|
|
125
|
+
axes.plot(ends, slope * ends + intercept, **style)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _draw_latest(axes: Axes, df: DataFrame, spec: object, points: dict[str, Any]) -> None:
|
|
129
|
+
"""Redraw the point with the latest index value, larger and as a star."""
|
|
130
|
+
position = int(df.index.argmax())
|
|
131
|
+
latest = df.index[position]
|
|
132
|
+
style = _style(
|
|
133
|
+
spec,
|
|
134
|
+
{
|
|
135
|
+
"color": points["color"],
|
|
136
|
+
"s": points["s"] * LATEST_SIZE_MULTIPLE,
|
|
137
|
+
"marker": "*",
|
|
138
|
+
"edgecolors": "black",
|
|
139
|
+
"linewidths": get_setting("line_narrow"),
|
|
140
|
+
"zorder": points["zorder"] + 1,
|
|
141
|
+
"label": f"Latest ({latest})",
|
|
142
|
+
},
|
|
143
|
+
)
|
|
144
|
+
if style is None:
|
|
145
|
+
return
|
|
146
|
+
row = df.iloc[position]
|
|
147
|
+
axes.scatter([row.iloc[0]], [row.iloc[1]], **style)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
# --- public functions
|
|
151
|
+
def scatter_plot(data: DataFrame, **kwargs: Unpack[ScatterKwargs]) -> Axes:
|
|
152
|
+
"""Plot the second column of a DataFrame (y) against the first (x).
|
|
153
|
+
|
|
154
|
+
Args:
|
|
155
|
+
data: DataFrame - exactly two numeric columns, x first and y second.
|
|
156
|
+
The index is not plotted; it identifies the latest point.
|
|
157
|
+
kwargs: ScatterKwargs - keyword arguments for the scatter plot
|
|
158
|
+
|
|
159
|
+
The overlays - diagonal, fit and highlight_latest - each take True for the
|
|
160
|
+
house style, or a dict of matplotlib arguments merged over the house style.
|
|
161
|
+
diagonal - the y = x line (dashed, labelled "45° (equal)")
|
|
162
|
+
fit - an OLS line of best fit, in the colour of the points
|
|
163
|
+
highlight_latest - the point with the latest index value, as a star
|
|
164
|
+
report_corr=True appends the correlation to the label, e.g. "GDP (r = 0.83)".
|
|
165
|
+
|
|
166
|
+
To layer several groups (each with its own colour and fit line), make
|
|
167
|
+
repeated calls with the same ax=, then call finalise_plot().
|
|
168
|
+
|
|
169
|
+
Returns:
|
|
170
|
+
- axes: Axes - the axes object for the plot
|
|
171
|
+
|
|
172
|
+
"""
|
|
173
|
+
# --- check the kwargs
|
|
174
|
+
report_kwargs(caller=ME, **kwargs)
|
|
175
|
+
validate_kwargs(schema=ScatterKwargs, caller=ME, **kwargs)
|
|
176
|
+
|
|
177
|
+
# --- check and prepare the data
|
|
178
|
+
df, kwargs_d = _constrain(_check_data(data), dict(kwargs))
|
|
179
|
+
if kwargs_d.pop("dropna", True):
|
|
180
|
+
df = df.dropna()
|
|
181
|
+
|
|
182
|
+
# --- Let's plot
|
|
183
|
+
axes, kwargs_d = get_axes(**kwargs_d)
|
|
184
|
+
if df.empty or df.isna().all().all():
|
|
185
|
+
# Note: finalise plot should ignore an empty axes object
|
|
186
|
+
print(f"Warning: No data to plot in {ME}().")
|
|
187
|
+
return axes
|
|
188
|
+
|
|
189
|
+
x, y = df.iloc[:, 0], df.iloc[:, 1]
|
|
190
|
+
points: dict[str, Any] = {
|
|
191
|
+
"color": kwargs_d.get("color", get_color_list(1)[0]),
|
|
192
|
+
"s": kwargs_d.get("size", DEFAULT_SIZE),
|
|
193
|
+
"alpha": kwargs_d.get("alpha", DEFAULT_ALPHA),
|
|
194
|
+
"marker": kwargs_d.get("marker", DEFAULT_MARKER),
|
|
195
|
+
"zorder": kwargs_d.get("zorder", DEFAULT_POINTS_ZORDER),
|
|
196
|
+
}
|
|
197
|
+
label = _points_label(kwargs_d.get("label"), x, y, report_corr=bool(kwargs_d.get("report_corr")))
|
|
198
|
+
axes.scatter(x, y, label=label, **points)
|
|
199
|
+
|
|
200
|
+
# --- overlays
|
|
201
|
+
_draw_fit(axes, x, y, kwargs_d.get("fit"), points["color"])
|
|
202
|
+
_draw_latest(axes, df, kwargs_d.get("highlight_latest"), points)
|
|
203
|
+
_draw_diagonal(axes, kwargs_d.get("diagonal")) # last, so its range covers the points
|
|
204
|
+
|
|
205
|
+
return axes
|
mgplot/utilities.py
CHANGED
|
@@ -81,7 +81,10 @@ def check_clean_timeseries(data: DataT, caller: str = "") -> DataT:
|
|
|
81
81
|
if start is None:
|
|
82
82
|
return data # no valid index, return original data
|
|
83
83
|
|
|
84
|
-
|
|
84
|
+
position = data.index.get_loc(start) # an int, as the index is unique
|
|
85
|
+
if not isinstance(position, int):
|
|
86
|
+
raise TypeError(f"Unexpected location {position!r} for the first valid index {start!r}.")
|
|
87
|
+
data = data.iloc[position:]
|
|
85
88
|
missing(data, caller=caller)
|
|
86
89
|
return data
|
|
87
90
|
|
|
@@ -127,7 +130,7 @@ def constrain_data(data: DataT, **kwargs: Any) -> tuple[DataT, dict[str, Any]]:
|
|
|
127
130
|
"Warning: 'plot_from' must be a Period or an integer. "
|
|
128
131
|
f"Found {type(plot_from)}. No data constrained.",
|
|
129
132
|
)
|
|
130
|
-
return data, kwargs
|
|
133
|
+
return data, kwargs
|
|
131
134
|
|
|
132
135
|
|
|
133
136
|
def apply_defaults(
|
|
@@ -194,14 +197,14 @@ def get_axes(**kwargs: Any) -> tuple[Axes, dict[str, Any]]:
|
|
|
194
197
|
"""Get the axes to plot on."""
|
|
195
198
|
axes: Axes | None = kwargs.pop("ax", None)
|
|
196
199
|
if axes and isinstance(axes, Axes):
|
|
197
|
-
return axes, kwargs
|
|
200
|
+
return axes, kwargs
|
|
198
201
|
|
|
199
202
|
if axes is not None:
|
|
200
203
|
raise TypeError(f"ax must be a matplotlib Axes object, not {type(axes)}")
|
|
201
204
|
|
|
202
205
|
figsize = kwargs.get("figsize", get_setting("figsize"))
|
|
203
206
|
_fig, axes = subplots(figsize=figsize)
|
|
204
|
-
return axes, kwargs
|
|
207
|
+
return axes, kwargs
|
|
205
208
|
|
|
206
209
|
|
|
207
210
|
def default_rounding(
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: mgplot
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
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
|
|
@@ -194,6 +194,7 @@ the plot and finalise steps:
|
|
|
194
194
|
- `postcovid_plot_finalise()`
|
|
195
195
|
- `revision_plot_finalise()`
|
|
196
196
|
- `run_plot_finalise()`
|
|
197
|
+
- `scatter_plot_finalise()`
|
|
197
198
|
- `seastrend_plot_finalise()`
|
|
198
199
|
- `series_growth_plot_finalise()`
|
|
199
200
|
- `summary_plot_finalise()`
|
|
@@ -1,25 +1,26 @@
|
|
|
1
|
-
mgplot/__init__.py,sha256=
|
|
1
|
+
mgplot/__init__.py,sha256=9AXauCKo2XlPP-yfDQRnEXr3X9OI2A7kCe0zDcbLRn8,3305
|
|
2
2
|
mgplot/annotation_utils.py,sha256=p0iju88_QGsfzttK3sn53DwF4hD3ZXiCJVkE6RENovw,20972
|
|
3
3
|
mgplot/axis_utils.py,sha256=iJlTDplmc2uaoRHYYMxE3miCTmm6Q_ufg2BFSZce-TI,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
7
|
mgplot/finalise_plot.py,sha256=8NGi2SFAABrP1vjKpHcug8OS6jWWpHErwq1mif6qCCg,24456
|
|
8
|
-
mgplot/finalisers.py,sha256
|
|
9
|
-
mgplot/growth_plot.py,sha256=
|
|
8
|
+
mgplot/finalisers.py,sha256=-3gSpGa4-z4JyhnrKyFyexKmYcY3u9IlHRDgsv4HqL8,11256
|
|
9
|
+
mgplot/growth_plot.py,sha256=ahGvOB2hr981KvgoqeoWb7jRg6Uag91JrD6-aKMojXM,8752
|
|
10
10
|
mgplot/keyword_checking.py,sha256=8CFexwEK_Uyv3_8hAnJ2ewk0tEjNjkwzKfX2uFw2UpM,11446
|
|
11
11
|
mgplot/line_plot.py,sha256=dZC66k-HSbAXIiRJtvcwyJAc_P1084sLPROOFDJ7ew0,10161
|
|
12
12
|
mgplot/lint-all.sh,sha256=O7ns09v0cQNQ6POWtXtYn6VdtYURHTjy06vntR8tr_U,465
|
|
13
|
-
mgplot/multi_plot.py,sha256=
|
|
14
|
-
mgplot/postcovid_plot.py,sha256=
|
|
13
|
+
mgplot/multi_plot.py,sha256=ONEY16Lql3a7iFzLcWSVcSnoLF0RnACsAo7_yQHJINY,10730
|
|
14
|
+
mgplot/postcovid_plot.py,sha256=FIuJnANOoPIwqddS2MP1_8QjReszmjJEcN5zBanafKQ,8792
|
|
15
15
|
mgplot/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
|
16
16
|
mgplot/revision_plot.py,sha256=GC4h-7VKBkA0wdvbzsRtOdexdjJBrqZ6cDtGaq-65LE,2238
|
|
17
17
|
mgplot/run_plot.py,sha256=JYNaUh_ghCa5YFE4q2qiRgXcwI9Z73OZiKbg-9fnK9o,7438
|
|
18
|
+
mgplot/scatter_plot.py,sha256=WVPPof_W1j8sT7hUA1WeTOkCESGK--ulmME6ZSq2jPA,8188
|
|
18
19
|
mgplot/seastrend_plot.py,sha256=hi9t0cY0bHdIOU5abLMX7qvAp_hlVLlJFyEKNBzg6Ts,2000
|
|
19
20
|
mgplot/settings.py,sha256=RhxgX4d-CgRpvs-ALG_j8tg3wwHSyfvFNdL0aMjofA0,5584
|
|
20
21
|
mgplot/summary_plot.py,sha256=Kg7VD8KFIls4KlD4jeaaXnDw51BZ3p_wMAUpjG49zGQ,11102
|
|
21
|
-
mgplot/utilities.py,sha256=
|
|
22
|
-
mgplot-0.
|
|
23
|
-
mgplot-0.
|
|
24
|
-
mgplot-0.
|
|
25
|
-
mgplot-0.
|
|
22
|
+
mgplot/utilities.py,sha256=269tGaEt4sMqPKSr1sUXfBjN7RLvCugLwN6EjTS2uE0,8536
|
|
23
|
+
mgplot-0.3.0.dist-info/METADATA,sha256=1sFO19vgAT1CLxC6nhPoRcNR3k_rsNy-DhhSaosvLKc,7950
|
|
24
|
+
mgplot-0.3.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
25
|
+
mgplot-0.3.0.dist-info/licenses/LICENSE,sha256=6ZyruOwF8J7mY25-vZHdOibtY8cSNLz0vWeH59TLhtw,1082
|
|
26
|
+
mgplot-0.3.0.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|