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,211 @@
1
+ """Category charts: bar chart (counts or values per category) and pie chart."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+
8
+ from .. import speech as sp
9
+ from ..config import config
10
+ from ..result import build
11
+ from ..errors import SpeechKeyError
12
+
13
+ _AGG_WORDS = {"sum": "Sum", "mean": "Mean", "median": "Median", "count": "Count", "max": "Maximum", "min": "Minimum"}
14
+
15
+
16
+ def category_values(data, column=None, values=None, agg="sum"):
17
+ """Return (Series of value per category, label, mode, n_missing).
18
+
19
+ * DataFrame and column: counts of each category.
20
+ * DataFrame, column and values: ``agg`` of the values column per category.
21
+ * Series of numbers with category labels as its index, or a dict: used as they are.
22
+ * Any other Series, list or array: counts.
23
+ """
24
+ if isinstance(data, dict):
25
+ s = pd.Series(data, dtype=float)
26
+ return s, "values", "given", 0
27
+ if isinstance(data, pd.DataFrame):
28
+ if column is None:
29
+ raise ValueError("Pass the category column, for example df.spl.bar(\"city\").")
30
+ if column not in data.columns:
31
+ raise SpeechKeyError(f"No column named {column!r}.")
32
+ cats = data[column]
33
+ n_missing = int(cats.isna().sum())
34
+ if values is None:
35
+ return cats.value_counts(dropna=True), str(column), "counts", n_missing
36
+ if values not in data.columns:
37
+ raise SpeechKeyError(f"No column named {values!r}.")
38
+ if agg not in _AGG_WORDS:
39
+ raise ValueError(f"agg must be one of {', '.join(_AGG_WORDS)}.")
40
+ s = data.groupby(column, observed=True, dropna=True)[values].agg(agg)
41
+ return s, f"{values} by {column}", agg, n_missing
42
+ s = data if isinstance(data, pd.Series) else pd.Series(np.asarray(data).ravel())
43
+ if (pd.api.types.is_numeric_dtype(s) and not pd.api.types.is_bool_dtype(s)
44
+ and not isinstance(s.index, pd.RangeIndex)):
45
+ return s.dropna(), str(s.name) if s.name is not None else "values", "given", int(s.isna().sum())
46
+ name = str(s.name) if s.name is not None else "values"
47
+ return s.value_counts(dropna=True), name, "counts", int(s.isna().sum())
48
+
49
+
50
+ def _maybe_plot(res, plot, kind, **kw):
51
+ if plot:
52
+ from ..plotting import draw
53
+
54
+ res.figure = draw(kind, res.title, **kw)
55
+ return res
56
+
57
+
58
+ def _labeller(s: pd.Series, column):
59
+ """Number-like category labels read badly next to values ("2 20.7"), so prefix the column name."""
60
+ numeric = all(isinstance(k, (int, float, np.integer, np.floating)) and not isinstance(k, bool) for k in s.index)
61
+ if numeric and column is not None:
62
+ return s.rename(index=lambda k: f"{column} {k}")
63
+ return s
64
+
65
+
66
+ def _item(k, v, share=None) -> str:
67
+ text = f"{k} {sp.num(v) if not float(v).is_integer() else sp.integer(v)}"
68
+ if share is not None:
69
+ text += f", {sp.pct(share)}"
70
+ return text
71
+
72
+
73
+ def bar(data, column=None, *, values=None, agg="sum", level=None, plot=False):
74
+ """Describe a bar chart.
75
+
76
+ ``df.spl.bar("city")`` counts rows per city. ``df.spl.bar("city", values="sales")`` sums
77
+ sales per city; ``agg="mean"`` averages instead. A Series with category labels as its
78
+ index, or a dict, is described as given.
79
+ """
80
+ s, label, mode, n_missing = category_values(data, column, values, agg)
81
+ s = _labeller(s.astype(float).sort_values(ascending=False, kind="mergesort"), column)
82
+ n = len(s)
83
+ if n == 0:
84
+ return build("bar", label, {"n_categories": 0}, [("brief", f"No categories to describe in {label}.")], level=level)
85
+ non_negative = bool((s >= 0).all())
86
+ total = float(s.sum())
87
+ # Shares of a total only make sense when the values add up: counts and sums.
88
+ additive = mode in ("counts", "sum", "count", "given")
89
+ shares = (s / total) if additive and non_negative and total > 0 else None
90
+ what = "Counts of" if mode == "counts" else (f"{_AGG_WORDS[mode]} of" if mode in _AGG_WORDS else "Bar chart of")
91
+ missing = f", {sp.integer(n_missing)} missing" if n_missing else ""
92
+ L = [("brief", f"{what} {label}, {sp.plural(n, 'category', 'categories')}{missing}.")]
93
+ k0, v0 = s.index[0], s.iloc[0]
94
+ tied = list(s.index[s == v0])
95
+ sh = (lambda k: shares[k]) if shares is not None else (lambda k: None)
96
+ if len(tied) > 1:
97
+ L.append(("brief", f"{sp.join([str(t) for t in tied])} tie for the lead at {_item('', v0).strip()}."))
98
+ else:
99
+ L.append(("brief", f"{k0} leads with {_item('', v0, sh(k0)).strip()}."))
100
+ rest = [(k, v) for k, v in s.iloc[1:].items() if k not in tied]
101
+ if rest:
102
+ shown = rest[: config.max_items - 1]
103
+ listed = sp.join([_item(k, v, sh(k)) for k, v in shown])
104
+ tail = ""
105
+ if len(rest) > len(shown):
106
+ kl, vl = s.index[-1], s.iloc[-1]
107
+ tail = f"; {sp.integer(len(rest) - len(shown))} more, smallest {_item(kl, vl, sh(kl))}"
108
+ L.append(("brief", f"Then {listed}{tail}."))
109
+ if len(tied) == 1 and n > 1:
110
+ k1, v1 = s.index[1], s.iloc[1]
111
+ gap = v0 - v1
112
+ text = f"{k0} is {sp.num(gap)} ahead of {k1}, the next category"
113
+ if v1 > 0:
114
+ text += f", {sp.num(v0 / v1)} times as large"
115
+ L.append(("brief", text + "."))
116
+ if shares is not None and shares.iloc[0] >= config.thresholds["dominant_share"] and len(tied) == 1:
117
+ L.append(("brief", f"{k0} is dominant, {sp.pct(shares.iloc[0])} of the total."))
118
+ if shares is not None and n > 3:
119
+ L.append(("standard", f"Top 3 together make {sp.pct(shares.iloc[:3].sum())}."))
120
+ small = shares[shares < config.thresholds["small_share"]] if shares is not None else pd.Series(dtype=float)
121
+ if len(small):
122
+ L.append(("standard", f"{sp.plural(len(small), 'category', 'categories')} under {sp.pct(config.thresholds['small_share'])} each, "
123
+ f"together {sp.pct(small.sum())}: {sp.capped([str(k) for k in small.index], where='.table')}."))
124
+ if n > config.max_items:
125
+ listed = "; ".join(_item(k, v, sh(k)) for k, v in s.head(12).items())
126
+ L.append(("standard", f"Full order: {listed}" + ("." if n <= 12 else f"; and {n - 12} more, see .table.")))
127
+ if n > 1:
128
+ L.append(("standard", f"Average per category {sp.num(s.mean())}, median {sp.num(s.median())}."))
129
+ if not non_negative and additive:
130
+ L.append(("standard", "Some values are negative, so shares of the total are not given."))
131
+ if n > 12:
132
+ L.append(("full", "All categories: " + "; ".join(_item(k, v, sh(k)) for k, v in s.items()) + "."))
133
+ if n > config.thresholds["high_cardinality"]:
134
+ L.insert(1, ("brief", f"Many categories, {sp.integer(n)}: a histogram may suit this column better if it is numeric."))
135
+ L = [(lv, t) for lv, t in L if t]
136
+ facts = {"n_categories": n, "n_missing": n_missing, "total": total, "mode": mode,
137
+ "leader": tied[0] if len(tied) == 1 else tied, "leader_value": float(v0),
138
+ "categories": [str(k) for k in s.index], "values_by_category": {str(k): float(v) for k, v in s.items()}}
139
+ if shares is not None:
140
+ facts["shares"] = {str(k): float(v) for k, v in shares.items()}
141
+ if n > 1:
142
+ facts["gap_to_second"] = float(v0 - s.iloc[1])
143
+ advice = []
144
+ if n > config.thresholds["high_cardinality"]:
145
+ advice.append("With this many categories, group the rare ones into an Other category before modelling.")
146
+ if len(small):
147
+ advice.append(f"{sp.plural(len(small), 'small category', 'small categories')}: consider merging them into Other.")
148
+ if mode == "counts" and shares is not None and shares.iloc[-1] < config.thresholds["imbalance"] and n <= config.thresholds["max_target_classes"]:
149
+ advice.append("If this is the target, the classes are uneven: use a stratified split and look beyond accuracy.")
150
+ gloss = {"share": "A category's share is its value divided by the total of all categories.",
151
+ "dominant": f"A category is called dominant at {sp.pct(config.thresholds['dominant_share'])} of the total or more."}
152
+ res = build("bar", label, facts, L, title=f"Bar chart of {label}", level=level, glossary=gloss,
153
+ advice=advice or ["Nothing here needs fixing."], extras={"table": s})
154
+ return _maybe_plot(res, plot, "bar", labels=[str(k) for k in s.index], heights=s.to_numpy())
155
+
156
+
157
+ def pie(data, column=None, *, values=None, agg="sum", level=None, plot=False):
158
+ """Describe a pie chart: each category's share of the whole."""
159
+ s, label, mode, n_missing = category_values(data, column, values, agg)
160
+ s = _labeller(s.astype(float).sort_values(ascending=False, kind="mergesort"), column)
161
+ if mode in ("mean", "median", "max", "min"):
162
+ raise ValueError(f"A pie chart shows parts of a whole, and a {mode} per category does not add up to a whole. "
163
+ "Use agg='sum', or a bar chart.")
164
+ if (s < 0).any():
165
+ raise ValueError("A pie chart needs values of zero or more; use bar for negative values.")
166
+ total = float(s.sum())
167
+ n = len(s)
168
+ if n == 0 or total == 0:
169
+ return build("pie", label, {"n_slices": n}, [("brief", f"No values to share out in {label}.")], level=level)
170
+ shares = s / total
171
+ missing = f", {sp.integer(n_missing)} missing" if n_missing else ""
172
+ L = [("brief", f"Share of {label}, {sp.plural(n, 'slice')}{missing}.")]
173
+ # Name up to max_items slices; if only one is left over, name it too.
174
+ limit = config.max_items + 1 if n == config.max_items + 1 else config.max_items
175
+ shown = list(shares.items())[:limit]
176
+ listed = sp.join([f"{k} at {sp.pct(v)}" for k, v in shown])
177
+ if n > len(shown):
178
+ others = shares.iloc[len(shown):]
179
+ listed += f"; the other {sp.integer(len(others))} together make {sp.pct(others.sum())}"
180
+ L.append(("brief", listed + "."))
181
+ top_k, top_v = shares.index[0], shares.iloc[0]
182
+ if top_v > 0.5:
183
+ L.append(("brief", f"{top_k} is more than half."))
184
+ elif top_v == 0.5:
185
+ L.append(("brief", f"{top_k} is exactly half."))
186
+ # The two smallest together, as the original post asked; skipped when the sentence above
187
+ # already gave exactly those two as "the other 2".
188
+ if n >= 4 and n - len(shown) != 2:
189
+ two = shares.iloc[-2:]
190
+ L.append(("brief", f"The two smallest, {two.index[0]} and {two.index[1]}, together make {sp.pct(two.sum())}."))
191
+ if n >= 2 and shares.iloc[-1] > 0 and top_v / shares.iloc[-1] <= 1.5:
192
+ L.append(("brief", f"Slices are fairly even: largest {sp.pct(top_v)}, smallest {sp.pct(shares.iloc[-1])}."))
193
+ small = shares[shares < config.thresholds["small_share"]]
194
+ if len(small):
195
+ L.append(("standard", f"{sp.plural(len(small), 'slice')} under {sp.pct(config.thresholds['small_share'])} each, together "
196
+ f"{sp.pct(small.sum())}: {sp.capped([str(k) for k in small.index], where='.table')}."))
197
+ if n > config.max_items:
198
+ L.append(("standard", "All slices: " + "; ".join(f"{k} {sp.pct(v)}" for k, v in shares.head(12).items())
199
+ + ("." if n <= 12 else f"; and {n - 12} more, see .table.")))
200
+ L.append(("full", f"Total {sp.num(total)}."))
201
+ facts = {"n_slices": n, "n_missing": n_missing, "total": total, "largest": str(top_k),
202
+ "largest_share": float(top_v), "shares": {str(k): float(v) for k, v in shares.items()}}
203
+ advice = []
204
+ if n > 6:
205
+ advice.append("Pie charts get hard to read past about 6 slices, for anyone; a sorted bar chart says the same thing more clearly.")
206
+ if len(small):
207
+ advice.append("Merge the small slices into Other.")
208
+ res = build("pie", label, facts, L, title=f"Pie chart of {label}", level=level,
209
+ glossary={"share": "Each slice's share is its value divided by the total. All shares add to 100%."},
210
+ advice=advice or ["Nothing here needs fixing."], extras={"table": shares})
211
+ return _maybe_plot(res, plot, "pie", labels=[str(k) for k in s.index], sizes=s.to_numpy())
@@ -0,0 +1,409 @@
1
+ """Distribution charts: histogram, density, box, violin, Q-Q and cumulative distribution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+ from scipy import stats
8
+
9
+ from .. import rules
10
+ from .. import speech as sp
11
+ from ..config import config
12
+ from ..result import build
13
+ from . import _input, _stats, _text
14
+
15
+
16
+ def _clean_facts(d: dict) -> dict:
17
+ return {k: v for k, v in d.items() if not k.startswith("_") and k not in ("grid", "density")}
18
+
19
+
20
+ def _outlier_rows(inp: _input.NumericInput, s: dict):
21
+ mask = _stats.outlier_mask(inp.values, s)
22
+ idx = inp.series.index[mask]
23
+ if inp.frame is not None:
24
+ rows = inp.frame.loc[idx]
25
+ return rows.reindex(inp.series[mask].sort_values(ascending=False).index)
26
+ return inp.series[mask].sort_values(ascending=False)
27
+
28
+
29
+ def _maybe_plot(res, plot, kind, **kw):
30
+ if plot:
31
+ from ..plotting import draw
32
+
33
+ res.figure = draw(kind, res.title, **kw)
34
+ return res
35
+
36
+
37
+ def _common(inp: _input.NumericInput):
38
+ s = _stats.summary(inp.values)
39
+ pk = _stats.density_peaks(inp.values)
40
+ nt = _stats.normality(inp.values)
41
+ return s, pk, nt
42
+
43
+
44
+ def _empty(kind, inp, level):
45
+ lines = [("brief", f"No numeric values in {inp.name}: {inp.missing_phrase()}.")]
46
+ return build(kind, inp.name, {"n": 0, "n_missing": inp.n_missing}, lines, level=level)
47
+
48
+
49
+ # ----- histogram ---------------------------------------------------------------
50
+
51
+ def hist(data, column=None, *, bins="auto", name=None, level=None, plot=False):
52
+ """Describe the histogram of one numeric column.
53
+
54
+ ``data`` can be a DataFrame with ``column``, a Series, a list or an array.
55
+ """
56
+ inp = _input.numeric(data, column, name)
57
+ if inp.n == 0:
58
+ return _empty("hist", inp, level)
59
+ x = inp.values
60
+ s, pk, nt = _common(inp)
61
+ edges = np.histogram_bin_edges(x, bins=bins)
62
+ if isinstance(bins, str) and len(edges) > 51:
63
+ edges = np.histogram_bin_edges(x, bins=50)
64
+ counts, edges = np.histogram(x, bins=edges)
65
+ top = int(np.argmax(counts))
66
+ bin_list = [(float(edges[i]), float(edges[i + 1]), int(counts[i])) for i in range(len(counts))]
67
+
68
+ L = []
69
+ L.append(("brief", f"Histogram of {inp.name}, {sp.plural(inp.n, 'value')}, {inp.missing_phrase()}."))
70
+ if s["constant"]:
71
+ L.append(("brief", _text.shape_sentence(s)))
72
+ else:
73
+ small = _text.small_sample_sentence(inp.n)
74
+ if small:
75
+ L.append(("brief", small))
76
+ L.append(("brief", _text.shape_sentence(s, pk["peaks"])))
77
+ L.append(("brief", f"Median {sp.num(s['median'])}, mean {sp.num(s['mean'])}."))
78
+ L.append(("brief", f"Middle half lies between {sp.num(s['q1'])} and {sp.num(s['q3'])}."))
79
+ L.append(("brief", _text.outlier_sentence(s, x[_stats.outlier_mask(x, s)])))
80
+ L.append(("standard", f"Range {sp.range_text(s['min'], s['max'])}, standard deviation {sp.num(s['std'])}."))
81
+ L.append(("standard", _text.peaks_sentence(pk["peaks"], pk["flat"])))
82
+ L.append(("standard", _text.tails_sentence(s)))
83
+ width = edges[1] - edges[0]
84
+ L.append((
85
+ "standard",
86
+ f"{sp.plural(len(counts), 'bin')} of width {sp.num(width)}. Tallest bin, {sp.range_text(edges[top], edges[top + 1])}, "
87
+ f"holds {sp.plural(int(counts[top]), 'value')}, {sp.pct(counts[top] / inp.n)}.",
88
+ ))
89
+ if s["n_extreme"]:
90
+ L.append(("standard", f"{sp.integer(s['n_extreme'])} of the outliers are extreme, beyond {sp.num(config.thresholds['extreme_iqr'])} IQR."))
91
+ L.append(("full", f"90% of values lie between {sp.num(s['p5'])} and {sp.num(s['p95'])}."))
92
+ L.append(("full", _text.normality_sentence(nt, inp.n)))
93
+ if len(bin_list) <= 30:
94
+ listed = "; ".join(f"{sp.range_text(a, b)}: {sp.integer(c)}" for a, b, c in bin_list)
95
+ L.append(("full", f"Bin counts: {listed}."))
96
+ L = [(lv, t) for lv, t in L if t]
97
+
98
+ facts = {**s, **nt, "peaks": pk["peaks"], "n_peaks": len(pk["peaks"]), "flat": pk["flat"], "n_missing": inp.n_missing,
99
+ "n_total": inp.n_total, "n_bins": len(counts), "bin_width": float(edges[1] - edges[0])}
100
+ res = build(
101
+ "hist", inp.name, facts, L, title=f"Histogram of {inp.name}", level=level,
102
+ glossary=_text.glossary(s),
103
+ advice=_text.numeric_advice(x, s, inp.n_missing, inp.n_total, pk["peaks"]),
104
+ extras={"bins": bin_list, "outliers": _outlier_rows(inp, s)},
105
+ )
106
+ return _maybe_plot(res, plot, "hist", x=x, edges=edges)
107
+
108
+
109
+ # ----- density -----------------------------------------------------------------
110
+
111
+ def kde(data, column=None, *, name=None, level=None, plot=False):
112
+ """Describe the density curve (kernel density estimate) of one numeric column."""
113
+ inp = _input.numeric(data, column, name)
114
+ if inp.n == 0:
115
+ return _empty("kde", inp, level)
116
+ x = inp.values
117
+ s, pk, nt = _common(inp)
118
+ L = [("brief", f"Density of {inp.name}, {sp.plural(inp.n, 'value')}, {inp.missing_phrase()}.")]
119
+ if s["constant"]:
120
+ L.append(("brief", _text.shape_sentence(s)))
121
+ else:
122
+ L.append(("brief", _text.small_sample_sentence(inp.n)))
123
+ L.append(("brief", _text.peaks_sentence(pk["peaks"], pk["flat"])))
124
+ L.append(("brief", sp.sentence(f"{rules.skew_words(s['skewness'])}, skewness {sp.num(s['skewness'])}")))
125
+ L.append(("brief", _text.tails_sentence(s)))
126
+ L.append(("standard", f"Median {sp.num(s['median'])}, mean {sp.num(s['mean'])}. Middle half between {sp.num(s['q1'])} and {sp.num(s['q3'])}."))
127
+ L.append(("standard", f"Range {sp.range_text(s['min'], s['max'])}. Smoothing bandwidth {sp.num(pk['bandwidth'])}, Scott's rule."))
128
+ L.append(("full", _text.outlier_sentence(s, x[_stats.outlier_mask(x, s)])))
129
+ L.append(("full", _text.normality_sentence(nt, inp.n)))
130
+ L = [(lv, t) for lv, t in L if t]
131
+ facts = {**s, **nt, "peaks": pk["peaks"], "peak_heights": pk["peak_heights"], "n_peaks": len(pk["peaks"]), "flat": pk["flat"],
132
+ "bandwidth": pk["bandwidth"], "n_missing": inp.n_missing, "n_total": inp.n_total}
133
+ res = build(
134
+ "kde", inp.name, facts, L, title=f"Density of {inp.name}", level=level,
135
+ glossary=_text.glossary(s),
136
+ advice=_text.numeric_advice(x, s, inp.n_missing, inp.n_total, pk["peaks"]),
137
+ extras={"outliers": _outlier_rows(inp, s)},
138
+ )
139
+ return _maybe_plot(res, plot, "kde", grid=pk["grid"], density=pk["density"])
140
+
141
+
142
+ # ----- groups ------------------------------------------------------------------
143
+
144
+ def _groups(data, column, by):
145
+ frame, column, by = _input.frame_and_group(data, column, by)
146
+ out = []
147
+ for key, part in frame.groupby(by, sort=True, observed=True, dropna=True):
148
+ key = key[0] if isinstance(key, tuple) and len(key) == 1 else key
149
+ inp = _input.numeric(part, column, name=str(column))
150
+ out.append((key, inp))
151
+ return frame, column, by, out
152
+
153
+
154
+ def _label(by, key) -> str:
155
+ return f"{by} {key}"
156
+
157
+
158
+ def _group_table(by, groups) -> pd.DataFrame:
159
+ rows = []
160
+ for key, inp in groups:
161
+ s = _stats.summary(inp.values)
162
+ pk = _stats.density_peaks(inp.values)
163
+ rows.append({by: key, "n": s["n"], "missing": inp.n_missing, "median": s["median"], "mean": s["mean"],
164
+ "q1": s["q1"], "q3": s["q3"], "iqr": s["iqr"], "outliers": s["n_outliers"],
165
+ "n_peaks": len(pk["peaks"]), "flat": pk["flat"], "peaks": pk["peaks"]})
166
+ return pd.DataFrame(rows).set_index(by)
167
+
168
+
169
+ def _grouped_lines(kind_word, column, by, table: pd.DataFrame, groups) -> list:
170
+ t = table[table["n"] > 0]
171
+ L = [("brief", f"{column} by {by}, {sp.plural(len(table), 'group')}.")]
172
+ if len(t) == 0:
173
+ return L + [("brief", "No numeric values in any group.")]
174
+ med = t["median"]
175
+ if len(t) == 1:
176
+ only = t.index[0]
177
+ L.append(("brief", f"Only {_label(by, only)} has values: median {sp.num(med.iloc[0])}."))
178
+ elif med.max() == med.min():
179
+ L.append(("brief", f"Every group has the same median, {sp.num(med.iloc[0])}."))
180
+ else:
181
+ top = [_label(by, k) for k in med.index[med == med.max()]]
182
+ bottom = [_label(by, k) for k in med.index[med == med.min()]]
183
+ L.append(("brief", f"Highest median: {sp.join(top)} at {sp.num(med.max())}. "
184
+ f"Lowest: {sp.join(bottom)} at {sp.num(med.min())}."))
185
+ if len(t) > 1:
186
+ wide = t["iqr"].idxmax()
187
+ L.append(("brief", f"Widest spread: {_label(by, wide)}, middle half {sp.range_text(t.loc[wide, 'q1'], t.loc[wide, 'q3'])}."))
188
+ for key, row in table.iterrows():
189
+ if row["n"] == 0:
190
+ L.append(("standard", f"{_label(by, key)}: no values."))
191
+ continue
192
+ extra = ""
193
+ if kind_word == "violin":
194
+ pk = row["peaks"]
195
+ extra = ", one peak" if len(pk) == 1 else f", {len(pk)} peaks near {sp.join([sp.num(p) for p in pk[:3]])}"
196
+ L.append(("standard", f"{_label(by, key)}: {sp.plural(int(row['n']), 'value')}, median {sp.num(row['median'])}, "
197
+ f"middle half {sp.range_text(row['q1'], row['q3'])}, {sp.plural(int(row['outliers']), 'outlier')}{extra}."))
198
+ samples = [inp.values for _, inp in groups if inp.n > 0]
199
+ if len(samples) >= 2:
200
+ try:
201
+ p = float(stats.kruskal(*samples).pvalue)
202
+ verdict = "the groups differ" if p < config.thresholds["normality_alpha"] else "no evidence the groups differ"
203
+ L.append(("full", f"Kruskal-Wallis test, {sp.pvalue(p)}: {verdict}."))
204
+ except ValueError:
205
+ pass
206
+ return L
207
+
208
+
209
+ # ----- box ---------------------------------------------------------------------
210
+
211
+ def box(data, column=None, *, by=None, name=None, level=None, plot=False):
212
+ """Describe a box plot, optionally one box per group with ``by=``."""
213
+ if by is not None:
214
+ frame, column, by, groups = _groups(data, column, by)
215
+ table = _group_table(by, groups)
216
+ L = _grouped_lines("box", column, by, table, groups)
217
+ res = build("box", f"{column} by {by}", {"n_groups": len(table)}, L,
218
+ title=f"Box plot of {column} by {by}", level=level,
219
+ extras={"groups": table.drop(columns=["peaks", "n_peaks", "flat"])})
220
+ return _maybe_plot(res, plot, "box", groups=[(k, g.values) for k, g in groups])
221
+
222
+ inp = _input.numeric(data, column, name)
223
+ if inp.n == 0:
224
+ return _empty("box", inp, level)
225
+ x = inp.values
226
+ s, pk, nt = _common(inp)
227
+ L = [("brief", f"Box plot of {inp.name}, {sp.plural(inp.n, 'value')}, {inp.missing_phrase()}.")]
228
+ if s["constant"]:
229
+ L.append(("brief", _text.shape_sentence(s)))
230
+ else:
231
+ L.append(("brief", _text.small_sample_sentence(inp.n)))
232
+ L.append(("brief", f"Median {sp.num(s['median'])}, middle half {sp.range_text(s['q1'], s['q3'])}."))
233
+ L.append(("brief", f"Whiskers {sp.range_text(s['whisker_low'], s['whisker_high'])}."))
234
+ L.append(("brief", _text.outlier_sentence(s, x[_stats.outlier_mask(x, s)])))
235
+ L.append(("standard", f"IQR {sp.num(s['iqr'])}. Mean {sp.num(s['mean'])}."))
236
+ L.append(("standard", sp.sentence(f"{rules.skew_words(s['skewness'])}, skewness {sp.num(s['skewness'])}")))
237
+ if s["n_extreme"]:
238
+ L.append(("standard", f"{sp.integer(s['n_extreme'])} of the outliers are extreme, beyond {sp.num(config.thresholds['extreme_iqr'])} IQR."))
239
+ L.append(("full", f"Range {sp.range_text(s['min'], s['max'])}."))
240
+ L.append(("full", _text.normality_sentence(nt, inp.n)))
241
+ L = [(lv, t) for lv, t in L if t]
242
+ facts = {**s, **nt, "n_missing": inp.n_missing, "n_total": inp.n_total}
243
+ extra_gloss = {"whiskers": (
244
+ "Whiskers reach from the box to the most extreme values that are not outliers. "
245
+ f"This result: {sp.range_text(s['whisker_low'], s['whisker_high'])}.")}
246
+ res = build("box", inp.name, facts, L, title=f"Box plot of {inp.name}", level=level,
247
+ glossary=_text.glossary(s, extra_gloss),
248
+ advice=_text.numeric_advice(x, s, inp.n_missing, inp.n_total),
249
+ extras={"outliers": _outlier_rows(inp, s)})
250
+ return _maybe_plot(res, plot, "box", x=x)
251
+
252
+
253
+ # ----- violin ------------------------------------------------------------------
254
+
255
+ def violin(data, column=None, *, by=None, name=None, level=None, plot=False):
256
+ """Describe a violin plot: box-plot numbers plus the shape of the density."""
257
+ if by is not None:
258
+ frame, column, by, groups = _groups(data, column, by)
259
+ table = _group_table(by, groups)
260
+ L = _grouped_lines("violin", column, by, table, groups)
261
+ # In brief, also say the peaks of up to max_items groups.
262
+ shown = 0
263
+ for key, row in table.iterrows():
264
+ if row["n"] == 0 or shown >= config.max_items:
265
+ continue
266
+ pk = row["peaks"]
267
+ if len(pk) == 1:
268
+ txt = f"{_label(by, key)}: one peak near {sp.num(pk[0])}."
269
+ elif pk:
270
+ txt = f"{_label(by, key)}: {len(pk)} peaks, near {sp.join([sp.num(p) for p in pk[:3]])}."
271
+ else:
272
+ txt = ""
273
+ if txt:
274
+ L.insert(1 + shown, ("brief", txt))
275
+ shown += 1
276
+ res = build("violin", f"{column} by {by}", {"n_groups": len(table)}, L,
277
+ title=f"Violin plot of {column} by {by}", level=level, extras={"groups": table})
278
+ return _maybe_plot(res, plot, "violin", groups=[(k, g.values) for k, g in groups])
279
+
280
+ inp = _input.numeric(data, column, name)
281
+ if inp.n == 0:
282
+ return _empty("violin", inp, level)
283
+ x = inp.values
284
+ s, pk, nt = _common(inp)
285
+ L = [("brief", f"Violin plot of {inp.name}, {sp.plural(inp.n, 'value')}, {inp.missing_phrase()}.")]
286
+ if s["constant"]:
287
+ L.append(("brief", _text.shape_sentence(s)))
288
+ else:
289
+ L.append(("brief", _text.small_sample_sentence(inp.n)))
290
+ L.append(("brief", _text.peaks_sentence(pk["peaks"], pk["flat"])))
291
+ L.append(("brief", f"Median {sp.num(s['median'])}, middle half {sp.range_text(s['q1'], s['q3'])}."))
292
+ L.append(("brief", sp.sentence(f"{rules.skew_words(s['skewness'])}, skewness {sp.num(s['skewness'])}")))
293
+ L.append(("standard", _text.tails_sentence(s)))
294
+ L.append(("standard", f"Range {sp.range_text(s['min'], s['max'])}."))
295
+ L.append(("standard", _text.outlier_sentence(s, x[_stats.outlier_mask(x, s)])))
296
+ L.append(("full", _text.normality_sentence(nt, inp.n)))
297
+ L = [(lv, t) for lv, t in L if t]
298
+ facts = {**s, **nt, "peaks": pk["peaks"], "n_peaks": len(pk["peaks"]), "flat": pk["flat"], "n_missing": inp.n_missing, "n_total": inp.n_total}
299
+ res = build("violin", inp.name, facts, L, title=f"Violin plot of {inp.name}", level=level,
300
+ glossary=_text.glossary(s),
301
+ advice=_text.numeric_advice(x, s, inp.n_missing, inp.n_total, pk["peaks"]),
302
+ extras={"outliers": _outlier_rows(inp, s)})
303
+ return _maybe_plot(res, plot, "violin", x=x)
304
+
305
+
306
+ # ----- Q-Q ---------------------------------------------------------------------
307
+
308
+ def _tail_sentences(q: dict) -> list[str]:
309
+ t = config.thresholds["qq_tail_sd"]
310
+ out = []
311
+ hg, lg = q["high_tail_gap"], q["low_tail_gap"]
312
+ if hg > t:
313
+ out.append("At the high end, points rise above the line: the upper tail is longer than normal.")
314
+ elif hg < -t:
315
+ out.append("At the high end, points fall below the line: the upper tail is shorter than normal.")
316
+ if lg < -t:
317
+ out.append("At the low end, points fall below the line: the lower tail is longer than normal.")
318
+ elif lg > t:
319
+ out.append("At the low end, points sit above the line: the lower tail is shorter than normal.")
320
+ if not out:
321
+ out.append("Points follow the line closely at both ends.")
322
+ return out
323
+
324
+
325
+ def qq(data, column=None, *, name=None, level=None, plot=False):
326
+ """Describe a normal Q-Q plot: where the points leave the straight line."""
327
+ inp = _input.numeric(data, column, name)
328
+ if inp.n == 0:
329
+ return _empty("qq", inp, level)
330
+ x = inp.values
331
+ s = _stats.summary(x)
332
+ nt = _stats.normality(x)
333
+ q = _stats.qq_tails(x)
334
+ L = [("brief", f"Q-Q plot of {inp.name} against the normal distribution, {sp.plural(inp.n, 'value')}.")]
335
+ if s["constant"]:
336
+ L.append(("brief", _text.shape_sentence(s)))
337
+ else:
338
+ L.append(("brief", _text.small_sample_sentence(inp.n)))
339
+ for t in _tail_sentences(q):
340
+ L.append(("brief", t))
341
+ L.append(("brief", _text.normality_sentence(nt, inp.n)))
342
+ L.append(("standard", f"Straightness of the points, correlation with the line: {sp.num(q['qq_r'], 4)}."))
343
+ L.append(("standard", sp.sentence(f"{rules.skew_words(s['skewness'])}, skewness {sp.num(s['skewness'])}; "
344
+ f"{rules.kurtosis_words(s['kurtosis'])}, excess kurtosis {sp.num(s['kurtosis'])}")))
345
+ L.append(("full", f"Mean gap from the line in the outer {sp.pct(config.thresholds['qq_tail_share'])} of points, "
346
+ f"in standard deviations: low end {sp.num(q['low_tail_gap'])}, high end {sp.num(q['high_tail_gap'])}."))
347
+ if inp.n_missing:
348
+ L.append(("full", f"{inp.missing_phrase().capitalize()} were left out."))
349
+ L = [(lv, t) for lv, t in L if t]
350
+ facts = {**s, **nt, **{k: v for k, v in q.items() if not k.startswith("_")},
351
+ "n_missing": inp.n_missing, "n_total": inp.n_total}
352
+ gloss = _text.glossary(s, {"q-q plot": (
353
+ "A Q-Q plot puts each sorted value against where it would sit if the data were normal. "
354
+ "Normal data falls on a straight line. Points above the line at the high end mean a longer "
355
+ "upper tail; points below the line at the low end mean a longer lower tail. "
356
+ f"A tail is called different when its points sit more than {sp.num(config.thresholds['qq_tail_sd'])} "
357
+ "standard deviations from the line on average.")})
358
+ res = build("qq", inp.name, facts, L, title=f"Q-Q plot of {inp.name}", level=level, glossary=gloss,
359
+ advice=_text.numeric_advice(x, s, inp.n_missing, inp.n_total))
360
+ return _maybe_plot(res, plot, "qq", osm=q.get("_osm"), osr=q.get("_osr"),
361
+ slope=q["qq_slope"], intercept=q["qq_intercept"])
362
+
363
+
364
+ # ----- cumulative distribution -------------------------------------------------
365
+
366
+ def ecdf(data, column=None, *, name=None, level=None, plot=False):
367
+ """Describe the cumulative distribution (cumulative histogram) of one numeric column.
368
+
369
+ The result answers follow-up questions: ``r.at(100)`` gives the share of values
370
+ at or below 100, and ``r.quantile(0.9)`` the value with 90% at or below it.
371
+ """
372
+ inp = _input.numeric(data, column, name)
373
+ if inp.n == 0:
374
+ return _empty("ecdf", inp, level)
375
+ x = np.sort(inp.values)
376
+ s = _stats.summary(x)
377
+ pk = _stats.density_peaks(x)
378
+ probs = [0.10, 0.25, 0.50, 0.75, 0.90]
379
+ qs = {p: float(np.percentile(x, p * 100)) for p in probs}
380
+
381
+ def at(value) -> float:
382
+ """Share of values at or below ``value``."""
383
+ return float(np.searchsorted(x, value, side="right") / len(x))
384
+
385
+ def quantile(p: float) -> float:
386
+ """The value with share ``p`` of values at or below it."""
387
+ return float(np.percentile(x, p * 100))
388
+
389
+ L = [("brief", f"Cumulative distribution of {inp.name}, {sp.plural(inp.n, 'value')}, {inp.missing_phrase()}.")]
390
+ if s["constant"]:
391
+ L.append(("brief", _text.shape_sentence(s)))
392
+ else:
393
+ L.append(("brief", f"25% of values are at or below {sp.num(qs[0.25])}, 50% at or below {sp.num(qs[0.5])}, "
394
+ f"90% at or below {sp.num(qs[0.9])}."))
395
+ if pk["peaks"]:
396
+ L.append(("brief", f"Steepest rise near {sp.num(pk['peaks'][0])}."))
397
+ L.append(("standard", f"10% at or below {sp.num(qs[0.1])}, 75% at or below {sp.num(qs[0.75])}."))
398
+ L.append(("standard", f"Starts at {sp.num(s['min'])} and reaches 100% at {sp.num(s['max'])}."))
399
+ L.append(("full", "Use .at(value) for the share at or below a value, and .quantile(share) for the reverse."))
400
+ facts = {**s, "quantiles": {f"{int(p * 100)}%": v for p, v in qs.items()},
401
+ "steepest_near": pk["peaks"][0] if pk["peaks"] else float("nan"),
402
+ "n_missing": inp.n_missing, "n_total": inp.n_total}
403
+ gloss = _text.glossary(s, {"ecdf": (
404
+ "The empirical cumulative distribution shows, for each value, the share of data at or below it. "
405
+ "It rises from 0 to 100%. It rises fastest where values are most crowded.")})
406
+ res = build("ecdf", inp.name, facts, L, title=f"Cumulative distribution of {inp.name}", level=level,
407
+ glossary=gloss, advice=_text.numeric_advice(x, s, inp.n_missing, inp.n_total),
408
+ extras={"at": at, "quantile": quantile})
409
+ return _maybe_plot(res, plot, "ecdf", x=x)