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,651 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
from matplotlib.cm import ScalarMappable
|
|
8
|
+
from matplotlib.colors import Normalize
|
|
9
|
+
from scipy import stats
|
|
10
|
+
|
|
11
|
+
from statstudio.plots.common import (
|
|
12
|
+
attach_row_ids,
|
|
13
|
+
color,
|
|
14
|
+
frame,
|
|
15
|
+
new_figure,
|
|
16
|
+
numeric,
|
|
17
|
+
rotate_labels,
|
|
18
|
+
row_ids_for,
|
|
19
|
+
style_axes,
|
|
20
|
+
)
|
|
21
|
+
from statstudio.stats.results import PlotSpec
|
|
22
|
+
|
|
23
|
+
_ERROR_ALIASES = {
|
|
24
|
+
"sd": "sd",
|
|
25
|
+
"standard deviation": "sd",
|
|
26
|
+
"std": "sd",
|
|
27
|
+
"se": "se",
|
|
28
|
+
"standard error": "se",
|
|
29
|
+
"sem": "se",
|
|
30
|
+
"ci": "ci",
|
|
31
|
+
"95% ci": "ci",
|
|
32
|
+
"confidence interval": "ci",
|
|
33
|
+
"range": "range",
|
|
34
|
+
"none": "none",
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _ordered_levels(values: pd.Series) -> list:
|
|
39
|
+
present = list(pd.unique(values.dropna()))
|
|
40
|
+
try:
|
|
41
|
+
return sorted(present)
|
|
42
|
+
except TypeError:
|
|
43
|
+
return sorted(present, key=lambda item: str(item))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _level_label(value) -> str:
|
|
47
|
+
return "(missing)" if pd.isna(value) else str(value)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _nested_levels(data: pd.DataFrame, columns: list[str]) -> list[str]:
|
|
51
|
+
unique = data[columns].drop_duplicates()
|
|
52
|
+
try:
|
|
53
|
+
unique = unique.sort_values(by=columns, kind="stable", na_position="last")
|
|
54
|
+
except TypeError:
|
|
55
|
+
unique = unique.assign(**{column: unique[column].astype(str) for column in columns})
|
|
56
|
+
unique = unique.sort_values(by=columns, kind="stable", na_position="last")
|
|
57
|
+
return [" / ".join(_level_label(value) for value in row) for row in unique.itertuples(index=False, name=None)]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _group_chunks(data: pd.DataFrame, group_name: str | None) -> list[tuple[str, pd.DataFrame]]:
|
|
61
|
+
if not group_name or group_name not in data.columns:
|
|
62
|
+
return [("All", data)]
|
|
63
|
+
chunks = []
|
|
64
|
+
for label, chunk in data.groupby(group_name, dropna=False, sort=True):
|
|
65
|
+
chunks.append(("Missing" if pd.isna(label) else str(label), chunk))
|
|
66
|
+
return chunks
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _error_bars(values: np.ndarray, kind: str) -> tuple[float, float] | None:
|
|
70
|
+
count = len(values)
|
|
71
|
+
if count == 0 or kind == "none":
|
|
72
|
+
return None
|
|
73
|
+
mean = float(np.mean(values))
|
|
74
|
+
if kind == "range":
|
|
75
|
+
return mean - float(np.min(values)), float(np.max(values)) - mean
|
|
76
|
+
if count < 2:
|
|
77
|
+
return None
|
|
78
|
+
deviation = float(np.std(values, ddof=1))
|
|
79
|
+
if kind == "ci":
|
|
80
|
+
deviation = float(stats.t.ppf(0.975, count - 1) * deviation / math.sqrt(count))
|
|
81
|
+
elif kind == "se":
|
|
82
|
+
deviation = float(deviation / math.sqrt(count))
|
|
83
|
+
if not np.isfinite(deviation):
|
|
84
|
+
return None
|
|
85
|
+
return deviation, deviation
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def variability(spec: PlotSpec):
|
|
89
|
+
data = frame(spec)
|
|
90
|
+
x_param = spec.params.get("x") or spec.params.get("column")
|
|
91
|
+
x_names = [str(column) for column in x_param] if isinstance(x_param, (list, tuple)) else ([str(x_param)] if x_param else [])
|
|
92
|
+
y_name = spec.params.get("y") or spec.params.get("column")
|
|
93
|
+
group_name = spec.params.get("group")
|
|
94
|
+
error_kind = _ERROR_ALIASES.get(str(spec.params.get("error", "sd")).strip().lower(), "sd")
|
|
95
|
+
x_display = " / ".join(x_names)
|
|
96
|
+
figure = new_figure(max(7.0, 0.9 * max(1, len(x_names))))
|
|
97
|
+
ax = figure.add_subplot(111)
|
|
98
|
+
if not x_names or not y_name or any(column not in data.columns for column in x_names) or y_name not in data.columns:
|
|
99
|
+
style_axes(ax, spec.title or "Variability Chart", x_display, str(y_name or ""))
|
|
100
|
+
return figure
|
|
101
|
+
values = numeric(data, y_name)
|
|
102
|
+
valid = data[x_names].notna().all(axis=1) & values.notna()
|
|
103
|
+
clean = data.loc[valid].copy()
|
|
104
|
+
clean["__value__"] = values.loc[valid]
|
|
105
|
+
levels = _nested_levels(clean, x_names)
|
|
106
|
+
if not levels:
|
|
107
|
+
style_axes(ax, spec.title or f"Variability of {y_name} by {x_display}", x_display, str(y_name))
|
|
108
|
+
return figure
|
|
109
|
+
clean["__level__"] = clean[x_names].apply(
|
|
110
|
+
lambda row: " / ".join(_level_label(value) for value in row), axis=1
|
|
111
|
+
)
|
|
112
|
+
positions = {level: index for index, level in enumerate(levels)}
|
|
113
|
+
figure.set_size_inches(max(7.0, 0.9 * len(levels)), figure.get_size_inches()[1])
|
|
114
|
+
rng = np.random.default_rng(0)
|
|
115
|
+
overall = float(clean["__value__"].mean())
|
|
116
|
+
ax.axhline(overall, color="#8a93a0", linestyle="--", linewidth=1, label="Overall mean")
|
|
117
|
+
for group_index, (group_label, chunk) in enumerate(_group_chunks(clean, group_name)):
|
|
118
|
+
colour = color(group_index)
|
|
119
|
+
offsets = rng.uniform(-0.14, 0.14, len(chunk))
|
|
120
|
+
xs = chunk["__level__"].map(positions).to_numpy(dtype=float) + offsets
|
|
121
|
+
ax.scatter(xs, chunk["__value__"].to_numpy(dtype=float), s=18, alpha=0.45, color=colour, linewidths=0)
|
|
122
|
+
means = []
|
|
123
|
+
mean_positions = []
|
|
124
|
+
for level in levels:
|
|
125
|
+
subset = chunk.loc[chunk["__level__"] == level, "__value__"].to_numpy(dtype=float)
|
|
126
|
+
if not len(subset):
|
|
127
|
+
continue
|
|
128
|
+
mean = float(np.mean(subset))
|
|
129
|
+
mean_positions.append(positions[level])
|
|
130
|
+
means.append(mean)
|
|
131
|
+
bars = _error_bars(subset, error_kind)
|
|
132
|
+
if bars is not None:
|
|
133
|
+
ax.errorbar(
|
|
134
|
+
positions[level],
|
|
135
|
+
mean,
|
|
136
|
+
yerr=np.array(bars).reshape(2, 1),
|
|
137
|
+
fmt="none",
|
|
138
|
+
ecolor=colour,
|
|
139
|
+
elinewidth=1.2,
|
|
140
|
+
capsize=4,
|
|
141
|
+
alpha=0.9,
|
|
142
|
+
)
|
|
143
|
+
ax.plot(positions[level], mean, marker="D", markersize=5, color=colour, markeredgecolor="white")
|
|
144
|
+
if len(mean_positions) > 1:
|
|
145
|
+
ax.plot(mean_positions, means, color=colour, linewidth=1.4, alpha=0.8)
|
|
146
|
+
if group_name:
|
|
147
|
+
ax.plot([], [], color=colour, marker="D", linewidth=1.4, label=group_label)
|
|
148
|
+
ax.set_xticks(range(len(levels)), levels)
|
|
149
|
+
rotate_labels(ax, 90, "center")
|
|
150
|
+
if group_name:
|
|
151
|
+
ax.legend(title=str(group_name), frameon=False, fontsize=8)
|
|
152
|
+
style_axes(ax, spec.title or f"Variability of {y_name} by {x_display}", x_display, str(y_name))
|
|
153
|
+
return figure
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def scatter3d(spec: PlotSpec):
|
|
157
|
+
data = frame(spec)
|
|
158
|
+
x_name = spec.params.get("x")
|
|
159
|
+
y_name = spec.params.get("y")
|
|
160
|
+
z_name = spec.params.get("z")
|
|
161
|
+
group_name = spec.params.get("group")
|
|
162
|
+
size_name = spec.params.get("size")
|
|
163
|
+
figure = new_figure(7.0, 5.5)
|
|
164
|
+
ax = figure.add_subplot(111, projection="3d")
|
|
165
|
+
if not x_name or not y_name or not z_name:
|
|
166
|
+
ax.set_title(spec.title or "3D Scatter Plot", fontsize=11, fontweight="bold")
|
|
167
|
+
return figure
|
|
168
|
+
missing = [name for name in (x_name, y_name, z_name) if name not in data.columns]
|
|
169
|
+
if missing:
|
|
170
|
+
ax.set_title(spec.title or "3D Scatter Plot", fontsize=11, fontweight="bold")
|
|
171
|
+
return figure
|
|
172
|
+
clean = pd.DataFrame(
|
|
173
|
+
{
|
|
174
|
+
"x": numeric(data, x_name),
|
|
175
|
+
"y": numeric(data, y_name),
|
|
176
|
+
"z": numeric(data, z_name),
|
|
177
|
+
}
|
|
178
|
+
)
|
|
179
|
+
if size_name and size_name in data.columns:
|
|
180
|
+
clean["size"] = numeric(data, size_name).abs()
|
|
181
|
+
if group_name and group_name in data.columns:
|
|
182
|
+
clean["group"] = data[group_name].reset_index(drop=True)
|
|
183
|
+
clean = clean.dropna(subset=["x", "y", "z"]).reset_index(drop=True)
|
|
184
|
+
if clean.empty:
|
|
185
|
+
ax.set_title(spec.title or "3D Scatter Plot", fontsize=11, fontweight="bold")
|
|
186
|
+
return figure
|
|
187
|
+
sizes = None
|
|
188
|
+
if "size" in clean.columns:
|
|
189
|
+
finite = clean["size"].dropna()
|
|
190
|
+
if len(finite) and float(finite.max()) > float(finite.min()):
|
|
191
|
+
scaled = (clean["size"] - float(finite.min())) / (float(finite.max()) - float(finite.min()))
|
|
192
|
+
sizes = 20 + 160 * scaled.fillna(0.0).to_numpy(dtype=float)
|
|
193
|
+
if "group" in clean.columns:
|
|
194
|
+
for index, (label, chunk) in enumerate(clean.groupby("group", dropna=False, sort=True)):
|
|
195
|
+
chunk_sizes = None
|
|
196
|
+
if sizes is not None:
|
|
197
|
+
chunk_sizes = sizes[chunk.index.to_numpy()]
|
|
198
|
+
ax.scatter(
|
|
199
|
+
chunk["x"],
|
|
200
|
+
chunk["y"],
|
|
201
|
+
chunk["z"],
|
|
202
|
+
s=chunk_sizes if chunk_sizes is not None else 36,
|
|
203
|
+
alpha=0.78,
|
|
204
|
+
color=color(index),
|
|
205
|
+
label="Missing" if pd.isna(label) else str(label),
|
|
206
|
+
depthshade=True,
|
|
207
|
+
)
|
|
208
|
+
ax.legend(title=str(group_name), frameon=False, fontsize=8)
|
|
209
|
+
else:
|
|
210
|
+
ax.scatter(clean["x"], clean["y"], clean["z"], s=sizes if sizes is not None else 36, alpha=0.78, color=color(0), depthshade=True)
|
|
211
|
+
ax.set_xlabel(str(x_name))
|
|
212
|
+
ax.set_ylabel(str(y_name))
|
|
213
|
+
ax.set_zlabel(str(z_name))
|
|
214
|
+
ax.set_title(spec.title or f"{z_name} vs {x_name} and {y_name}", fontsize=11, fontweight="bold")
|
|
215
|
+
ax.view_init(elev=float(spec.params.get("elev", 22)), azim=float(spec.params.get("azim", -60)))
|
|
216
|
+
try:
|
|
217
|
+
ax.mouse_init()
|
|
218
|
+
except Exception:
|
|
219
|
+
pass
|
|
220
|
+
ax.grid(True, color="#e4e8ee", linewidth=0.7, alpha=0.8)
|
|
221
|
+
return figure
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _clean_xyz(data: pd.DataFrame, x_name: str, y_name: str, z_name: str, group_name: str | None = None, size_name: str | None = None) -> pd.DataFrame:
|
|
225
|
+
clean = pd.DataFrame(
|
|
226
|
+
{
|
|
227
|
+
"x": numeric(data, x_name),
|
|
228
|
+
"y": numeric(data, y_name),
|
|
229
|
+
"z": numeric(data, z_name),
|
|
230
|
+
}
|
|
231
|
+
)
|
|
232
|
+
if size_name and size_name in data.columns:
|
|
233
|
+
clean["size"] = numeric(data, size_name).abs()
|
|
234
|
+
if group_name and group_name in data.columns:
|
|
235
|
+
clean["group"] = data[group_name].reset_index(drop=True)
|
|
236
|
+
return clean.dropna(subset=["x", "y", "z"]).reset_index(drop=True)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _scaled_sizes(values: pd.Series, low: float = 20.0, high: float = 200.0) -> np.ndarray:
|
|
240
|
+
finite = values.dropna()
|
|
241
|
+
if len(finite) == 0 or float(finite.max()) == float(finite.min()):
|
|
242
|
+
return np.full(len(values), (low + high) / 2)
|
|
243
|
+
scaled = (values - float(finite.min())) / (float(finite.max()) - float(finite.min()))
|
|
244
|
+
return low + (high - low) * scaled.fillna(0.0).to_numpy(dtype=float)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _bubble_scale(params: dict) -> float:
|
|
248
|
+
try:
|
|
249
|
+
scale = float(params.get("bubble_scale", 1.0))
|
|
250
|
+
except (TypeError, ValueError):
|
|
251
|
+
scale = 1.0
|
|
252
|
+
return min(5.0, max(0.05, scale))
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def bubble(spec: PlotSpec):
|
|
256
|
+
data = frame(spec)
|
|
257
|
+
x_name = spec.params.get("x")
|
|
258
|
+
y_name = spec.params.get("y")
|
|
259
|
+
color_name = spec.params.get("color") or spec.params.get("group")
|
|
260
|
+
size_name = spec.params.get("size")
|
|
261
|
+
shape_name = spec.params.get("shape")
|
|
262
|
+
markers = ["o", "s", "^", "D", "v", "P", "X", "*"]
|
|
263
|
+
figure = new_figure()
|
|
264
|
+
ax = figure.add_subplot(111)
|
|
265
|
+
if not x_name or not y_name:
|
|
266
|
+
style_axes(ax, spec.title or "Bubble Plot", str(x_name or ""), str(y_name or ""))
|
|
267
|
+
return figure
|
|
268
|
+
clean = pd.DataFrame({"x": numeric(data, x_name), "y": numeric(data, y_name)})
|
|
269
|
+
if size_name and size_name in data.columns:
|
|
270
|
+
clean["size"] = numeric(data, size_name).abs()
|
|
271
|
+
if color_name and color_name in data.columns:
|
|
272
|
+
clean["color"] = numeric(data, color_name)
|
|
273
|
+
clean["group"] = data[color_name].to_numpy()
|
|
274
|
+
if shape_name and shape_name in data.columns:
|
|
275
|
+
clean["shape"] = data[shape_name].to_numpy()
|
|
276
|
+
clean["_row_id"] = pd.Series(row_ids_for(spec, data.index), index=data.index)
|
|
277
|
+
clean = clean.dropna(subset=["x", "y"]).reset_index(drop=True)
|
|
278
|
+
if clean.empty:
|
|
279
|
+
style_axes(ax, spec.title or f"{y_name} vs {x_name}", str(x_name), str(y_name))
|
|
280
|
+
return figure
|
|
281
|
+
|
|
282
|
+
def ids_for(chunk) -> list:
|
|
283
|
+
return [clean["_row_id"].iloc[int(position)] for position in chunk.index]
|
|
284
|
+
|
|
285
|
+
base_sizes = _scaled_sizes(clean["size"]) if "size" in clean.columns else np.full(len(clean), 60.0)
|
|
286
|
+
sizes = base_sizes * _bubble_scale(spec.params)
|
|
287
|
+
continuous_color = (
|
|
288
|
+
"color" in clean.columns
|
|
289
|
+
and pd.api.types.is_numeric_dtype(clean["color"])
|
|
290
|
+
and clean["color"].notna().any()
|
|
291
|
+
and clean["color"].nunique(dropna=True) > 12
|
|
292
|
+
)
|
|
293
|
+
if continuous_color:
|
|
294
|
+
color_values = clean["color"].to_numpy(dtype=float)
|
|
295
|
+
norm = Normalize(vmin=float(np.nanmin(color_values)), vmax=float(np.nanmax(color_values)))
|
|
296
|
+
if "shape" in clean.columns:
|
|
297
|
+
for shape_index, (shape_label, shape_chunk) in enumerate(clean.groupby("shape", dropna=False, sort=True)):
|
|
298
|
+
points = ax.scatter(
|
|
299
|
+
shape_chunk["x"],
|
|
300
|
+
shape_chunk["y"],
|
|
301
|
+
s=sizes[shape_chunk.index.to_numpy()],
|
|
302
|
+
c=shape_chunk["color"],
|
|
303
|
+
cmap="viridis",
|
|
304
|
+
norm=norm,
|
|
305
|
+
marker=markers[shape_index % len(markers)],
|
|
306
|
+
alpha=0.7,
|
|
307
|
+
edgecolors="white",
|
|
308
|
+
linewidths=0.5,
|
|
309
|
+
label=str(shape_label),
|
|
310
|
+
picker=True,
|
|
311
|
+
)
|
|
312
|
+
attach_row_ids(points, ids_for(shape_chunk))
|
|
313
|
+
ax.legend(title=str(shape_name), frameon=False, fontsize=8)
|
|
314
|
+
else:
|
|
315
|
+
points = ax.scatter(
|
|
316
|
+
clean["x"],
|
|
317
|
+
clean["y"],
|
|
318
|
+
s=sizes,
|
|
319
|
+
c=clean["color"],
|
|
320
|
+
cmap="viridis",
|
|
321
|
+
norm=norm,
|
|
322
|
+
alpha=0.7,
|
|
323
|
+
edgecolors="white",
|
|
324
|
+
linewidths=0.5,
|
|
325
|
+
picker=True,
|
|
326
|
+
)
|
|
327
|
+
attach_row_ids(points, ids_for(clean))
|
|
328
|
+
mappable = ScalarMappable(norm=norm, cmap="viridis")
|
|
329
|
+
mappable.set_array(color_values)
|
|
330
|
+
figure.colorbar(mappable, ax=ax, label=str(color_name))
|
|
331
|
+
elif "group" in clean.columns:
|
|
332
|
+
for index, (label, chunk) in enumerate(clean.groupby("group", dropna=False, sort=True)):
|
|
333
|
+
group_label = "Missing" if pd.isna(label) else str(label)
|
|
334
|
+
if "shape" in clean.columns:
|
|
335
|
+
for shape_index, (shape_label, shape_chunk) in enumerate(chunk.groupby("shape", dropna=False, sort=True)):
|
|
336
|
+
points = ax.scatter(
|
|
337
|
+
shape_chunk["x"],
|
|
338
|
+
shape_chunk["y"],
|
|
339
|
+
s=sizes[shape_chunk.index.to_numpy()],
|
|
340
|
+
color=color(index),
|
|
341
|
+
marker=markers[shape_index % len(markers)],
|
|
342
|
+
alpha=0.7,
|
|
343
|
+
edgecolors="white",
|
|
344
|
+
linewidths=0.5,
|
|
345
|
+
label=group_label if shape_index == 0 else None,
|
|
346
|
+
picker=True,
|
|
347
|
+
)
|
|
348
|
+
attach_row_ids(points, ids_for(shape_chunk))
|
|
349
|
+
else:
|
|
350
|
+
points = ax.scatter(
|
|
351
|
+
chunk["x"],
|
|
352
|
+
chunk["y"],
|
|
353
|
+
s=sizes[chunk.index.to_numpy()],
|
|
354
|
+
color=color(index),
|
|
355
|
+
alpha=0.7,
|
|
356
|
+
edgecolors="white",
|
|
357
|
+
linewidths=0.5,
|
|
358
|
+
label=group_label,
|
|
359
|
+
picker=True,
|
|
360
|
+
)
|
|
361
|
+
attach_row_ids(points, ids_for(chunk))
|
|
362
|
+
ax.legend(title=str(color_name), frameon=False, fontsize=8)
|
|
363
|
+
elif "shape" in clean.columns:
|
|
364
|
+
for shape_index, (shape_label, shape_chunk) in enumerate(clean.groupby("shape", dropna=False, sort=True)):
|
|
365
|
+
points = ax.scatter(
|
|
366
|
+
shape_chunk["x"],
|
|
367
|
+
shape_chunk["y"],
|
|
368
|
+
s=sizes[shape_chunk.index.to_numpy()],
|
|
369
|
+
color=color(shape_index),
|
|
370
|
+
marker=markers[shape_index % len(markers)],
|
|
371
|
+
alpha=0.7,
|
|
372
|
+
edgecolors="white",
|
|
373
|
+
linewidths=0.5,
|
|
374
|
+
label=str(shape_label),
|
|
375
|
+
picker=True,
|
|
376
|
+
)
|
|
377
|
+
attach_row_ids(points, ids_for(shape_chunk))
|
|
378
|
+
ax.legend(title=str(shape_name), frameon=False, fontsize=8)
|
|
379
|
+
else:
|
|
380
|
+
points = ax.scatter(clean["x"], clean["y"], s=sizes, color=color(0), alpha=0.7, edgecolors="white", linewidths=0.5, picker=True)
|
|
381
|
+
attach_row_ids(points, ids_for(clean))
|
|
382
|
+
style_axes(ax, spec.title or f"{y_name} vs {x_name}", str(x_name), str(y_name))
|
|
383
|
+
from statstudio.plots.basic import _apply_options
|
|
384
|
+
|
|
385
|
+
_apply_options(ax, spec, clean.rename(columns={"x": x_name, "y": y_name}), x_name, y_name)
|
|
386
|
+
return figure
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def line3d(spec: PlotSpec):
|
|
390
|
+
data = frame(spec)
|
|
391
|
+
x_name = spec.params.get("x")
|
|
392
|
+
y_name = spec.params.get("y")
|
|
393
|
+
z_name = spec.params.get("z")
|
|
394
|
+
group_name = spec.params.get("group")
|
|
395
|
+
figure = new_figure(7.0, 5.5)
|
|
396
|
+
ax = figure.add_subplot(111, projection="3d")
|
|
397
|
+
if not x_name or not y_name or not z_name or any(name not in data.columns for name in (x_name, y_name, z_name)):
|
|
398
|
+
ax.set_title(spec.title or "3D Line Plot", fontsize=11, fontweight="bold")
|
|
399
|
+
return figure
|
|
400
|
+
clean = _clean_xyz(data, x_name, y_name, z_name, group_name)
|
|
401
|
+
if clean.empty:
|
|
402
|
+
ax.set_title(spec.title or "3D Line Plot", fontsize=11, fontweight="bold")
|
|
403
|
+
return figure
|
|
404
|
+
if "group" in clean.columns:
|
|
405
|
+
for index, (label, chunk) in enumerate(clean.groupby("group", dropna=False, sort=True)):
|
|
406
|
+
ax.plot(
|
|
407
|
+
chunk["x"],
|
|
408
|
+
chunk["y"],
|
|
409
|
+
chunk["z"],
|
|
410
|
+
marker="o",
|
|
411
|
+
markersize=3,
|
|
412
|
+
linewidth=1.6,
|
|
413
|
+
color=color(index),
|
|
414
|
+
alpha=0.85,
|
|
415
|
+
label="Missing" if pd.isna(label) else str(label),
|
|
416
|
+
)
|
|
417
|
+
ax.legend(title=str(group_name), frameon=False, fontsize=8)
|
|
418
|
+
else:
|
|
419
|
+
ax.plot(clean["x"], clean["y"], clean["z"], marker="o", markersize=3, linewidth=1.6, color=color(0), alpha=0.85)
|
|
420
|
+
ax.set_xlabel(str(x_name))
|
|
421
|
+
ax.set_ylabel(str(y_name))
|
|
422
|
+
ax.set_zlabel(str(z_name))
|
|
423
|
+
ax.set_title(spec.title or f"3D Line: {z_name} vs {x_name} and {y_name}", fontsize=11, fontweight="bold")
|
|
424
|
+
ax.view_init(elev=float(spec.params.get("elev", 22)), azim=float(spec.params.get("azim", -60)))
|
|
425
|
+
ax.grid(True, color="#e4e8ee", linewidth=0.7, alpha=0.8)
|
|
426
|
+
return figure
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def _axis_positions(values: pd.Series) -> tuple[np.ndarray, list[str] | None, bool]:
|
|
430
|
+
if pd.api.types.is_datetime64_any_dtype(values):
|
|
431
|
+
from matplotlib import dates as mdates
|
|
432
|
+
|
|
433
|
+
return mdates.date2num(values), None, True
|
|
434
|
+
if pd.api.types.is_numeric_dtype(values):
|
|
435
|
+
return values.to_numpy(dtype=float), None, False
|
|
436
|
+
levels = _ordered_levels(values)
|
|
437
|
+
mapping = {level: index for index, level in enumerate(levels)}
|
|
438
|
+
return values.map(mapping).to_numpy(dtype=float), [str(level) for level in levels], False
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def area(spec: PlotSpec):
|
|
442
|
+
data = frame(spec)
|
|
443
|
+
x_name = spec.params.get("x")
|
|
444
|
+
y_name = spec.params.get("y")
|
|
445
|
+
group_name = spec.params.get("group")
|
|
446
|
+
figure = new_figure()
|
|
447
|
+
ax = figure.add_subplot(111)
|
|
448
|
+
if not x_name or not y_name or x_name not in data.columns or y_name not in data.columns:
|
|
449
|
+
style_axes(ax, spec.title or "Area Chart", str(x_name or ""), str(y_name or ""))
|
|
450
|
+
return figure
|
|
451
|
+
clean = pd.DataFrame({"x": data[x_name].reset_index(drop=True), "y": numeric(data, y_name)})
|
|
452
|
+
if group_name and group_name in data.columns:
|
|
453
|
+
clean["group"] = data[group_name].reset_index(drop=True)
|
|
454
|
+
clean = clean.dropna(subset=["x", "y"]).reset_index(drop=True)
|
|
455
|
+
if clean.empty:
|
|
456
|
+
style_axes(ax, spec.title or f"{y_name} by {x_name}", str(x_name), str(y_name))
|
|
457
|
+
return figure
|
|
458
|
+
all_positions, labels, datetime_axis = _axis_positions(clean["x"])
|
|
459
|
+
clean["__position__"] = all_positions
|
|
460
|
+
chunks = _group_chunks(clean, group_name)
|
|
461
|
+
for index, (label, chunk) in enumerate(chunks):
|
|
462
|
+
positions = chunk["__position__"].to_numpy(dtype=float)
|
|
463
|
+
order = np.argsort(positions)
|
|
464
|
+
positions = positions[order]
|
|
465
|
+
values = chunk["y"].to_numpy(dtype=float)[order]
|
|
466
|
+
colour = color(index)
|
|
467
|
+
ax.fill_between(positions, 0, values, color=colour, alpha=0.28, linewidth=0)
|
|
468
|
+
ax.plot(positions, values, color=colour, linewidth=1.6, label=label if group_name else None)
|
|
469
|
+
if labels is not None:
|
|
470
|
+
ax.set_xticks(range(len(labels)), labels)
|
|
471
|
+
rotate_labels(ax)
|
|
472
|
+
if datetime_axis:
|
|
473
|
+
from matplotlib import dates as mdates
|
|
474
|
+
|
|
475
|
+
ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(ax.xaxis.get_major_locator()))
|
|
476
|
+
figure.autofmt_xdate()
|
|
477
|
+
if group_name:
|
|
478
|
+
ax.legend(title=str(group_name), frameon=False, fontsize=8)
|
|
479
|
+
style_axes(ax, spec.title or f"{y_name} by {x_name}", str(x_name), str(y_name))
|
|
480
|
+
from statstudio.plots.basic import _apply_options
|
|
481
|
+
|
|
482
|
+
_apply_options(ax, spec, clean.rename(columns={"x": x_name, "y": y_name}), x_name, y_name)
|
|
483
|
+
return figure
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def dotplot(spec: PlotSpec):
|
|
487
|
+
data = frame(spec)
|
|
488
|
+
x_name = spec.params.get("x")
|
|
489
|
+
y_name = spec.params.get("y")
|
|
490
|
+
group_name = spec.params.get("group")
|
|
491
|
+
figure = new_figure()
|
|
492
|
+
ax = figure.add_subplot(111)
|
|
493
|
+
if not x_name or not y_name or x_name not in data.columns or y_name not in data.columns:
|
|
494
|
+
style_axes(ax, spec.title or "Dot Plot", str(y_name or ""), str(x_name or ""))
|
|
495
|
+
return figure
|
|
496
|
+
clean = pd.DataFrame({"level": data[x_name].reset_index(drop=True), "value": numeric(data, y_name)})
|
|
497
|
+
if group_name and group_name in data.columns:
|
|
498
|
+
clean["group"] = data[group_name].reset_index(drop=True)
|
|
499
|
+
clean = clean.dropna(subset=["level", "value"]).reset_index(drop=True)
|
|
500
|
+
levels = _ordered_levels(clean["level"])
|
|
501
|
+
if not levels:
|
|
502
|
+
style_axes(ax, spec.title or f"{y_name} by {x_name}", str(y_name), str(x_name))
|
|
503
|
+
return figure
|
|
504
|
+
positions = {level: index for index, level in enumerate(levels)}
|
|
505
|
+
rng = np.random.default_rng(0)
|
|
506
|
+
overall = float(clean["value"].mean())
|
|
507
|
+
ax.axvline(overall, color="#8a93a0", linestyle="--", linewidth=1, label="Overall mean")
|
|
508
|
+
for group_index, (group_label, chunk) in enumerate(_group_chunks(clean, group_name)):
|
|
509
|
+
colour = color(group_index)
|
|
510
|
+
offsets = rng.uniform(-0.16, 0.16, len(chunk))
|
|
511
|
+
ys = chunk["level"].map(positions).to_numpy(dtype=float) + offsets
|
|
512
|
+
ax.scatter(chunk["value"], ys, s=20, alpha=0.55, color=colour, linewidths=0)
|
|
513
|
+
means = []
|
|
514
|
+
mean_positions = []
|
|
515
|
+
for level in levels:
|
|
516
|
+
subset = chunk.loc[chunk["level"] == level, "value"]
|
|
517
|
+
if subset.empty:
|
|
518
|
+
continue
|
|
519
|
+
means.append(float(subset.mean()))
|
|
520
|
+
mean_positions.append(positions[level])
|
|
521
|
+
ax.plot(float(subset.mean()), positions[level], marker="D", markersize=5, color=colour, markeredgecolor="white")
|
|
522
|
+
if len(mean_positions) > 1:
|
|
523
|
+
ax.plot(means, mean_positions, color=colour, linewidth=1.4, alpha=0.8)
|
|
524
|
+
if group_name:
|
|
525
|
+
ax.plot([], [], color=colour, marker="D", linewidth=1.4, label=group_label)
|
|
526
|
+
ax.set_yticks(range(len(levels)), [str(level) for level in levels])
|
|
527
|
+
if group_name:
|
|
528
|
+
ax.legend(title=str(group_name), frameon=False, fontsize=8)
|
|
529
|
+
style_axes(ax, spec.title or f"{y_name} by {x_name}", str(y_name), str(x_name))
|
|
530
|
+
return figure
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def pie(spec: PlotSpec):
|
|
534
|
+
data = frame(spec)
|
|
535
|
+
category = spec.params.get("category") or spec.params.get("x")
|
|
536
|
+
count = spec.params.get("count") or spec.params.get("y")
|
|
537
|
+
figure = new_figure(6, 5)
|
|
538
|
+
ax = figure.add_subplot(111)
|
|
539
|
+
if not category or category not in data.columns:
|
|
540
|
+
ax.set_title(spec.title or "Pie Chart", fontsize=11, fontweight="bold")
|
|
541
|
+
return figure
|
|
542
|
+
labels = data[category].fillna("(missing)").astype(str)
|
|
543
|
+
if count and count in data.columns:
|
|
544
|
+
totals = pd.DataFrame({"label": labels, "value": numeric(data, count)}).dropna()
|
|
545
|
+
totals = totals.groupby("label", sort=False)["value"].sum()
|
|
546
|
+
totals = totals[totals > 0].sort_values(ascending=False)
|
|
547
|
+
else:
|
|
548
|
+
totals = labels.value_counts(dropna=False).sort_values(ascending=False)
|
|
549
|
+
if totals.empty:
|
|
550
|
+
ax.set_title(spec.title or f"Distribution of {category}", fontsize=11, fontweight="bold")
|
|
551
|
+
return figure
|
|
552
|
+
max_slices = int(spec.params.get("max_slices", 10))
|
|
553
|
+
if len(totals) > max_slices:
|
|
554
|
+
head = totals.iloc[: max_slices - 1]
|
|
555
|
+
other = float(totals.iloc[max_slices - 1 :].sum())
|
|
556
|
+
totals = pd.concat([head, pd.Series({"Other": other})])
|
|
557
|
+
ax.pie(
|
|
558
|
+
totals.to_numpy(dtype=float),
|
|
559
|
+
labels=[str(item) for item in totals.index],
|
|
560
|
+
autopct="%1.1f%%",
|
|
561
|
+
startangle=90,
|
|
562
|
+
counterclock=False,
|
|
563
|
+
colors=[color(index) for index in range(len(totals))],
|
|
564
|
+
wedgeprops={"edgecolor": "white", "linewidth": 1},
|
|
565
|
+
)
|
|
566
|
+
ax.axis("equal")
|
|
567
|
+
ax.set_title(spec.title or f"Distribution of {category}", fontsize=11, fontweight="bold")
|
|
568
|
+
return figure
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
def parallel_coordinates(spec: PlotSpec):
|
|
572
|
+
data = frame(spec)
|
|
573
|
+
columns = list(spec.params.get("columns") or [])
|
|
574
|
+
group_name = spec.params.get("group")
|
|
575
|
+
figure = new_figure(max(7, len(columns) * 1.3), 5)
|
|
576
|
+
ax = figure.add_subplot(111)
|
|
577
|
+
if len(columns) < 2:
|
|
578
|
+
style_axes(ax, spec.title or "Parallel Coordinates", "", "Normalized value")
|
|
579
|
+
return figure
|
|
580
|
+
clean = pd.DataFrame({name: numeric(data, name) for name in columns if name in data.columns})
|
|
581
|
+
clean = clean.dropna()
|
|
582
|
+
if clean.empty:
|
|
583
|
+
style_axes(ax, spec.title or "Parallel Coordinates", "", "Normalized value")
|
|
584
|
+
return figure
|
|
585
|
+
normalized = clean.copy()
|
|
586
|
+
for name in normalized.columns:
|
|
587
|
+
low, high = float(clean[name].min()), float(clean[name].max())
|
|
588
|
+
normalized[name] = 0.0 if high == low else (clean[name] - low) / (high - low)
|
|
589
|
+
normalized = normalized.reset_index(drop=True)
|
|
590
|
+
groups = None
|
|
591
|
+
if group_name and group_name in data.columns:
|
|
592
|
+
groups = data.loc[clean.index, group_name].reset_index(drop=True)
|
|
593
|
+
limit = int(spec.params.get("max_lines", 400))
|
|
594
|
+
positions = np.arange(len(normalized.columns))
|
|
595
|
+
if groups is not None:
|
|
596
|
+
for index, label in enumerate(_ordered_levels(groups.fillna("(missing)").astype(str))):
|
|
597
|
+
mask = groups.fillna("(missing)").astype(str) == label
|
|
598
|
+
subset = normalized.loc[mask]
|
|
599
|
+
if len(subset) > limit:
|
|
600
|
+
step = max(1, len(subset) // limit)
|
|
601
|
+
subset = subset.iloc[::step].iloc[:limit]
|
|
602
|
+
for row in subset.to_numpy(dtype=float):
|
|
603
|
+
ax.plot(positions, row, color=color(index), alpha=0.35, linewidth=0.9)
|
|
604
|
+
ax.plot([], [], color=color(index), linewidth=1.5, label=str(label))
|
|
605
|
+
ax.legend(title=str(group_name), frameon=False, fontsize=8)
|
|
606
|
+
else:
|
|
607
|
+
subset = normalized
|
|
608
|
+
if len(subset) > limit:
|
|
609
|
+
step = max(1, len(subset) // limit)
|
|
610
|
+
subset = subset.iloc[::step].iloc[:limit]
|
|
611
|
+
for row in subset.to_numpy(dtype=float):
|
|
612
|
+
ax.plot(positions, row, color=color(0), alpha=0.25, linewidth=0.9)
|
|
613
|
+
ax.set_xticks(positions, [str(name) for name in normalized.columns])
|
|
614
|
+
rotate_labels(ax)
|
|
615
|
+
style_axes(ax, spec.title or "Parallel Coordinates", "", "Normalized value")
|
|
616
|
+
return figure
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def heatmap(spec: PlotSpec):
|
|
620
|
+
data = frame(spec)
|
|
621
|
+
x_name = spec.params.get("x")
|
|
622
|
+
y_name = spec.params.get("y")
|
|
623
|
+
z_name = spec.params.get("z")
|
|
624
|
+
figure = new_figure(7, 5.5)
|
|
625
|
+
ax = figure.add_subplot(111)
|
|
626
|
+
if not x_name or not y_name or not z_name or any(name not in data.columns for name in (x_name, y_name, z_name)):
|
|
627
|
+
style_axes(ax, spec.title or "Heatmap", str(x_name or ""), str(y_name or ""))
|
|
628
|
+
return figure
|
|
629
|
+
working = data.assign(__z=pd.to_numeric(data[z_name], errors="coerce"))
|
|
630
|
+
pivot = working.pivot_table(index=y_name, columns=x_name, values="__z", aggfunc="mean")
|
|
631
|
+
if pivot.empty:
|
|
632
|
+
style_axes(ax, spec.title or f"{z_name} by {x_name} and {y_name}", str(x_name), str(y_name))
|
|
633
|
+
return figure
|
|
634
|
+
values = pivot.to_numpy(dtype=float)
|
|
635
|
+
image = ax.imshow(values, aspect="auto", origin="lower", cmap="RdYlBu_r")
|
|
636
|
+
ax.set_xticks(range(len(pivot.columns)), [str(item) for item in pivot.columns])
|
|
637
|
+
ax.set_yticks(range(len(pivot.index)), [str(item) for item in pivot.index])
|
|
638
|
+
if len(pivot.columns) > 6 or len(pivot.index) > 8:
|
|
639
|
+
rotate_labels(ax)
|
|
640
|
+
if spec.params.get("annotate", values.size <= 144):
|
|
641
|
+
finite = values[np.isfinite(values)]
|
|
642
|
+
for row in range(values.shape[0]):
|
|
643
|
+
for column in range(values.shape[1]):
|
|
644
|
+
value = values[row, column]
|
|
645
|
+
if not np.isfinite(value):
|
|
646
|
+
continue
|
|
647
|
+
text_color = "white" if (value - float(np.nanmin(finite))) > 0.55 * (float(np.nanmax(finite)) - float(np.nanmin(finite)) + 1e-12) else "#20242a"
|
|
648
|
+
ax.text(column, row, f"{value:.3g}", ha="center", va="center", fontsize=7, color=text_color)
|
|
649
|
+
figure.colorbar(image, ax=ax, label=str(z_name))
|
|
650
|
+
style_axes(ax, spec.title or f"{z_name} by {x_name} and {y_name}", str(x_name), str(y_name))
|
|
651
|
+
return figure
|