speechplotlib 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,281 @@
1
+ """Line charts and time series: trend, growth, peaks, seasonality and unusual points."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+ from scipy import stats
10
+
11
+ from .. import speech as sp
12
+ from ..config import config
13
+ from ..result import build
14
+ from ..errors import SpeechKeyError
15
+
16
+ _MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August",
17
+ "September", "October", "November", "December"]
18
+ _DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
19
+
20
+ # frequency name, seasonal lag, word for one step
21
+ _FREQ = {"yearly": (None, "year"), "quarterly": (4, "quarter"), "monthly": (12, "month"),
22
+ "weekly": (52, "week"), "daily": (7, "day"), "hourly": (24, "hour")}
23
+
24
+
25
+ def _frequency(idx: pd.DatetimeIndex) -> str | None:
26
+ """Name the spacing of the dates from the typical gap between them.
27
+
28
+ This works the same on every pandas version (pd.infer_freq changes its return type in
29
+ pandas 4) and also handles gaps such as weekends in business-day data.
30
+ """
31
+ if len(idx) < 3:
32
+ return None
33
+ # Convert to seconds explicitly: pandas may store dates in nanoseconds or microseconds.
34
+ seconds = np.diff(idx.values.astype("datetime64[s]")).astype("int64")
35
+ days = float(np.median(seconds)) / 86400
36
+ for name, lo, hi in (("hourly", 0.03, 0.06), ("daily", 0.9, 1.1), ("weekly", 6.5, 7.5),
37
+ ("monthly", 27, 32), ("quarterly", 88, 93), ("yearly", 360, 370)):
38
+ if lo <= days <= hi:
39
+ return name
40
+ return None
41
+
42
+
43
+ def _when(t, freq: str | None) -> str:
44
+ """A point on the x axis in words."""
45
+ if isinstance(t, pd.Timestamp):
46
+ if freq == "yearly":
47
+ return f"{t.year}"
48
+ if freq == "quarterly":
49
+ return f"quarter {t.quarter} of {t.year}"
50
+ if freq == "monthly":
51
+ return f"{_MONTHS[t.month - 1]} {t.year}"
52
+ if freq == "hourly":
53
+ return f"{t.day} {_MONTHS[t.month - 1]} {t.year}, {t.hour}:{t.minute:02d}"
54
+ return f"{t.day} {_MONTHS[t.month - 1]} {t.year}"
55
+ if isinstance(t, (int, float, np.integer, np.floating)):
56
+ return sp.num(t)
57
+ return str(t)
58
+
59
+
60
+ def _mann_kendall(y: np.ndarray):
61
+ """Trend test: Kendall's tau between time order and value (the Mann-Kendall test), with Sen's slope."""
62
+ n = len(y)
63
+ t = np.arange(n)
64
+ tau, p = stats.kendalltau(t, y)
65
+ if n > 3000: # Sen's slope on an evenly spaced subsample keeps memory small
66
+ keep = np.linspace(0, n - 1, 3000).round().astype(int)
67
+ sen = stats.theilslopes(y[keep], t[keep])[0]
68
+ else:
69
+ sen = stats.theilslopes(y, t)[0]
70
+ return float(tau), float(p), float(sen)
71
+
72
+
73
+ def _maybe_plot(res, plot, kind, **kw):
74
+ if plot:
75
+ from ..plotting import draw
76
+
77
+ res.figure = draw(kind, res.title, **kw)
78
+ return res
79
+
80
+
81
+ def line(data, y=None, x=None, *, name=None, level=None, plot=False):
82
+ """Describe a line chart or time series of one column.
83
+
84
+ ``df.spl.line("sales", x="date")`` uses the date column as the x axis. Without ``x``,
85
+ a DatetimeIndex is used if the DataFrame or Series has one, otherwise the row order.
86
+ """
87
+ if isinstance(data, pd.DataFrame):
88
+ if y is None:
89
+ raise ValueError("Pass the column to follow, for example df.spl.line(\"sales\", x=\"date\").")
90
+ if y not in data.columns:
91
+ raise SpeechKeyError(f"No column named {y!r}.")
92
+ ys = data[y]
93
+ if x is not None:
94
+ if x not in data.columns:
95
+ raise SpeechKeyError(f"No column named {x!r}.")
96
+ xs = data[x]
97
+ x_name = str(x)
98
+ else:
99
+ xs = pd.Series(data.index, index=data.index)
100
+ x_name = str(data.index.name) if data.index.name else "position"
101
+ y_name = name or str(y)
102
+ else:
103
+ ys = data if isinstance(data, pd.Series) else pd.Series(np.asarray(data).ravel())
104
+ xs = pd.Series(ys.index, index=ys.index) if x is None else pd.Series(np.asarray(x), index=ys.index)
105
+ x_name = str(ys.index.name) if x is None and ys.index.name else ("x" if x is not None else "position")
106
+ y_name = name or (str(ys.name) if ys.name is not None else "values")
107
+
108
+ ys = pd.to_numeric(ys, errors="coerce").astype(float)
109
+ # Turn date-like x values into timestamps.
110
+ if not pd.api.types.is_datetime64_any_dtype(xs) and xs.dtype == object:
111
+ parsed = pd.to_datetime(xs, errors="coerce")
112
+ if parsed.notna().mean() > 0.9:
113
+ xs = parsed
114
+ is_time = pd.api.types.is_datetime64_any_dtype(xs)
115
+ frame = pd.DataFrame({"x": xs.to_numpy(), "y": ys.to_numpy()})
116
+ n_total = len(frame)
117
+ frame = frame.dropna()
118
+ n_missing = n_total - len(frame)
119
+ if is_time or pd.api.types.is_numeric_dtype(frame["x"]):
120
+ frame = frame.sort_values("x", kind="mergesort")
121
+ frame = frame.reset_index(drop=True)
122
+ n = len(frame)
123
+ if n < 3:
124
+ return build("line", y_name, {"n": n}, [("brief", f"Line of {y_name}: too few points to describe, {sp.integer(n)}.")], level=level)
125
+
126
+ yv = frame["y"].to_numpy()
127
+ xv = frame["x"]
128
+ freq = _frequency(pd.DatetimeIndex(xv)) if is_time else None
129
+ when = lambda i: _when(xv.iloc[i], freq)
130
+ t = config.thresholds
131
+
132
+ tau, mk_p, sen = _mann_kendall(yv)
133
+ start, end = yv[0], yv[-1]
134
+ change = end - start
135
+ pct_change = change / abs(start) if start != 0 else float("nan")
136
+ if mk_p < t["normality_alpha"]:
137
+ direction = "rising" if tau > 0 else "falling"
138
+ else:
139
+ direction = "no clear"
140
+
141
+ # Growth per year (time) or per step, from first to last value, only for positive values.
142
+ growth = float("nan")
143
+ growth_unit = None
144
+ if start > 0 and end > 0:
145
+ if is_time:
146
+ years = (xv.iloc[-1] - xv.iloc[0]).days / 365.25
147
+ if years >= 1.5:
148
+ growth, growth_unit = (end / start) ** (1 / years) - 1, "a year"
149
+ if growth_unit is None:
150
+ unit = _FREQ[freq][1] if freq else "step"
151
+ growth, growth_unit = (end / start) ** (1 / (n - 1)) - 1, f"per {unit}"
152
+
153
+ # Seasonality: autocorrelation at the seasonal lag after removing a moving-average trend.
154
+ season = {"seasonal": False}
155
+ lag = _FREQ[freq][0] if freq else None
156
+ detrended = None
157
+ if lag and n >= 2 * lag + 2:
158
+ trend = pd.Series(yv).rolling(lag, center=True, min_periods=lag).mean()
159
+ detrended = (pd.Series(yv) - trend).to_numpy()
160
+ ok = ~np.isnan(detrended)
161
+ d = detrended[ok]
162
+ if len(d) > lag + 2 and np.std(d) > 0:
163
+ acf = float(np.corrcoef(d[:-lag], d[lag:])[0, 1])
164
+ season["acf"] = acf
165
+ if acf >= t["seasonality_acf"]:
166
+ pos = pd.DatetimeIndex(xv)[ok]
167
+ if freq == "monthly":
168
+ key, names = pos.month, lambda k: _MONTHS[k - 1]
169
+ elif freq == "daily":
170
+ key, names = pos.day_of_week, lambda k: _DAYS[k]
171
+ elif freq == "quarterly":
172
+ key, names = pos.quarter, lambda k: f"quarter {k}"
173
+ elif freq == "hourly":
174
+ key, names = pos.hour, lambda k: f"{k}:00"
175
+ else:
176
+ key, names = pos.isocalendar().week.to_numpy(), lambda k: f"week {k}"
177
+ profile = pd.Series(d).groupby(np.asarray(key)).mean().sort_values(ascending=False)
178
+ season.update(seasonal=True, high=[names(k) for k in profile.index[:2]],
179
+ low=[names(k) for k in profile.index[-1:]], profile={str(names(k)): float(v) for k, v in profile.items()})
180
+ if detrended is None:
181
+ w = max(3, n // 10)
182
+ trend = pd.Series(yv).rolling(w, center=True, min_periods=1).mean()
183
+ detrended = (pd.Series(yv) - trend).to_numpy()
184
+ d = detrended[~np.isnan(detrended)]
185
+ third = len(d) // 3
186
+ swing = float("nan")
187
+ if third >= 4:
188
+ a, b = np.std(d[:third]), np.std(d[-third:])
189
+ swing = float(b / a) if a > 0 else float("nan")
190
+
191
+ # Biggest single steps.
192
+ steps = np.diff(yv)
193
+ up, down = int(np.argmax(steps)), int(np.argmin(steps))
194
+ # Unusual points: what is left after removing the trend and the seasonal pattern,
195
+ # measured against the local spread, so growing seasonal swings are not flagged.
196
+ rest = pd.Series(detrended)
197
+ if season.get("seasonal"):
198
+ pos_key = {"monthly": pd.DatetimeIndex(xv).month, "daily": pd.DatetimeIndex(xv).day_of_week,
199
+ "quarterly": pd.DatetimeIndex(xv).quarter, "hourly": pd.DatetimeIndex(xv).hour}.get(freq)
200
+ if pos_key is not None:
201
+ keyed = pd.Series(np.asarray(pos_key))
202
+ rest = rest - rest.groupby(keyed).transform("mean")
203
+ w = max(2 * (lag or 0), n // 10, 10)
204
+ centre = rest.rolling(w, center=True, min_periods=5).median()
205
+ mad = (rest - centre).abs().rolling(w, center=True, min_periods=5).median() * 1.4826
206
+ z = ((rest - centre) / mad.replace(0, np.nan)).to_numpy()
207
+ z = np.nan_to_num(z, nan=0.0)
208
+ unusual = np.where(np.abs(z) > t["anomaly_z"])[0]
209
+ hi_i, lo_i = int(np.argmax(yv)), int(np.argmin(yv))
210
+
211
+ span = f"{when(0)} to {when(n - 1)}"
212
+ head = f"{freq.capitalize() + ' ' if freq else ''}{y_name}{' over ' + x_name if not is_time and x_name != 'position' else ''}, {span}, {sp.plural(n, 'point')}"
213
+ if n_missing:
214
+ head += f", {sp.integer(n_missing)} missing"
215
+ L = [("brief", head + ".")]
216
+ move = f"from {sp.num(start)} to {sp.num(end)}"
217
+ if not math.isnan(pct_change) and start > 0:
218
+ move += f", {'up' if change >= 0 else 'down'} {sp.pct(abs(pct_change))}"
219
+ if growth_unit and not math.isnan(growth) and direction != "no clear":
220
+ move += f", about {sp.pct(growth)} {growth_unit} on average"
221
+ if direction == "no clear":
222
+ L.append(("brief", f"No clear trend, Mann-Kendall {sp.pvalue(mk_p)}; it goes {move}."))
223
+ else:
224
+ L.append(("brief", f"{direction.capitalize()} trend, {move}."))
225
+ if season.get("seasonal"):
226
+ period = {"monthly": "Yearly", "daily": "Weekly", "quarterly": "Yearly", "hourly": "Daily", "weekly": "Yearly"}[freq]
227
+ L.append(("brief", f"{period} seasonality: highest in {sp.join(season['high'])}, lowest in {sp.join(season['low'])}."))
228
+ if not math.isnan(swing):
229
+ if swing >= t["volatility_ratio"]:
230
+ L.append(("brief", "Swings grow over time."))
231
+ elif swing <= 1 / t["volatility_ratio"]:
232
+ L.append(("brief", "Swings shrink over time."))
233
+ L.append(("brief", f"Highest {sp.num(yv[hi_i])} in {when(hi_i)}; lowest {sp.num(yv[lo_i])} in {when(lo_i)}."))
234
+ L.append(("standard", f"Largest rise: {sp.num(steps[up])}, from {when(up)} to {when(up + 1)}. "
235
+ f"Largest fall: {sp.num(abs(steps[down]))}, from {when(down)} to {when(down + 1)}."))
236
+ step_word = _FREQ[freq][1] if freq else "step"
237
+ L.append(("standard", f"Typical change {sp.num(sen)} per {step_word}, Sen's slope; Mann-Kendall {sp.pvalue(mk_p)}."))
238
+ if len(unusual):
239
+ named = sp.capped([f"{when(i)} at {sp.num(yv[i])}" for i in unusual], where=".unusual")
240
+ L.append(("standard", f"{sp.plural(len(unusual), 'unusual point')}, far from the local pattern: {named}."))
241
+ if "acf" in season:
242
+ L.append(("full", f"Autocorrelation at a lag of {lag} {step_word}s after removing the trend: {sp.num(season['acf'])}."))
243
+ if not math.isnan(swing):
244
+ L.append(("full", f"Spread of the last third against the first third: {sp.num(swing)} times."))
245
+ L = [(lv, txt) for lv, txt in L if txt]
246
+
247
+ facts = {"n": n, "n_missing": n_missing, "start": float(start), "end": float(end), "change": float(change),
248
+ "pct_change": float(pct_change), "trend": direction, "mann_kendall_tau": tau, "mann_kendall_p": mk_p,
249
+ "sens_slope": sen, "growth": float(growth), "growth_unit": growth_unit, "frequency": freq,
250
+ "highest": float(yv[hi_i]), "highest_at": xv.iloc[hi_i], "lowest": float(yv[lo_i]), "lowest_at": xv.iloc[lo_i],
251
+ "seasonal": season.get("seasonal", False), "seasonal_acf": season.get("acf", float("nan")),
252
+ "swing_ratio": swing, "n_unusual": int(len(unusual))}
253
+ if season.get("seasonal"):
254
+ facts["seasonal_profile"] = season["profile"]
255
+ advice = []
256
+ if direction != "no clear":
257
+ advice.append("The series has a trend: models that assume a steady level, such as plain ARIMA without differencing, need it removed first.")
258
+ if season.get("seasonal"):
259
+ advice.append("Seasonality is strong: use a seasonal model, or add month or weekday as a feature.")
260
+ if not math.isnan(swing) and swing >= t["volatility_ratio"]:
261
+ advice.append("Swings grow with the level: a log transform usually makes them steady.")
262
+ if len(unusual):
263
+ advice.append("Check the unusual points: real events, or data errors.")
264
+ if not is_time and x is None:
265
+ advice.append("No dates were given, so the row order was used. Pass x= with a date column for dates in the description.")
266
+ gloss = {
267
+ "mann-kendall": ("The Mann-Kendall test checks whether values tend to go up or down over time, without assuming a "
268
+ "straight line. p below 0.05 means a trend."),
269
+ "sen's slope": "Sen's slope is the median change per step across all pairs of points; extreme points barely move it.",
270
+ "seasonality": ("Seasonality is a pattern that repeats each year, week or day. It is called seasonal when the "
271
+ f"autocorrelation at the seasonal lag, after removing the trend, is at least {sp.num(t['seasonality_acf'])}."),
272
+ "growth": "Average growth is the steady rate that would take the first value to the last value over the same time.",
273
+ "unusual points": ("A point is unusual when, after removing the trend and any seasonal pattern, it is more than "
274
+ f"{sp.num(t['anomaly_z'])} robust standard deviations from its neighbours, measured with the "
275
+ "local median and median absolute deviation."),
276
+ }
277
+ res = build("line", y_name, facts, L, title=f"Line chart of {y_name}", level=level, glossary=gloss,
278
+ advice=advice or ["Nothing in this series needs fixing."],
279
+ extras={"unusual": frame.iloc[unusual].rename(columns={"x": x_name, "y": y_name}),
280
+ "points": frame.rename(columns={"x": x_name, "y": y_name})})
281
+ return _maybe_plot(res, plot, "line", x=xv.to_numpy(), y=yv, x_name=x_name, y_name=y_name)
@@ -0,0 +1,124 @@
1
+ """Global settings: description level, output behaviour and every threshold.
2
+
3
+ All bands used to turn numbers into words live in ``THRESHOLDS`` so they can be
4
+ read, tested and changed in one place::
5
+
6
+ import speechplotlib as spl
7
+ spl.config.level = "standard"
8
+ spl.config.thresholds["skewness"]["high"] = 1.2
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import copy
14
+ from dataclasses import dataclass, field
15
+
16
+ LEVELS = ("brief", "standard", "full")
17
+
18
+ DEFAULT_THRESHOLDS = {
19
+ # Absolute correlation coefficient, Evans (1996) five-band scale.
20
+ # Read top down: the first band whose lower bound is reached is used.
21
+ "correlation": [
22
+ (0.8, "very strong"),
23
+ (0.6, "strong"),
24
+ (0.4, "moderate"),
25
+ (0.2, "weak"),
26
+ (0.0, "very weak"),
27
+ ],
28
+ # Absolute sample skewness (bias-corrected, as pandas .skew()). Bulmer's convention.
29
+ "skewness": {"moderate": 0.5, "high": 1.0},
30
+ # Excess kurtosis (bias-corrected Fisher, as pandas .kurt()). Rule of thumb.
31
+ "kurtosis": {"light": -1.0, "heavy": 1.0, "very_heavy": 3.0},
32
+ # Tukey fences: multiples of the IQR beyond the quartiles.
33
+ "outlier_iqr": 1.5,
34
+ "extreme_iqr": 3.0,
35
+ # Normality tests.
36
+ "normality_alpha": 0.05,
37
+ "shapiro_max_n": 5000,
38
+ # A density peak counts when its prominence is at least this share of the highest peak.
39
+ "peak_prominence": 0.10,
40
+ # Flat: light tails (excess kurtosis below kurtosis["light"]) and, across the middle
41
+ # half, the density stays at or above this share of its top.
42
+ "flat_ratio": 0.70,
43
+ # Q-Q tails: mean gap between points and line in the outer 5%, in standard deviations.
44
+ "qq_tail_sd": 0.2,
45
+ "qq_tail_share": 0.05,
46
+ # Share of missing values in a column.
47
+ "missing": {"low": 0.05, "high": 0.30},
48
+ # Dataset overview.
49
+ "high_cardinality": 50,
50
+ "id_unique_ratio": 0.9,
51
+ "near_constant_share": 0.95,
52
+ "max_target_classes": 20,
53
+ # Class balance: share of the smallest class.
54
+ "imbalance": 0.20,
55
+ "severe_imbalance": 0.05,
56
+ # Below this many values the shape is called uncertain.
57
+ "small_sample": 30,
58
+ # ----- relationships -----
59
+ # Pearson and Spearman further apart than this: say the relationship is not simply linear.
60
+ "correlation_gap": 0.2,
61
+ # Two predictors this correlated or more are flagged as multicollinear.
62
+ "multicollinearity": 0.9,
63
+ # A quadratic term that adds at least this much R-squared counts as a curve.
64
+ "curve_r2_gain": 0.05,
65
+ # Points whose residual is beyond this many standard deviations stand apart.
66
+ "residual_z": 3.0,
67
+ # Regression R-squared: below moderate is weak, at or above strong is strong. Rule of thumb.
68
+ "r2": {"moderate": 0.3, "strong": 0.7},
69
+ # ----- categories -----
70
+ # The top category is dominant at this share or more.
71
+ "dominant_share": 0.5,
72
+ # Slices or bars below this share are grouped as small.
73
+ "small_share": 0.02,
74
+ # ----- trends -----
75
+ # Autocorrelation at the seasonal lag needed to call a series seasonal.
76
+ "seasonality_acf": 0.5,
77
+ # Spread of the last third against the first third: at least this ratio means swings grow.
78
+ "volatility_ratio": 1.5,
79
+ # Robust z-score (median and MAD) beyond which a point is called unusual.
80
+ "anomaly_z": 3.5,
81
+ # ----- models -----
82
+ # ROC AUC bands, Hosmer and Lemeshow. Read top down.
83
+ "auc": [(0.9, "outstanding"), (0.8, "excellent"), (0.7, "acceptable"), (0.5, "weak"), (0.0, "worse than chance")],
84
+ # Residual mean smaller than this share of the residual spread counts as centred on zero.
85
+ "residual_bias": 0.1,
86
+ # Feature importance: the features that make up this share of the total are named.
87
+ "importance_cumulative": 0.8,
88
+ # Features below this share of the total importance are near zero.
89
+ "importance_near_zero": 0.01,
90
+ # PCA: report how many components reach each of these shares of variance.
91
+ "pca_targets": [0.8, 0.9, 0.95],
92
+ }
93
+
94
+
95
+ @dataclass
96
+ class Config:
97
+ """Settings for the session. Change attributes directly on ``spl.config``."""
98
+
99
+ #: Default description level: "brief", "standard" or "full".
100
+ level: str = "brief"
101
+ #: Print the description as soon as a result is made.
102
+ #: "auto" prints in scripts and Jupyter, and leaves the plain Python prompt to show it.
103
+ autoprint: str | bool = "auto"
104
+ #: Significant figures for numbers in descriptions.
105
+ sig_figs: int = 3
106
+ #: Most items named in one sentence before "and N more".
107
+ max_items: int = 3
108
+ #: Add a one-line tip to the first result of the session.
109
+ hints: bool = True
110
+ thresholds: dict = field(default_factory=lambda: copy.deepcopy(DEFAULT_THRESHOLDS))
111
+
112
+ def reset(self) -> None:
113
+ """Restore every setting to its default."""
114
+ fresh = Config()
115
+ self.__dict__.update(fresh.__dict__)
116
+
117
+ def check_level(self, level: str | None) -> str:
118
+ level = level or self.level
119
+ if level not in LEVELS:
120
+ raise ValueError(f"level must be one of {', '.join(LEVELS)}; got {level!r}")
121
+ return level
122
+
123
+
124
+ config = Config()
@@ -0,0 +1,8 @@
1
+ """Exceptions with messages that read cleanly aloud."""
2
+
3
+
4
+ class SpeechKeyError(KeyError):
5
+ """A KeyError whose message prints without the quote marks Python's KeyError adds."""
6
+
7
+ def __str__(self) -> str:
8
+ return str(self.args[0]) if self.args else ""
@@ -0,0 +1,102 @@
1
+ """Optional drawings for sighted colleagues, made with ``plot=True``.
2
+
3
+ Matplotlib is imported only when a drawing is asked for. The figure is stored
4
+ on the result as ``result.figure``; nothing here changes the description.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import numpy as np
10
+
11
+
12
+ def _plt():
13
+ try:
14
+ import matplotlib.pyplot as plt
15
+ except ImportError as exc: # pragma: no cover
16
+ raise ImportError("plot=True needs matplotlib: pip install speechplotlib[plot]") from exc
17
+ return plt
18
+
19
+
20
+ def draw(kind: str, title: str, **kw):
21
+ plt = _plt()
22
+ fig, ax = plt.subplots(figsize=(7, 4))
23
+ if kind == "hist":
24
+ ax.hist(kw["x"], bins=kw["edges"])
25
+ elif kind == "kde":
26
+ ax.plot(kw["grid"], kw["density"])
27
+ elif kind == "box":
28
+ groups = kw.get("groups")
29
+ if groups:
30
+ # Tick labels are set separately: boxplot's labels argument was renamed in
31
+ # Matplotlib 3.9 and removed later, so this form works on every version.
32
+ ax.boxplot([g for _, g in groups])
33
+ ax.set_xticks(range(1, len(groups) + 1), [str(k) for k, _ in groups])
34
+ else:
35
+ ax.boxplot(kw["x"])
36
+ elif kind == "violin":
37
+ groups = kw.get("groups")
38
+ data = [g for _, g in groups] if groups else [kw["x"]]
39
+ ax.violinplot(data, showmedians=True)
40
+ if groups:
41
+ ax.set_xticks(range(1, len(groups) + 1), [str(k) for k, _ in groups])
42
+ elif kind == "qq":
43
+ ax.scatter(kw["osm"], kw["osr"], s=8)
44
+ ax.plot(kw["osm"], kw["slope"] * kw["osm"] + kw["intercept"])
45
+ ax.set_xlabel("Normal quantiles")
46
+ elif kind == "ecdf":
47
+ ax.ecdf(kw["x"])
48
+ elif kind in ("scatter", "regression"):
49
+ ax.scatter(kw["x"], kw["y"], s=8, alpha=0.6)
50
+ if kind == "regression":
51
+ xs = np.linspace(np.min(kw["x"]), np.max(kw["x"]), 100)
52
+ ax.plot(xs, kw["intercept"] + kw["slope"] * xs)
53
+ ax.set_xlabel(kw["x_name"])
54
+ ax.set_ylabel(kw["y_name"])
55
+ elif kind == "corr":
56
+ m = kw["matrix"]
57
+ im = ax.imshow(m.to_numpy(), vmin=-1, vmax=1, cmap="RdBu_r")
58
+ ax.set_xticks(range(len(m.columns)), m.columns, rotation=90)
59
+ ax.set_yticks(range(len(m.index)), m.index)
60
+ if len(m) <= 12:
61
+ for i in range(len(m)):
62
+ for j in range(len(m)):
63
+ ax.text(j, i, f"{m.iloc[i, j]:.2f}", ha="center", va="center", fontsize=7)
64
+ fig.colorbar(im, ax=ax)
65
+ elif kind == "bar":
66
+ ax.bar(kw["labels"], kw["heights"])
67
+ ax.tick_params(axis="x", rotation=45)
68
+ elif kind == "pie":
69
+ ax.pie(kw["sizes"], labels=kw["labels"], autopct="%1.1f%%")
70
+ elif kind == "line":
71
+ ax.plot(kw["x"], kw["y"])
72
+ ax.set_xlabel(kw["x_name"])
73
+ ax.set_ylabel(kw["y_name"])
74
+ elif kind == "elbow":
75
+ ax.plot(kw["k"], kw["inertia"], marker="o")
76
+ if kw.get("knee") is not None:
77
+ ax.axvline(kw["k"][kw["knee"]], linestyle="--")
78
+ ax.set_xlabel("k")
79
+ ax.set_ylabel("inertia")
80
+ elif kind == "pca":
81
+ idx = np.arange(1, len(kw["ratios"]) + 1)
82
+ ax.bar(idx, kw["ratios"])
83
+ ax.plot(idx, kw["cum"], marker="o")
84
+ ax.set_xlabel("component")
85
+ ax.set_ylabel("share of variance")
86
+ elif kind == "importance":
87
+ ax.barh(kw["names"][::-1], kw["values"][::-1])
88
+ elif kind == "roc":
89
+ ax.plot(kw["fpr"], kw["tpr"], label=f"AUC {kw['auc']:.3f}")
90
+ ax.plot([0, 1], [0, 1], linestyle="--")
91
+ ax.scatter([kw["fpr"][kw["best"]]], [kw["tpr"][kw["best"]]])
92
+ ax.set_xlabel("false positive rate")
93
+ ax.set_ylabel("true positive rate")
94
+ ax.legend()
95
+ elif kind == "residuals":
96
+ ax.scatter(kw["pred"], kw["resid"], s=8, alpha=0.6)
97
+ ax.axhline(0, linestyle="--")
98
+ ax.set_xlabel("predicted")
99
+ ax.set_ylabel("residual")
100
+ ax.set_title(title)
101
+ fig.tight_layout()
102
+ return fig