statstudio 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.
- statstudio/__init__.py +9 -0
- statstudio/__main__.py +3 -0
- statstudio/app.py +83 -0
- statstudio/cli.py +116 -0
- statstudio/core/__init__.py +3 -0
- statstudio/core/archive.py +27 -0
- statstudio/core/commands.py +67 -0
- statstudio/core/formula_catalog.py +74 -0
- statstudio/core/formulas.py +605 -0
- statstudio/core/joins.py +123 -0
- statstudio/core/project.py +358 -0
- statstudio/core/runtime.py +321 -0
- statstudio/core/scripting.py +594 -0
- statstudio/core/table.py +796 -0
- statstudio/core/transform.py +450 -0
- statstudio/feature_help.py +595 -0
- statstudio/io/__init__.py +3 -0
- statstudio/io/docx.py +201 -0
- statstudio/io/export.py +99 -0
- statstudio/io/file_import.py +199 -0
- statstudio/io/odbc.py +334 -0
- statstudio/io/sample_data.py +164 -0
- statstudio/io/table_io.py +118 -0
- statstudio/plots/__init__.py +19 -0
- statstudio/plots/advanced.py +651 -0
- statstudio/plots/basic.py +957 -0
- statstudio/plots/bayesian_plots.py +94 -0
- statstudio/plots/common.py +334 -0
- statstudio/plots/diagnostics.py +214 -0
- statstudio/plots/doe_plots.py +235 -0
- statstudio/plots/plotly_builders.py +719 -0
- statstudio/plots/predictive_plots.py +72 -0
- statstudio/plots/registry.py +251 -0
- statstudio/plugins.py +111 -0
- statstudio/resources/help_topics.json +13195 -0
- statstudio/resources/logo.ico +0 -0
- statstudio/resources/logo.png +0 -0
- statstudio/resources/statstudio.svg +8 -0
- statstudio/stats/__init__.py +42 -0
- statstudio/stats/bayesian.py +1094 -0
- statstudio/stats/bayesian_optimization.py +590 -0
- statstudio/stats/common.py +140 -0
- statstudio/stats/correlation.py +135 -0
- statstudio/stats/custom_doe.py +1714 -0
- statstudio/stats/descriptive.py +200 -0
- statstudio/stats/desirability.py +132 -0
- statstudio/stats/distributions.py +331 -0
- statstudio/stats/doe.py +1070 -0
- statstudio/stats/hypothesis.py +1305 -0
- statstudio/stats/multivariate.py +307 -0
- statstudio/stats/optimal_doe.py +264 -0
- statstudio/stats/power.py +194 -0
- statstudio/stats/predictive.py +605 -0
- statstudio/stats/profiler.py +379 -0
- statstudio/stats/quality.py +1218 -0
- statstudio/stats/regression.py +1600 -0
- statstudio/stats/results.py +235 -0
- statstudio/stats/simulator.py +95 -0
- statstudio/stats/survival.py +637 -0
- statstudio/stats/timeseries.py +643 -0
- statstudio/stats/tolerance.py +154 -0
- statstudio/ui/__init__.py +0 -0
- statstudio/ui/analysis_hub.py +271 -0
- statstudio/ui/command_catalog.py +460 -0
- statstudio/ui/command_palette.py +55 -0
- statstudio/ui/console.py +239 -0
- statstudio/ui/dialogs/__init__.py +0 -0
- statstudio/ui/dialogs/advanced_dialogs.py +392 -0
- statstudio/ui/dialogs/base.py +537 -0
- statstudio/ui/dialogs/bayesian_dialogs.py +488 -0
- statstudio/ui/dialogs/bayesian_optimization_dialog.py +299 -0
- statstudio/ui/dialogs/custom_doe_dialog.py +467 -0
- statstudio/ui/dialogs/doe_dialogs.py +220 -0
- statstudio/ui/dialogs/extended_dialogs.py +665 -0
- statstudio/ui/dialogs/graph_builder.py +139 -0
- statstudio/ui/dialogs/help_dialog.py +207 -0
- statstudio/ui/dialogs/help_topics.py +280 -0
- statstudio/ui/dialogs/lazy.py +184 -0
- statstudio/ui/dialogs/odbc_dialog.py +311 -0
- statstudio/ui/dialogs/plot_dialog.py +1385 -0
- statstudio/ui/dialogs/report_composer.py +218 -0
- statstudio/ui/dialogs/script_dialogs.py +267 -0
- statstudio/ui/dialogs/stats_dialogs.py +1688 -0
- statstudio/ui/dialogs/table_dialogs.py +997 -0
- statstudio/ui/dialogs/window.py +58 -0
- statstudio/ui/docks/__init__.py +0 -0
- statstudio/ui/formula_editor.py +121 -0
- statstudio/ui/icons.py +257 -0
- statstudio/ui/jobs.py +179 -0
- statstudio/ui/main_window.py +3934 -0
- statstudio/ui/plot_interaction.py +178 -0
- statstudio/ui/profiler_widget.py +437 -0
- statstudio/ui/recent.py +82 -0
- statstudio/ui/reports/__init__.py +0 -0
- statstudio/ui/reports/report_view.py +1632 -0
- statstudio/ui/script_jobs.py +35 -0
- statstudio/ui/scripts_panel.py +271 -0
- statstudio/ui/table_document.py +233 -0
- statstudio/ui/table_model.py +285 -0
- statstudio/ui/table_view.py +285 -0
- statstudio/ui/theme.py +645 -0
- statstudio/ui/welcome.py +453 -0
- statstudio/ui/window_controls.py +53 -0
- statstudio/ui/workers.py +53 -0
- statstudio-0.1.0.dist-info/METADATA +261 -0
- statstudio-0.1.0.dist-info/RECORD +110 -0
- statstudio-0.1.0.dist-info/WHEEL +5 -0
- statstudio-0.1.0.dist-info/entry_points.txt +5 -0
- statstudio-0.1.0.dist-info/licenses/LICENSE +674 -0
- statstudio-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,957 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
5
|
+
from matplotlib import dates as mdates
|
|
6
|
+
from scipy import stats
|
|
7
|
+
|
|
8
|
+
from statstudio.plots.common import (
|
|
9
|
+
attach_row_ids,
|
|
10
|
+
color,
|
|
11
|
+
error_column_name,
|
|
12
|
+
frame,
|
|
13
|
+
new_figure,
|
|
14
|
+
numeric,
|
|
15
|
+
rotate_labels,
|
|
16
|
+
row_ids_for,
|
|
17
|
+
style_axes,
|
|
18
|
+
)
|
|
19
|
+
from statstudio.stats.results import PlotSpec
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _is_date_like(series: pd.Series) -> bool:
|
|
23
|
+
if pd.api.types.is_datetime64_any_dtype(series):
|
|
24
|
+
return True
|
|
25
|
+
if series.dtype == object:
|
|
26
|
+
sample = series.dropna().head(200).astype(str)
|
|
27
|
+
if sample.empty:
|
|
28
|
+
return False
|
|
29
|
+
has_sep = sample.str.contains(r"[-/:T]", regex=True).any()
|
|
30
|
+
has_year = sample.str.contains(r"(?:19|20)\d{2}", regex=True).all()
|
|
31
|
+
return bool(has_sep and has_year)
|
|
32
|
+
return False
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _to_datetime(series: pd.Series) -> pd.Series:
|
|
36
|
+
return pd.to_datetime(series, errors="coerce")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def histogram(spec: PlotSpec):
|
|
40
|
+
data = frame(spec)
|
|
41
|
+
name = spec.params.get("column") or spec.params.get("x")
|
|
42
|
+
values = numeric(data, name).dropna()
|
|
43
|
+
figure = new_figure()
|
|
44
|
+
ax = figure.add_subplot(111)
|
|
45
|
+
bins = spec.params.get("bins", "auto")
|
|
46
|
+
distribution = spec.params.get("distribution")
|
|
47
|
+
density_mode = bool(distribution)
|
|
48
|
+
group_name = spec.params.get("group")
|
|
49
|
+
if group_name and group_name in data.columns:
|
|
50
|
+
grouped = list(data.groupby(group_name, dropna=False, sort=True))
|
|
51
|
+
pooled = pd.concat([numeric(chunk, name).dropna() for _, chunk in grouped])
|
|
52
|
+
shared_bins = bins
|
|
53
|
+
if len(pooled) > 0 and not isinstance(bins, (list, tuple, np.ndarray)):
|
|
54
|
+
shared_bins = np.histogram_bin_edges(pooled.to_numpy(dtype=float), bins=bins)
|
|
55
|
+
for index, (label, chunk) in enumerate(grouped):
|
|
56
|
+
chunk_values = numeric(chunk, name).dropna()
|
|
57
|
+
if len(chunk_values):
|
|
58
|
+
ax.hist(chunk_values, bins=shared_bins, color=color(index), edgecolor="white", alpha=0.6, density=density_mode, label="Missing" if pd.isna(label) else str(label))
|
|
59
|
+
ax.legend(title=str(group_name), frameon=False, fontsize=8)
|
|
60
|
+
else:
|
|
61
|
+
ax.hist(values, bins=bins, color=color(0), edgecolor="white", alpha=0.9, density=density_mode)
|
|
62
|
+
if distribution:
|
|
63
|
+
scipy_name = spec.params.get("scipy_distribution") or distribution
|
|
64
|
+
scipy_distribution = getattr(stats, scipy_name, None)
|
|
65
|
+
if scipy_distribution is not None:
|
|
66
|
+
if group_name and group_name in data.columns:
|
|
67
|
+
for index, (label, chunk) in enumerate(data.groupby(group_name, dropna=False, sort=True)):
|
|
68
|
+
chunk_values = numeric(chunk, name).dropna().to_numpy(dtype=float)
|
|
69
|
+
if len(chunk_values) < 3:
|
|
70
|
+
continue
|
|
71
|
+
try:
|
|
72
|
+
fitted = tuple(float(value) for value in scipy_distribution.fit(chunk_values))
|
|
73
|
+
except Exception:
|
|
74
|
+
continue
|
|
75
|
+
xs = np.linspace(float(chunk_values.min()), float(chunk_values.max()), 300)
|
|
76
|
+
label_text = "Missing" if pd.isna(label) else str(label)
|
|
77
|
+
ax.plot(xs, scipy_distribution.pdf(xs, *fitted), color=color(index), linewidth=2, label=f"{label_text} fit")
|
|
78
|
+
ax.legend(title=str(group_name), frameon=False, fontsize=8)
|
|
79
|
+
elif spec.params.get("fit_args") is not None:
|
|
80
|
+
xs = np.linspace(values.min(), values.max(), 300)
|
|
81
|
+
ax.plot(xs, scipy_distribution.pdf(xs, *spec.params["fit_args"]), color=color(1), linewidth=2, label=str(distribution))
|
|
82
|
+
ax.legend(frameon=False)
|
|
83
|
+
for value, label, style in [(spec.params.get("lsl"), "LSL", "--"), (spec.params.get("usl"), "USL", "--"), (spec.params.get("target"), "Target", ":")]:
|
|
84
|
+
if value is not None:
|
|
85
|
+
ax.axvline(value, color="#333333", linestyle=style, linewidth=1.3)
|
|
86
|
+
ax.text(value, ax.get_ylim()[1] * 0.95, label, fontsize=8, ha="center")
|
|
87
|
+
if spec.params.get("normal_overlay"):
|
|
88
|
+
if len(values) > 2 and values.std() > 0:
|
|
89
|
+
xs = np.linspace(values.min(), values.max(), 200)
|
|
90
|
+
density = stats.norm.pdf(xs, values.mean(), values.std(ddof=1))
|
|
91
|
+
if density_mode:
|
|
92
|
+
scaled = density
|
|
93
|
+
else:
|
|
94
|
+
counts, edges = np.histogram(values, bins=bins)
|
|
95
|
+
width = float(edges[1] - edges[0]) if len(edges) > 1 else 1.0
|
|
96
|
+
scaled = density * len(values) * width
|
|
97
|
+
ax.plot(xs, scaled, color=color(1), linewidth=2, label="Normal")
|
|
98
|
+
ax.legend(frameon=False)
|
|
99
|
+
style_axes(ax, spec.title or f"Distribution of {name}", str(name), "Density" if density_mode else "Count")
|
|
100
|
+
_apply_options(ax, spec)
|
|
101
|
+
return figure
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def box(spec: PlotSpec):
|
|
105
|
+
data = frame(spec)
|
|
106
|
+
value_name = spec.params.get("column") or spec.params.get("y")
|
|
107
|
+
group_name = spec.params.get("group") or spec.params.get("x")
|
|
108
|
+
show_points = bool(spec.params.get("show_points", True))
|
|
109
|
+
figure = new_figure()
|
|
110
|
+
ax = figure.add_subplot(111)
|
|
111
|
+
work = pd.DataFrame({"__value__": numeric(data, value_name)}, index=data.index)
|
|
112
|
+
work["__row_id__"] = row_ids_for(spec, data.index)
|
|
113
|
+
if group_name and group_name in data.columns:
|
|
114
|
+
work["__group__"] = data[group_name]
|
|
115
|
+
groups = []
|
|
116
|
+
labels = []
|
|
117
|
+
point_groups = []
|
|
118
|
+
for label, chunk in work.groupby("__group__", dropna=False, sort=True):
|
|
119
|
+
valid = chunk["__value__"].notna()
|
|
120
|
+
groups.append(chunk.loc[valid, "__value__"].to_numpy(dtype=float))
|
|
121
|
+
labels.append("Missing" if pd.isna(label) else str(label))
|
|
122
|
+
point_groups.append((chunk.loc[valid, "__value__"].to_numpy(dtype=float), chunk.loc[valid, "__row_id__"].tolist()))
|
|
123
|
+
try:
|
|
124
|
+
ax.boxplot(
|
|
125
|
+
groups,
|
|
126
|
+
tick_labels=labels,
|
|
127
|
+
patch_artist=True,
|
|
128
|
+
boxprops={"facecolor": "#dce8f5"},
|
|
129
|
+
medianprops={"color": color(1)},
|
|
130
|
+
showfliers=not show_points,
|
|
131
|
+
)
|
|
132
|
+
except TypeError:
|
|
133
|
+
ax.boxplot(
|
|
134
|
+
groups,
|
|
135
|
+
labels=labels,
|
|
136
|
+
patch_artist=True,
|
|
137
|
+
boxprops={"facecolor": "#dce8f5"},
|
|
138
|
+
medianprops={"color": color(1)},
|
|
139
|
+
showfliers=not show_points,
|
|
140
|
+
)
|
|
141
|
+
if show_points:
|
|
142
|
+
rng = np.random.default_rng(0)
|
|
143
|
+
for position, (values, ids) in enumerate(point_groups, start=1):
|
|
144
|
+
_box_points(ax, values, ids, position, rng)
|
|
145
|
+
rotate_labels(ax)
|
|
146
|
+
style_axes(ax, spec.title or f"{value_name} by {group_name}", str(group_name), str(value_name))
|
|
147
|
+
else:
|
|
148
|
+
valid = work["__value__"].notna()
|
|
149
|
+
values = work.loc[valid, "__value__"].to_numpy(dtype=float)
|
|
150
|
+
ids = work.loc[valid, "__row_id__"].tolist()
|
|
151
|
+
try:
|
|
152
|
+
ax.boxplot(
|
|
153
|
+
[values],
|
|
154
|
+
tick_labels=[str(value_name)],
|
|
155
|
+
patch_artist=True,
|
|
156
|
+
boxprops={"facecolor": "#dce8f5"},
|
|
157
|
+
medianprops={"color": color(1)},
|
|
158
|
+
showfliers=not show_points,
|
|
159
|
+
)
|
|
160
|
+
except TypeError:
|
|
161
|
+
ax.boxplot(
|
|
162
|
+
[values],
|
|
163
|
+
labels=[str(value_name)],
|
|
164
|
+
patch_artist=True,
|
|
165
|
+
boxprops={"facecolor": "#dce8f5"},
|
|
166
|
+
medianprops={"color": color(1)},
|
|
167
|
+
showfliers=not show_points,
|
|
168
|
+
)
|
|
169
|
+
if show_points:
|
|
170
|
+
_box_points(ax, values, ids, 1, np.random.default_rng(0))
|
|
171
|
+
style_axes(ax, spec.title or f"Distribution of {value_name}", "", str(value_name))
|
|
172
|
+
_apply_options(ax, spec)
|
|
173
|
+
return figure
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _box_points(ax, values, ids, position: int, rng) -> None:
|
|
177
|
+
if len(values) == 0:
|
|
178
|
+
return
|
|
179
|
+
jitter = rng.uniform(-0.08, 0.08, size=len(values))
|
|
180
|
+
points = ax.scatter(
|
|
181
|
+
np.full(len(values), float(position)) + jitter,
|
|
182
|
+
values,
|
|
183
|
+
s=14,
|
|
184
|
+
color="#425466",
|
|
185
|
+
alpha=0.55,
|
|
186
|
+
linewidths=0,
|
|
187
|
+
zorder=3,
|
|
188
|
+
picker=True,
|
|
189
|
+
)
|
|
190
|
+
attach_row_ids(points, ids)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def bar(spec: PlotSpec):
|
|
194
|
+
data = frame(spec)
|
|
195
|
+
x_name = spec.params["x"]
|
|
196
|
+
y_name = spec.params["y"]
|
|
197
|
+
group_name = spec.params.get("group")
|
|
198
|
+
error_name = error_column_name(spec.params, data)
|
|
199
|
+
figure = new_figure()
|
|
200
|
+
ax = figure.add_subplot(111)
|
|
201
|
+
work = pd.DataFrame({"__x": data[x_name].fillna("(missing)").astype(str), "__y": numeric(data, y_name)})
|
|
202
|
+
if group_name and group_name in data.columns:
|
|
203
|
+
work["__g"] = data[group_name].fillna("(missing)").astype(str)
|
|
204
|
+
if error_name:
|
|
205
|
+
work["__e"] = numeric(data, error_name)
|
|
206
|
+
error_agg = work.groupby(["__x", "__g"], sort=False, dropna=False)["__e"].sum().unstack("__g")
|
|
207
|
+
else:
|
|
208
|
+
error_agg = None
|
|
209
|
+
aggregated = work.groupby(["__x", "__g"], sort=False, dropna=False)["__y"].sum().unstack("__g")
|
|
210
|
+
categories = [str(value) for value in aggregated.index]
|
|
211
|
+
positions = np.arange(len(categories), dtype=float)
|
|
212
|
+
count = max(1, aggregated.shape[1])
|
|
213
|
+
width = 0.8 / count
|
|
214
|
+
for group_index, group_label in enumerate(aggregated.columns):
|
|
215
|
+
offsets = positions + (group_index - (count - 1) / 2.0) * width
|
|
216
|
+
ax.bar(offsets, aggregated[group_label].to_numpy(dtype=float), width=width, color=color(group_index), alpha=0.9, label=str(group_label))
|
|
217
|
+
if error_agg is not None and group_label in error_agg.columns:
|
|
218
|
+
yerr = error_agg[group_label].reindex(aggregated.index).to_numpy(dtype=float)
|
|
219
|
+
ax.errorbar(offsets, aggregated[group_label].to_numpy(dtype=float), yerr=yerr, fmt="none", ecolor="#333333", capsize=3)
|
|
220
|
+
ax.set_xticks(positions, categories)
|
|
221
|
+
ax.legend(title=str(group_name), frameon=False, fontsize=8)
|
|
222
|
+
else:
|
|
223
|
+
aggregated = work.groupby("__x", sort=False, dropna=False)["__y"].sum()
|
|
224
|
+
categories = [str(value) for value in aggregated.index]
|
|
225
|
+
positions = np.arange(len(categories), dtype=float)
|
|
226
|
+
ax.bar(positions, aggregated.to_numpy(dtype=float), color=color(0), alpha=0.9)
|
|
227
|
+
ax.set_xticks(positions, categories)
|
|
228
|
+
if error_name:
|
|
229
|
+
error_values = (
|
|
230
|
+
pd.DataFrame({"__x": work["__x"], "__e": numeric(data, error_name)})
|
|
231
|
+
.groupby("__x", sort=False)["__e"]
|
|
232
|
+
.sum()
|
|
233
|
+
.reindex(aggregated.index)
|
|
234
|
+
)
|
|
235
|
+
ax.errorbar(positions, aggregated.to_numpy(dtype=float), yerr=error_values.to_numpy(dtype=float), fmt="none", ecolor="#333333", capsize=3)
|
|
236
|
+
rotate_labels(ax)
|
|
237
|
+
style_axes(ax, spec.title or f"{y_name} by {x_name}", str(x_name), str(y_name))
|
|
238
|
+
_apply_options(ax, spec, data, x_name, y_name)
|
|
239
|
+
_add_secondary(ax, spec, data, x_name, categories)
|
|
240
|
+
return figure
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _float_param(params: dict, key: str, default: float) -> float:
|
|
244
|
+
try:
|
|
245
|
+
return float(params.get(key, default))
|
|
246
|
+
except (TypeError, ValueError):
|
|
247
|
+
return float(default)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _y1_modes(spec: PlotSpec) -> tuple[bool, bool]:
|
|
251
|
+
default_line = spec.kind == "line"
|
|
252
|
+
default_points = spec.kind == "scatter"
|
|
253
|
+
return (
|
|
254
|
+
bool(spec.params.get("y1_show_line", default_line)),
|
|
255
|
+
bool(spec.params.get("y1_show_points", default_points)),
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def scatter(spec: PlotSpec):
|
|
260
|
+
data = frame(spec)
|
|
261
|
+
x_name = spec.params["x"]
|
|
262
|
+
y_name = spec.params["y"]
|
|
263
|
+
jitter = bool(spec.params.get("jitter"))
|
|
264
|
+
rng = np.random.default_rng(0)
|
|
265
|
+
figure = new_figure()
|
|
266
|
+
ax = figure.add_subplot(111)
|
|
267
|
+
is_date = _is_date_like(data[x_name])
|
|
268
|
+
show_line, show_points = _y1_modes(spec)
|
|
269
|
+
y1_color = spec.params.get("y1_color")
|
|
270
|
+
line_width = _float_param(spec.params, "y1_line_width", 1.8)
|
|
271
|
+
marker_size = _float_param(spec.params, "marker_size", 28)
|
|
272
|
+
|
|
273
|
+
def x_values(chunk: pd.DataFrame) -> pd.Series:
|
|
274
|
+
if is_date:
|
|
275
|
+
return pd.Series(mdates.date2num(_to_datetime(chunk[x_name])), index=chunk.index)
|
|
276
|
+
values = numeric(chunk, x_name)
|
|
277
|
+
if not jitter:
|
|
278
|
+
return values
|
|
279
|
+
finite = values.dropna()
|
|
280
|
+
span = float(finite.max() - finite.min()) if len(finite) else 0.0
|
|
281
|
+
width = span * 0.02 if span > 0 else 0.02
|
|
282
|
+
return values + pd.Series(rng.uniform(-width, width, len(values)), index=values.index)
|
|
283
|
+
|
|
284
|
+
def add_points(chunk: pd.DataFrame, point_color: str, marker: str = "o", label: str | None = None) -> None:
|
|
285
|
+
if not show_points:
|
|
286
|
+
return
|
|
287
|
+
points = ax.scatter(
|
|
288
|
+
x_values(chunk),
|
|
289
|
+
numeric(chunk, y_name),
|
|
290
|
+
s=marker_size,
|
|
291
|
+
alpha=0.8,
|
|
292
|
+
color=point_color,
|
|
293
|
+
marker=marker,
|
|
294
|
+
label=label,
|
|
295
|
+
picker=True,
|
|
296
|
+
)
|
|
297
|
+
attach_row_ids(points, row_ids_for(spec, chunk.index))
|
|
298
|
+
|
|
299
|
+
def add_line(chunk: pd.DataFrame, line_color: str, label: str | None = None) -> None:
|
|
300
|
+
if not show_line:
|
|
301
|
+
return
|
|
302
|
+
line_data = pd.DataFrame(
|
|
303
|
+
{
|
|
304
|
+
"x": x_values(chunk),
|
|
305
|
+
"y": numeric(chunk, y_name),
|
|
306
|
+
"_row_id": pd.Series(row_ids_for(spec, chunk.index), index=chunk.index),
|
|
307
|
+
}
|
|
308
|
+
).dropna(subset=["x", "y"])
|
|
309
|
+
if len(line_data) < 2:
|
|
310
|
+
return
|
|
311
|
+
line_data = line_data.sort_values("x", kind="stable")
|
|
312
|
+
line, = ax.plot(
|
|
313
|
+
line_data["x"],
|
|
314
|
+
line_data["y"],
|
|
315
|
+
color=line_color,
|
|
316
|
+
linewidth=line_width,
|
|
317
|
+
alpha=0.85,
|
|
318
|
+
label=label,
|
|
319
|
+
)
|
|
320
|
+
attach_row_ids(line, line_data["_row_id"].tolist())
|
|
321
|
+
|
|
322
|
+
group_name = spec.params.get("group")
|
|
323
|
+
shape_name = spec.params.get("shape")
|
|
324
|
+
markers = ["o", "s", "^", "D", "v", "P", "X", "*"]
|
|
325
|
+
if group_name and group_name in data.columns:
|
|
326
|
+
for index, (label, chunk) in enumerate(data.groupby(group_name, dropna=False)):
|
|
327
|
+
group_label = "Missing" if pd.isna(label) else str(label)
|
|
328
|
+
group_color = y1_color or color(index)
|
|
329
|
+
if shape_name and shape_name in chunk.columns:
|
|
330
|
+
for shape_index, (_shape_label, shape_chunk) in enumerate(chunk.groupby(shape_name, dropna=False, sort=True)):
|
|
331
|
+
add_points(
|
|
332
|
+
shape_chunk,
|
|
333
|
+
group_color,
|
|
334
|
+
markers[shape_index % len(markers)],
|
|
335
|
+
group_label if shape_index == 0 else None,
|
|
336
|
+
)
|
|
337
|
+
else:
|
|
338
|
+
add_points(chunk, group_color, label=group_label)
|
|
339
|
+
add_line(chunk, group_color, None if show_points else group_label)
|
|
340
|
+
if show_points or show_line:
|
|
341
|
+
ax.legend(title=str(group_name), frameon=False, fontsize=8)
|
|
342
|
+
elif shape_name and shape_name in data.columns:
|
|
343
|
+
for shape_index, (shape_label, shape_chunk) in enumerate(data.groupby(shape_name, dropna=False, sort=True)):
|
|
344
|
+
shape_color = y1_color or color(shape_index)
|
|
345
|
+
add_points(
|
|
346
|
+
shape_chunk,
|
|
347
|
+
shape_color,
|
|
348
|
+
markers[shape_index % len(markers)],
|
|
349
|
+
str(shape_label),
|
|
350
|
+
)
|
|
351
|
+
add_line(shape_chunk, shape_color, None if show_points else str(shape_label))
|
|
352
|
+
if show_points or show_line:
|
|
353
|
+
ax.legend(title=str(shape_name), frameon=False, fontsize=8)
|
|
354
|
+
else:
|
|
355
|
+
base_color = y1_color or color(0)
|
|
356
|
+
add_points(data, base_color)
|
|
357
|
+
add_line(data, base_color)
|
|
358
|
+
if spec.params.get("identity"):
|
|
359
|
+
if is_date:
|
|
360
|
+
x_numeric = pd.Series(mdates.date2num(_to_datetime(data[x_name])), index=data.index)
|
|
361
|
+
else:
|
|
362
|
+
x_numeric = numeric(data, x_name)
|
|
363
|
+
values = pd.concat([x_numeric, numeric(data, y_name)]).dropna()
|
|
364
|
+
if not values.empty:
|
|
365
|
+
low, high = values.min(), values.max()
|
|
366
|
+
ax.plot([low, high], [low, high], linestyle="--", color="#666666", linewidth=1)
|
|
367
|
+
style_axes(ax, spec.title or f"{y_name} vs {x_name}", str(x_name), str(y_name))
|
|
368
|
+
if is_date:
|
|
369
|
+
ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(ax.xaxis.get_major_locator()))
|
|
370
|
+
figure.autofmt_xdate()
|
|
371
|
+
_apply_options(ax, spec, data, x_name, y_name)
|
|
372
|
+
_add_secondary(ax, spec, data, x_name)
|
|
373
|
+
return figure
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def line(spec: PlotSpec):
|
|
377
|
+
data = frame(spec)
|
|
378
|
+
x_name = spec.params["x"]
|
|
379
|
+
y_name = spec.params["y"]
|
|
380
|
+
figure = new_figure()
|
|
381
|
+
ax = figure.add_subplot(111)
|
|
382
|
+
x = data[x_name]
|
|
383
|
+
y = numeric(data, y_name)
|
|
384
|
+
show_line, show_points = _y1_modes(spec)
|
|
385
|
+
marker_size = max(2.0, _float_param(spec.params, "marker_size", 28) ** 0.5)
|
|
386
|
+
line_style = {
|
|
387
|
+
"color": spec.params.get("y1_color") or color(0),
|
|
388
|
+
"linewidth": _float_param(spec.params, "y1_line_width", 1.8),
|
|
389
|
+
"linestyle": "-" if show_line else "None",
|
|
390
|
+
"marker": "o" if show_points else None,
|
|
391
|
+
"markersize": marker_size,
|
|
392
|
+
}
|
|
393
|
+
if show_line or show_points:
|
|
394
|
+
if _is_date_like(x):
|
|
395
|
+
datetime_x = _to_datetime(x)
|
|
396
|
+
order = np.argsort(datetime_x.to_numpy())
|
|
397
|
+
x = x.iloc[order]
|
|
398
|
+
y = y.iloc[order]
|
|
399
|
+
ax.plot(datetime_x.iloc[order], y, **line_style)
|
|
400
|
+
ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(ax.xaxis.get_major_locator()))
|
|
401
|
+
figure.autofmt_xdate()
|
|
402
|
+
else:
|
|
403
|
+
numeric_x = pd.to_numeric(x, errors="coerce")
|
|
404
|
+
if numeric_x.notna().sum() == len(numeric_x):
|
|
405
|
+
order = np.argsort(numeric_x.to_numpy(dtype=float), kind="stable")
|
|
406
|
+
x = x.iloc[order]
|
|
407
|
+
y = y.iloc[order]
|
|
408
|
+
ax.plot(x, y, **line_style)
|
|
409
|
+
style_axes(ax, spec.title or f"{y_name}", str(x_name), str(y_name))
|
|
410
|
+
_apply_options(ax, spec, data, x_name, y_name)
|
|
411
|
+
_add_secondary(ax, spec, data, x_name)
|
|
412
|
+
return figure
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def correlation_heatmap(spec: PlotSpec):
|
|
416
|
+
data = frame(spec)
|
|
417
|
+
if "matrix" in spec.params:
|
|
418
|
+
corr = pd.DataFrame(spec.params["matrix"])
|
|
419
|
+
if "Variable" in corr.columns:
|
|
420
|
+
corr = corr.set_index("Variable")
|
|
421
|
+
else:
|
|
422
|
+
columns = spec.params.get("columns") or [str(c) for c in data.columns]
|
|
423
|
+
method = spec.params.get("method", "pearson")
|
|
424
|
+
corr = data.loc[:, columns].apply(pd.to_numeric, errors="coerce").corr(method=method)
|
|
425
|
+
figure = new_figure(max(5, len(corr) * 0.8), max(4, len(corr) * 0.75))
|
|
426
|
+
ax = figure.add_subplot(111)
|
|
427
|
+
image = ax.imshow(corr.to_numpy(dtype=float), cmap="RdBu_r", vmin=-1, vmax=1)
|
|
428
|
+
ax.set_xticks(range(len(corr.columns)), [str(c) for c in corr.columns], rotation=45, ha="right")
|
|
429
|
+
ax.set_yticks(range(len(corr.index)), [str(i) for i in corr.index])
|
|
430
|
+
for i in range(len(corr.index)):
|
|
431
|
+
for j in range(len(corr.columns)):
|
|
432
|
+
value = corr.iloc[i, j]
|
|
433
|
+
if pd.notna(value):
|
|
434
|
+
ax.text(j, i, f"{value:.2f}", ha="center", va="center", fontsize=8, color="white" if abs(value) > 0.6 else "#20242a")
|
|
435
|
+
figure.colorbar(image, ax=ax, fraction=0.046, pad=0.04)
|
|
436
|
+
ax.set_title(spec.title or "Correlation Matrix", fontsize=11, fontweight="bold")
|
|
437
|
+
return figure
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def pairplot(spec: PlotSpec):
|
|
441
|
+
data = frame(spec)
|
|
442
|
+
columns = spec.params.get("columns") or list(data.columns)
|
|
443
|
+
columns = [c for c in columns if c in data.columns]
|
|
444
|
+
n = len(columns)
|
|
445
|
+
bins = spec.params.get("bins", "auto")
|
|
446
|
+
figure = new_figure(max(6, n * 2.2), max(5, n * 2.0))
|
|
447
|
+
for row_index, y_name in enumerate(columns):
|
|
448
|
+
for col_index, x_name in enumerate(columns):
|
|
449
|
+
ax = figure.add_subplot(n, n, row_index * n + col_index + 1)
|
|
450
|
+
if row_index == col_index:
|
|
451
|
+
values = numeric(data, x_name).dropna()
|
|
452
|
+
ax.hist(values, bins=bins, color=color(0), alpha=0.85)
|
|
453
|
+
else:
|
|
454
|
+
ax.scatter(numeric(data, x_name), numeric(data, y_name), s=8, alpha=0.55, color=color(0))
|
|
455
|
+
if row_index == n - 1:
|
|
456
|
+
ax.set_xlabel(str(x_name), fontsize=8)
|
|
457
|
+
if col_index == 0:
|
|
458
|
+
ax.set_ylabel(str(y_name), fontsize=8)
|
|
459
|
+
ax.tick_params(labelsize=7)
|
|
460
|
+
figure.suptitle(spec.title or "Scatterplot Matrix", fontsize=12)
|
|
461
|
+
return figure
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def mosaic(spec: PlotSpec):
|
|
465
|
+
data = frame(spec)
|
|
466
|
+
row_name = spec.params["row"]
|
|
467
|
+
col_name = spec.params["column"]
|
|
468
|
+
table = pd.crosstab(data[row_name], data[col_name])
|
|
469
|
+
figure = new_figure()
|
|
470
|
+
ax = figure.add_subplot(111)
|
|
471
|
+
total = float(table.to_numpy().sum())
|
|
472
|
+
if total <= 0:
|
|
473
|
+
style_axes(ax, spec.title or f"{row_name} by {col_name}", str(row_name), "Proportion")
|
|
474
|
+
return figure
|
|
475
|
+
column_totals = table.sum(axis=0)
|
|
476
|
+
widths = (column_totals / total).to_numpy(dtype=float)
|
|
477
|
+
left = 0.0
|
|
478
|
+
for column_index, column_name in enumerate(table.columns):
|
|
479
|
+
width = float(widths[column_index])
|
|
480
|
+
if column_totals[column_name] > 0:
|
|
481
|
+
bottom = 0.0
|
|
482
|
+
for row_index, row_name_value in enumerate(table.index):
|
|
483
|
+
height = float(table.loc[row_name_value, column_name] / column_totals[column_name])
|
|
484
|
+
ax.bar(left, height, width=width, bottom=bottom, align="edge", color=color(row_index), alpha=0.9, label=str(row_name_value) if column_index == 0 else None)
|
|
485
|
+
bottom += height
|
|
486
|
+
ax.text(left + width / 2, 1.02, str(column_name), ha="center", va="bottom", fontsize=8)
|
|
487
|
+
left += width
|
|
488
|
+
ax.set_xlim(0, 1)
|
|
489
|
+
ax.set_ylim(0, 1.08)
|
|
490
|
+
ax.set_xticks([])
|
|
491
|
+
ax.legend(title=str(row_name), frameon=False, fontsize=8)
|
|
492
|
+
style_axes(ax, spec.title or f"{row_name} by {col_name}", str(col_name), "Proportion")
|
|
493
|
+
return figure
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def pareto(spec: PlotSpec):
|
|
497
|
+
data = frame(spec)
|
|
498
|
+
category = spec.params["category"]
|
|
499
|
+
count = spec.params["count"]
|
|
500
|
+
figure = new_figure()
|
|
501
|
+
ax = figure.add_subplot(111)
|
|
502
|
+
ordered = data.assign(__count=numeric(data, count)).sort_values("__count", ascending=False, kind="stable")
|
|
503
|
+
x = ordered[category].astype(str)
|
|
504
|
+
values = ordered["__count"].fillna(0)
|
|
505
|
+
ax.bar(x, values, color=color(0))
|
|
506
|
+
rotate_labels(ax)
|
|
507
|
+
style_axes(ax, spec.title or "Pareto Chart", str(category), "Count")
|
|
508
|
+
total = float(values.sum())
|
|
509
|
+
if total > 0:
|
|
510
|
+
cumulative = values.cumsum() / total * 100
|
|
511
|
+
ax2 = ax.twinx()
|
|
512
|
+
ax2.plot(x, cumulative, color=color(1), marker="o", linewidth=1.8)
|
|
513
|
+
ax2.set_ylabel("Cumulative Percent")
|
|
514
|
+
ax2.grid(False)
|
|
515
|
+
return figure
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def capability(spec: PlotSpec):
|
|
519
|
+
data = frame(spec)
|
|
520
|
+
name = spec.params["column"]
|
|
521
|
+
values = numeric(data, name).dropna()
|
|
522
|
+
lsl = spec.params.get("lsl")
|
|
523
|
+
usl = spec.params.get("usl")
|
|
524
|
+
target = spec.params.get("target")
|
|
525
|
+
figure = new_figure()
|
|
526
|
+
ax = figure.add_subplot(111)
|
|
527
|
+
ax.hist(values, bins=spec.params.get("bins", "auto"), density=True, color=color(0), alpha=0.75, edgecolor="white")
|
|
528
|
+
if len(values) > 2 and values.std() > 0:
|
|
529
|
+
xs = np.linspace(values.min(), values.max(), 300)
|
|
530
|
+
ax.plot(xs, stats.norm.pdf(xs, values.mean(), values.std(ddof=1)), color=color(1), linewidth=2)
|
|
531
|
+
for value, label, style in [(lsl, "LSL", "--"), (usl, "USL", "--"), (target, "Target", ":")]:
|
|
532
|
+
if value is not None:
|
|
533
|
+
ax.axvline(value, color="#333333", linestyle=style, linewidth=1.4)
|
|
534
|
+
ax.text(value, ax.get_ylim()[1] * 0.95, label, fontsize=8, ha="center")
|
|
535
|
+
style_axes(ax, spec.title or f"Process Capability: {name}", str(name), "Density")
|
|
536
|
+
return figure
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def control_chart(spec: PlotSpec):
|
|
540
|
+
data = frame(spec)
|
|
541
|
+
x_name = spec.params["x"]
|
|
542
|
+
y_name = spec.params["value"]
|
|
543
|
+
figure = new_figure()
|
|
544
|
+
ax = figure.add_subplot(111)
|
|
545
|
+
x = data[x_name]
|
|
546
|
+
y = numeric(data, y_name)
|
|
547
|
+
center_series = numeric(data, spec.params["center"])
|
|
548
|
+
ucl_series = numeric(data, spec.params["ucl"])
|
|
549
|
+
lcl_series = numeric(data, spec.params["lcl"])
|
|
550
|
+
|
|
551
|
+
def first_finite(series: pd.Series) -> float:
|
|
552
|
+
finite = series.dropna()
|
|
553
|
+
return float(finite.iloc[0]) if len(finite) else float("nan")
|
|
554
|
+
|
|
555
|
+
center = first_finite(center_series)
|
|
556
|
+
ucl = first_finite(ucl_series)
|
|
557
|
+
lcl = first_finite(lcl_series)
|
|
558
|
+
if pd.api.types.is_numeric_dtype(x):
|
|
559
|
+
positions = x.to_numpy(dtype=float)
|
|
560
|
+
else:
|
|
561
|
+
positions = np.arange(len(data), dtype=float)
|
|
562
|
+
ax.set_xticks(positions)
|
|
563
|
+
ax.set_xticklabels([str(v) for v in x])
|
|
564
|
+
ax.plot(positions, y, marker="o", color=color(0), linewidth=1.4, markersize=4)
|
|
565
|
+
variable = center_series.nunique(dropna=True) > 1 or ucl_series.nunique(dropna=True) > 1
|
|
566
|
+
if variable:
|
|
567
|
+
ax.step(positions, center_series, where="mid", color="#2e7d32", linewidth=1.3)
|
|
568
|
+
ax.step(positions, ucl_series, where="mid", color=color(1), linestyle="--", linewidth=1.3)
|
|
569
|
+
ax.step(positions, lcl_series, where="mid", color=color(1), linestyle="--", linewidth=1.3)
|
|
570
|
+
else:
|
|
571
|
+
if np.isfinite(center):
|
|
572
|
+
ax.axhline(center, color="#2e7d32", linewidth=1.3)
|
|
573
|
+
if np.isfinite(ucl):
|
|
574
|
+
ax.axhline(ucl, color=color(1), linestyle="--", linewidth=1.3)
|
|
575
|
+
if np.isfinite(lcl):
|
|
576
|
+
ax.axhline(lcl, color=color(1), linestyle="--", linewidth=1.3)
|
|
577
|
+
if "Phase" in data.columns:
|
|
578
|
+
phases = data["Phase"].astype(str).to_numpy()
|
|
579
|
+
for index in range(1, len(phases)):
|
|
580
|
+
if phases[index] != phases[index - 1]:
|
|
581
|
+
boundary = (positions[index - 1] + positions[index]) / 2
|
|
582
|
+
ax.axvline(boundary, color="#888888", linestyle=":", linewidth=1)
|
|
583
|
+
ax.text(boundary, ax.get_ylim()[1], phases[index], fontsize=7, va="top", ha="left", color="#666666")
|
|
584
|
+
status_name = spec.params.get("status", "Status")
|
|
585
|
+
status = data[status_name] if status_name in data.columns else None
|
|
586
|
+
if status is not None:
|
|
587
|
+
status_str = status.astype(str)
|
|
588
|
+
out_mask = (status_str == "out").to_numpy()
|
|
589
|
+
rule_mask = status_str.str.startswith("rule", na=False).to_numpy()
|
|
590
|
+
if out_mask.any():
|
|
591
|
+
ax.scatter(positions[out_mask], y.to_numpy()[out_mask], color=color(4), s=48, zorder=5, label="Out of control")
|
|
592
|
+
if rule_mask.any():
|
|
593
|
+
ax.scatter(positions[rule_mask], y.to_numpy()[rule_mask], color=color(6), s=48, zorder=5, label="Rule violation")
|
|
594
|
+
if out_mask.any() or rule_mask.any():
|
|
595
|
+
ax.legend(frameon=False, fontsize=8)
|
|
596
|
+
else:
|
|
597
|
+
if np.isfinite(ucl) and np.isfinite(lcl):
|
|
598
|
+
out = (y > ucl) | (y < lcl)
|
|
599
|
+
if out.any():
|
|
600
|
+
ax.scatter(positions[out.to_numpy()], y.to_numpy()[out.to_numpy()], color=color(4), s=45, zorder=5)
|
|
601
|
+
rotate_labels(ax)
|
|
602
|
+
style_axes(ax, spec.title or "Control Chart", str(x_name), str(y_name))
|
|
603
|
+
return figure
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
def survival(spec: PlotSpec):
|
|
607
|
+
data = frame(spec)
|
|
608
|
+
time_name = spec.params["time"]
|
|
609
|
+
survival_name = spec.params["survival"]
|
|
610
|
+
group_name = spec.params.get("group")
|
|
611
|
+
figure = new_figure()
|
|
612
|
+
ax = figure.add_subplot(111)
|
|
613
|
+
groups = data.groupby(group_name, dropna=False) if group_name and group_name in data.columns else [(None, data)]
|
|
614
|
+
for index, (label, chunk) in enumerate(groups):
|
|
615
|
+
chunk = chunk.assign(__time=numeric(chunk, time_name)).sort_values("__time", kind="stable")
|
|
616
|
+
x = numeric(chunk, time_name)
|
|
617
|
+
y = numeric(chunk, survival_name)
|
|
618
|
+
ax.step(x, y, where="post", color=color(index), linewidth=2, label=str(label) if label is not None else "All")
|
|
619
|
+
if "lower" in spec.params and "upper" in spec.params:
|
|
620
|
+
ax.fill_between(x, numeric(chunk, spec.params["lower"]), numeric(chunk, spec.params["upper"]), step="post", color=color(index), alpha=0.12)
|
|
621
|
+
if group_name:
|
|
622
|
+
ax.legend(title=str(group_name), frameon=False, fontsize=8)
|
|
623
|
+
style_axes(ax, spec.title or "Kaplan-Meier Survival", "Time", "Survival Probability")
|
|
624
|
+
return figure
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
def forecast(spec: PlotSpec):
|
|
628
|
+
data = frame(spec)
|
|
629
|
+
x_name = spec.params["x"]
|
|
630
|
+
actual_name = spec.params["actual"]
|
|
631
|
+
forecast_name = spec.params["forecast"]
|
|
632
|
+
figure = new_figure()
|
|
633
|
+
ax = figure.add_subplot(111)
|
|
634
|
+
x = data[x_name].astype(str)
|
|
635
|
+
actual = pd.to_numeric(data[actual_name], errors="coerce")
|
|
636
|
+
predicted = pd.to_numeric(data[forecast_name], errors="coerce")
|
|
637
|
+
ax.plot(x, actual, color=color(0), linewidth=1.8, label="Actual", marker="o", markersize=3)
|
|
638
|
+
ax.plot(x, predicted, color=color(1), linewidth=1.8, label="Forecast", marker="o", markersize=3)
|
|
639
|
+
if "lower" in spec.params and "upper" in spec.params:
|
|
640
|
+
lower = pd.to_numeric(data[spec.params["lower"]], errors="coerce")
|
|
641
|
+
upper = pd.to_numeric(data[spec.params["upper"]], errors="coerce")
|
|
642
|
+
ax.fill_between(range(len(x)), lower, upper, color=color(1), alpha=0.15)
|
|
643
|
+
step = max(1, len(x) // 12)
|
|
644
|
+
ax.set_xticks(range(0, len(x), step), [x.iloc[i] for i in range(0, len(x), step)], rotation=45, ha="right")
|
|
645
|
+
ax.legend(frameon=False)
|
|
646
|
+
style_axes(ax, spec.title or "Forecast", str(x_name), "Value")
|
|
647
|
+
return figure
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
def decomposition(spec: PlotSpec):
|
|
651
|
+
data = frame(spec)
|
|
652
|
+
x = data["Index"] if "Index" in data.columns else range(len(data))
|
|
653
|
+
figure = new_figure(8, 7)
|
|
654
|
+
components = ["Observed", "Trend", "Seasonal", "Residual"]
|
|
655
|
+
for index, component in enumerate(components):
|
|
656
|
+
ax = figure.add_subplot(len(components), 1, index + 1)
|
|
657
|
+
if component in data.columns:
|
|
658
|
+
ax.plot(x, numeric(data, component), color=color(index), linewidth=1.4)
|
|
659
|
+
ax.set_ylabel(component, fontsize=9)
|
|
660
|
+
ax.tick_params(labelsize=7)
|
|
661
|
+
if index == 0:
|
|
662
|
+
ax.set_title(spec.title or "Seasonal Decomposition", fontsize=11, fontweight="bold")
|
|
663
|
+
return figure
|
|
664
|
+
|
|
665
|
+
|
|
666
|
+
def acf_pacf(spec: PlotSpec):
|
|
667
|
+
lags = spec.params.get("lags") or []
|
|
668
|
+
acf_values = spec.params.get("acf") or []
|
|
669
|
+
pacf_values = spec.params.get("pacf") or []
|
|
670
|
+
figure = new_figure(8, 4)
|
|
671
|
+
ax1 = figure.add_subplot(1, 2, 1)
|
|
672
|
+
if lags and acf_values:
|
|
673
|
+
ax1.vlines(lags[: len(acf_values)], 0, acf_values, color=color(0), linewidth=1.8)
|
|
674
|
+
ax1.axhline(0, color="#333333", linewidth=0.8)
|
|
675
|
+
style_axes(ax1, "Autocorrelation", "Lag", "ACF")
|
|
676
|
+
ax2 = figure.add_subplot(1, 2, 2)
|
|
677
|
+
if lags and pacf_values:
|
|
678
|
+
ax2.vlines(lags[: len(pacf_values)], 0, pacf_values, color=color(1), linewidth=1.8)
|
|
679
|
+
ax2.axhline(0, color="#333333", linewidth=0.8)
|
|
680
|
+
style_axes(ax2, "Partial Autocorrelation", "Lag", "PACF")
|
|
681
|
+
return figure
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
def density(spec: PlotSpec):
|
|
685
|
+
data = frame(spec)
|
|
686
|
+
name = spec.params.get("column") or spec.params.get("x")
|
|
687
|
+
group_name = spec.params.get("group")
|
|
688
|
+
bins = spec.params.get("bins", "auto")
|
|
689
|
+
figure = new_figure()
|
|
690
|
+
ax = figure.add_subplot(111)
|
|
691
|
+
if group_name and group_name in data.columns:
|
|
692
|
+
plotted = False
|
|
693
|
+
for index, (label, chunk) in enumerate(data.groupby(group_name, dropna=False, sort=True)):
|
|
694
|
+
values = numeric(chunk, name).dropna()
|
|
695
|
+
if len(values) > 1 and values.nunique(dropna=True) > 1:
|
|
696
|
+
values.plot.kde(ax=ax, color=color(index), label=str(label))
|
|
697
|
+
plotted = True
|
|
698
|
+
if not plotted:
|
|
699
|
+
all_values = numeric(data, name).dropna()
|
|
700
|
+
if len(all_values):
|
|
701
|
+
ax.hist(all_values, bins=bins, density=True, color=color(0), alpha=0.4)
|
|
702
|
+
else:
|
|
703
|
+
ax.legend(title=str(group_name), frameon=False, fontsize=8)
|
|
704
|
+
else:
|
|
705
|
+
values = numeric(data, name).dropna()
|
|
706
|
+
if len(values) > 1 and values.nunique(dropna=True) > 1:
|
|
707
|
+
values.plot.kde(ax=ax, color=color(0))
|
|
708
|
+
elif len(values):
|
|
709
|
+
ax.hist(values, bins=bins, density=True, color=color(0), alpha=0.4)
|
|
710
|
+
style_axes(ax, spec.title or f"Density of {name}", str(name), "Density")
|
|
711
|
+
return figure
|
|
712
|
+
|
|
713
|
+
|
|
714
|
+
def _apply_options(ax, spec: PlotSpec, data=None, x_name=None, y_name=None):
|
|
715
|
+
params = spec.params
|
|
716
|
+
x_scale = params.get("x_scale") or ("log" if params.get("log_x") else None)
|
|
717
|
+
y_scale = params.get("y_scale") or ("log" if params.get("log_y") else None)
|
|
718
|
+
if x_scale in {"log", "linear"}:
|
|
719
|
+
ax.set_xscale(x_scale)
|
|
720
|
+
if y_scale in {"log", "linear"}:
|
|
721
|
+
ax.set_yscale(y_scale)
|
|
722
|
+
for value in params.get("ref_lines") or []:
|
|
723
|
+
try:
|
|
724
|
+
line = ax.axhline(float(value), color="#666666", linestyle="--", linewidth=1)
|
|
725
|
+
line._statstudio_reference = True
|
|
726
|
+
except (TypeError, ValueError):
|
|
727
|
+
continue
|
|
728
|
+
for value in params.get("ref_lines_x") or []:
|
|
729
|
+
try:
|
|
730
|
+
line = ax.axvline(float(value), color="#666666", linestyle=":", linewidth=1)
|
|
731
|
+
line._statstudio_reference = True
|
|
732
|
+
except (TypeError, ValueError):
|
|
733
|
+
continue
|
|
734
|
+
for annotation in params.get("annotations") or []:
|
|
735
|
+
if not isinstance(annotation, dict):
|
|
736
|
+
continue
|
|
737
|
+
try:
|
|
738
|
+
ax.annotate(str(annotation.get("text", "")), xy=(float(annotation.get("x")), float(annotation.get("y"))), xytext=(5, 5), textcoords="offset points", fontsize=8, color="#333333")
|
|
739
|
+
except (TypeError, ValueError):
|
|
740
|
+
continue
|
|
741
|
+
if params.get("smooth") and data is not None and x_name and y_name and x_name in data.columns and y_name in data.columns:
|
|
742
|
+
if pd.api.types.is_datetime64_any_dtype(data[x_name]):
|
|
743
|
+
x = pd.Series(mdates.date2num(pd.to_datetime(data[x_name])), index=data.index)
|
|
744
|
+
else:
|
|
745
|
+
x = pd.to_numeric(data[x_name], errors="coerce")
|
|
746
|
+
y = pd.to_numeric(data[y_name], errors="coerce")
|
|
747
|
+
mask = x.notna() & y.notna()
|
|
748
|
+
if mask.sum() > 1 and x[mask].nunique() > 1:
|
|
749
|
+
method = str(params.get("smooth_method") or "linear").lower()
|
|
750
|
+
x_values = x[mask].to_numpy(dtype=float)
|
|
751
|
+
y_values = y[mask].to_numpy(dtype=float)
|
|
752
|
+
order = np.argsort(x_values)
|
|
753
|
+
x_values = x_values[order]
|
|
754
|
+
y_values = y_values[order]
|
|
755
|
+
if method in {"lowess", "loess"}:
|
|
756
|
+
try:
|
|
757
|
+
from statsmodels.nonparametric.smoothers_lowess import lowess as lowess_smooth
|
|
758
|
+
|
|
759
|
+
smoothed = lowess_smooth(y_values, x_values, frac=min(0.8, max(0.2, 20 / len(x_values))), return_sorted=True)
|
|
760
|
+
ax.plot(smoothed[:, 0], smoothed[:, 1], color=color(1), linewidth=2, label="LOWESS")
|
|
761
|
+
except Exception:
|
|
762
|
+
method = "linear"
|
|
763
|
+
if method in {"spline", "p-spline", "pspline"}:
|
|
764
|
+
try:
|
|
765
|
+
from scipy.interpolate import UnivariateSpline
|
|
766
|
+
|
|
767
|
+
spline = UnivariateSpline(x_values, y_values, k=3, s=len(x_values) * float(np.var(y_values)) * 0.1)
|
|
768
|
+
xs = np.linspace(float(x_values.min()), float(x_values.max()), 200)
|
|
769
|
+
ax.plot(xs, spline(xs), color=color(1), linewidth=2, label="Spline")
|
|
770
|
+
except Exception:
|
|
771
|
+
method = "linear"
|
|
772
|
+
if method in {"moving average", "moving-average", "ma"}:
|
|
773
|
+
window = max(3, min(len(x_values) // 8, 25))
|
|
774
|
+
series = pd.Series(y_values).rolling(window=window, center=True, min_periods=1).mean()
|
|
775
|
+
ax.plot(x_values, series, color=color(1), linewidth=2, label=f"Moving average ({window})")
|
|
776
|
+
if method == "linear":
|
|
777
|
+
coefficients = np.polyfit(x_values, y_values, 1)
|
|
778
|
+
xs = np.linspace(float(x_values.min()), float(x_values.max()), 100)
|
|
779
|
+
ax.plot(xs, np.polyval(coefficients, xs), color=color(1), linewidth=2, label="Linear fit")
|
|
780
|
+
ax.legend(frameon=False, fontsize=8)
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
def _add_secondary(
|
|
784
|
+
ax,
|
|
785
|
+
spec: PlotSpec,
|
|
786
|
+
data: pd.DataFrame,
|
|
787
|
+
x_name: str,
|
|
788
|
+
categories: list[str] | None = None,
|
|
789
|
+
):
|
|
790
|
+
y2_name = spec.params.get("y2")
|
|
791
|
+
if not y2_name or y2_name not in data.columns:
|
|
792
|
+
return None
|
|
793
|
+
show_line = bool(spec.params.get("y2_show_line", True))
|
|
794
|
+
show_points = bool(spec.params.get("y2_show_points", True))
|
|
795
|
+
ax2 = ax.twinx()
|
|
796
|
+
if not show_line and not show_points:
|
|
797
|
+
ax2.set_visible(False)
|
|
798
|
+
return ax2
|
|
799
|
+
style = {
|
|
800
|
+
"color": spec.params.get("y2_color") or color(1),
|
|
801
|
+
"linewidth": _float_param(spec.params, "y2_line_width", 1.8),
|
|
802
|
+
"linestyle": "-" if show_line else "None",
|
|
803
|
+
"marker": "o" if show_points else None,
|
|
804
|
+
"markersize": _float_param(spec.params, "y2_marker_size", 5),
|
|
805
|
+
"label": str(y2_name),
|
|
806
|
+
}
|
|
807
|
+
numeric_y = pd.to_numeric(data[y2_name], errors="coerce")
|
|
808
|
+
if categories is not None:
|
|
809
|
+
keys = data[x_name].fillna("(missing)").astype(str)
|
|
810
|
+
secondary = numeric_y.groupby(keys).sum().reindex(categories)
|
|
811
|
+
ax2.plot(
|
|
812
|
+
np.arange(len(categories), dtype=float),
|
|
813
|
+
secondary.to_numpy(dtype=float),
|
|
814
|
+
**style,
|
|
815
|
+
)
|
|
816
|
+
elif _is_date_like(data[x_name]):
|
|
817
|
+
datetime_x = _to_datetime(data[x_name])
|
|
818
|
+
order = np.argsort(datetime_x.to_numpy())
|
|
819
|
+
ax2.plot(datetime_x.iloc[order], numeric_y.iloc[order], **style)
|
|
820
|
+
else:
|
|
821
|
+
numeric_x = pd.to_numeric(data[x_name], errors="coerce")
|
|
822
|
+
if numeric_x.notna().sum() == len(numeric_x):
|
|
823
|
+
order = np.argsort(numeric_x.to_numpy(dtype=float), kind="stable")
|
|
824
|
+
ax2.plot(numeric_x.iloc[order], numeric_y.iloc[order], **style)
|
|
825
|
+
else:
|
|
826
|
+
ax2.plot(data[x_name], numeric_y, **style)
|
|
827
|
+
ax2.set_ylabel(str(y2_name))
|
|
828
|
+
ax2.grid(False)
|
|
829
|
+
handles, labels = ax.get_legend_handles_labels()
|
|
830
|
+
handles2, labels2 = ax2.get_legend_handles_labels()
|
|
831
|
+
if labels2:
|
|
832
|
+
ax.legend(handles + handles2, labels + labels2, frameon=False, fontsize=8)
|
|
833
|
+
return ax2
|
|
834
|
+
|
|
835
|
+
|
|
836
|
+
def violin(spec: PlotSpec):
|
|
837
|
+
data = frame(spec)
|
|
838
|
+
value_name = spec.params.get("column") or spec.params.get("y")
|
|
839
|
+
group_name = spec.params.get("group") or spec.params.get("x")
|
|
840
|
+
figure = new_figure()
|
|
841
|
+
ax = figure.add_subplot(111)
|
|
842
|
+
if group_name and group_name in data.columns:
|
|
843
|
+
groups, labels = [], []
|
|
844
|
+
for label, chunk in data.groupby(group_name, dropna=False, sort=True):
|
|
845
|
+
values = numeric(chunk, value_name).dropna()
|
|
846
|
+
if len(values) > 1:
|
|
847
|
+
groups.append(values.to_numpy())
|
|
848
|
+
labels.append("Missing" if pd.isna(label) else str(label))
|
|
849
|
+
if groups:
|
|
850
|
+
parts = ax.violinplot(groups, showmeans=True, showextrema=False)
|
|
851
|
+
for index, body in enumerate(parts["bodies"]):
|
|
852
|
+
body.set_facecolor(color(index))
|
|
853
|
+
body.set_edgecolor("#333333")
|
|
854
|
+
body.set_alpha(0.7)
|
|
855
|
+
ax.set_xticks(range(1, len(labels) + 1), labels)
|
|
856
|
+
rotate_labels(ax)
|
|
857
|
+
style_axes(ax, spec.title or f"{value_name} by {group_name}", str(group_name), str(value_name))
|
|
858
|
+
else:
|
|
859
|
+
values = numeric(data, value_name).dropna()
|
|
860
|
+
if len(values) > 1:
|
|
861
|
+
parts = ax.violinplot([values], showmeans=True, showextrema=False)
|
|
862
|
+
for body in parts["bodies"]:
|
|
863
|
+
body.set_facecolor(color(0))
|
|
864
|
+
body.set_alpha(0.7)
|
|
865
|
+
style_axes(ax, spec.title or f"Distribution of {value_name}", "", str(value_name))
|
|
866
|
+
_apply_options(ax, spec)
|
|
867
|
+
return figure
|
|
868
|
+
|
|
869
|
+
|
|
870
|
+
def strip(spec: PlotSpec):
|
|
871
|
+
data = frame(spec)
|
|
872
|
+
value_name = spec.params.get("column") or spec.params.get("y")
|
|
873
|
+
group_name = spec.params.get("group") or spec.params.get("x")
|
|
874
|
+
rng = np.random.default_rng(0)
|
|
875
|
+
figure = new_figure()
|
|
876
|
+
ax = figure.add_subplot(111)
|
|
877
|
+
if group_name and group_name in data.columns:
|
|
878
|
+
labels = []
|
|
879
|
+
for index, (label, chunk) in enumerate(data.groupby(group_name, dropna=False, sort=True)):
|
|
880
|
+
values = numeric(chunk, value_name).dropna()
|
|
881
|
+
jitter = rng.uniform(-0.18, 0.18, len(values))
|
|
882
|
+
ax.scatter(index + 1 + jitter, values, s=26, alpha=0.75, color=color(index))
|
|
883
|
+
labels.append("Missing" if pd.isna(label) else str(label))
|
|
884
|
+
ax.set_xticks(range(1, len(labels) + 1))
|
|
885
|
+
ax.set_xticklabels(labels)
|
|
886
|
+
rotate_labels(ax)
|
|
887
|
+
style_axes(ax, spec.title or f"{value_name} by {group_name}", str(group_name), str(value_name))
|
|
888
|
+
else:
|
|
889
|
+
values = numeric(data, value_name).dropna()
|
|
890
|
+
jitter = rng.uniform(-0.18, 0.18, len(values))
|
|
891
|
+
ax.scatter(jitter, values, s=26, alpha=0.75, color=color(0))
|
|
892
|
+
style_axes(ax, spec.title or f"Strip Plot: {value_name}", "", str(value_name))
|
|
893
|
+
_apply_options(ax, spec)
|
|
894
|
+
return figure
|
|
895
|
+
|
|
896
|
+
|
|
897
|
+
def sixpack(spec: PlotSpec):
|
|
898
|
+
data = frame(spec)
|
|
899
|
+
name = spec.params["column"]
|
|
900
|
+
values = numeric(data, name).dropna()
|
|
901
|
+
lsl = spec.params.get("lsl")
|
|
902
|
+
usl = spec.params.get("usl")
|
|
903
|
+
target = spec.params.get("target")
|
|
904
|
+
figure = new_figure(9, 6)
|
|
905
|
+
figure.suptitle(spec.title or f"Six-Pack: {name}", fontsize=12)
|
|
906
|
+
ax = figure.add_subplot(2, 3, 1)
|
|
907
|
+
ax.hist(values, bins=spec.params.get("bins", "auto"), density=True, color=color(0), alpha=0.75, edgecolor="white")
|
|
908
|
+
if len(values) > 2 and values.std() > 0:
|
|
909
|
+
xs = np.linspace(values.min(), values.max(), 300)
|
|
910
|
+
ax.plot(xs, stats.norm.pdf(xs, values.mean(), values.std(ddof=1)), color=color(1), linewidth=2)
|
|
911
|
+
for value, label, style in [(lsl, "LSL", "--"), (usl, "USL", "--"), (target, "Target", ":")]:
|
|
912
|
+
if value is not None:
|
|
913
|
+
ax.axvline(value, color="#333333", linestyle=style, linewidth=1.1)
|
|
914
|
+
style_axes(ax, "Histogram", str(name), "Density")
|
|
915
|
+
|
|
916
|
+
ax = figure.add_subplot(2, 3, 2)
|
|
917
|
+
ax.plot(np.arange(1, len(values) + 1), values, marker="o", markersize=3, color=color(0), linewidth=1.1)
|
|
918
|
+
ax.axhline(float(values.mean()), color="#2e7d32", linewidth=1.2)
|
|
919
|
+
style_axes(ax, "Run Chart", "Observation", str(name))
|
|
920
|
+
|
|
921
|
+
ax = figure.add_subplot(2, 3, 3)
|
|
922
|
+
ax.boxplot(values, orientation="vertical", patch_artist=True, boxprops={"facecolor": color(0), "alpha": 0.5})
|
|
923
|
+
style_axes(ax, "Box Plot", "", "")
|
|
924
|
+
|
|
925
|
+
ax = figure.add_subplot(2, 3, 4)
|
|
926
|
+
if len(values) > 2:
|
|
927
|
+
stats.probplot(values, dist="norm", plot=ax)
|
|
928
|
+
style_axes(ax, "Normal Probability Plot", "Theoretical Quantiles", "Ordered Values")
|
|
929
|
+
|
|
930
|
+
ax = figure.add_subplot(2, 3, 5)
|
|
931
|
+
moving = values.diff().abs().dropna()
|
|
932
|
+
ax.plot(np.arange(1, len(moving) + 1), moving, marker="o", markersize=3, color=color(1), linewidth=1.1)
|
|
933
|
+
if len(moving):
|
|
934
|
+
ax.axhline(float(moving.mean()), color="#2e7d32", linewidth=1.2)
|
|
935
|
+
style_axes(ax, "Moving Range", "Observation", "Moving Range")
|
|
936
|
+
|
|
937
|
+
ax = figure.add_subplot(2, 3, 6)
|
|
938
|
+
columns = ["Metric", "Value"]
|
|
939
|
+
rows = [
|
|
940
|
+
("N", len(values)),
|
|
941
|
+
("Mean", float(values.mean()) if len(values) else np.nan),
|
|
942
|
+
("Std Dev", float(values.std(ddof=1)) if len(values) > 1 else np.nan),
|
|
943
|
+
("Min", float(values.min()) if len(values) else np.nan),
|
|
944
|
+
("Median", float(values.median()) if len(values) else np.nan),
|
|
945
|
+
("Max", float(values.max()) if len(values) else np.nan),
|
|
946
|
+
]
|
|
947
|
+
if lsl is not None and usl is not None and len(values) > 1 and values.std() > 0:
|
|
948
|
+
cp = (usl - lsl) / (6 * values.std(ddof=1))
|
|
949
|
+
cpk = min((usl - values.mean()) / (3 * values.std(ddof=1)), (values.mean() - lsl) / (3 * values.std(ddof=1)))
|
|
950
|
+
rows.extend([("Cp", float(cp)), ("Cpk", float(cpk))])
|
|
951
|
+
ax.axis("off")
|
|
952
|
+
table = ax.table(cellText=[[k, f"{v:.6g}" if isinstance(v, (int, float, np.floating)) else str(v)] for k, v in rows], colLabels=columns, loc="center")
|
|
953
|
+
table.auto_set_font_size(False)
|
|
954
|
+
table.set_fontsize(8)
|
|
955
|
+
table.scale(1, 1.3)
|
|
956
|
+
ax.set_title("Summary", fontsize=10)
|
|
957
|
+
return figure
|