staplot 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.
Files changed (68) hide show
  1. staplot/__init__.py +1 -0
  2. staplot/api.py +441 -0
  3. staplot/main.py +21 -0
  4. staplot/models/__init__.py +1 -0
  5. staplot/models/project.py +461 -0
  6. staplot/plots/__init__.py +14 -0
  7. staplot/plots/bar.py +104 -0
  8. staplot/plots/before_after.py +110 -0
  9. staplot/plots/bland_altman.py +73 -0
  10. staplot/plots/box.py +95 -0
  11. staplot/plots/distribution_plot.py +188 -0
  12. staplot/plots/grouped_bar.py +112 -0
  13. staplot/plots/heatmap.py +73 -0
  14. staplot/plots/histogram.py +76 -0
  15. staplot/plots/qq.py +61 -0
  16. staplot/plots/residuals.py +72 -0
  17. staplot/plots/roc_plot.py +40 -0
  18. staplot/plots/scatter.py +61 -0
  19. staplot/plots/significance.py +94 -0
  20. staplot/plots/styles.py +154 -0
  21. staplot/plots/survival.py +78 -0
  22. staplot/plots/volcano.py +110 -0
  23. staplot/stats/__init__.py +15 -0
  24. staplot/stats/anova.py +124 -0
  25. staplot/stats/chi_square.py +85 -0
  26. staplot/stats/correlation.py +71 -0
  27. staplot/stats/curve_fit.py +85 -0
  28. staplot/stats/descriptive.py +52 -0
  29. staplot/stats/distribution.py +223 -0
  30. staplot/stats/multiple_comparisons.py +104 -0
  31. staplot/stats/normality.py +67 -0
  32. staplot/stats/outliers.py +62 -0
  33. staplot/stats/power.py +130 -0
  34. staplot/stats/regression.py +95 -0
  35. staplot/stats/repeated_measures.py +114 -0
  36. staplot/stats/roc.py +196 -0
  37. staplot/stats/tests.py +142 -0
  38. staplot/stats/two_way_anova.py +88 -0
  39. staplot/ui/__init__.py +0 -0
  40. staplot/ui/analysis_dialog.py +406 -0
  41. staplot/ui/axis_dialog.py +104 -0
  42. staplot/ui/computed_column_dialog.py +261 -0
  43. staplot/ui/contingency_table_widget.py +158 -0
  44. staplot/ui/data_table_widget.py +277 -0
  45. staplot/ui/distribution_inspector.py +431 -0
  46. staplot/ui/figure_layout_widget.py +236 -0
  47. staplot/ui/graph_gallery.py +117 -0
  48. staplot/ui/graph_options_dialog.py +325 -0
  49. staplot/ui/grouped_table_widget.py +190 -0
  50. staplot/ui/layout_dialog.py +218 -0
  51. staplot/ui/main_window.py +1126 -0
  52. staplot/ui/multiple_comparisons_dialog.py +168 -0
  53. staplot/ui/navigator.py +88 -0
  54. staplot/ui/plot_canvas.py +251 -0
  55. staplot/ui/power_dialog.py +108 -0
  56. staplot/ui/report_dialog.py +255 -0
  57. staplot/ui/reshape_dialog.py +286 -0
  58. staplot/ui/results_widget.py +19 -0
  59. staplot/ui/standard_curve_dialog.py +150 -0
  60. staplot/ui/test_wizard.py +252 -0
  61. staplot/ui/transform_dialog.py +137 -0
  62. staplot/ui/undo_commands.py +86 -0
  63. staplot-0.1.0.dist-info/METADATA +85 -0
  64. staplot-0.1.0.dist-info/RECORD +68 -0
  65. staplot-0.1.0.dist-info/WHEEL +5 -0
  66. staplot-0.1.0.dist-info/entry_points.txt +2 -0
  67. staplot-0.1.0.dist-info/licenses/LICENSE +24 -0
  68. staplot-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,73 @@
1
+ """Bland-Altman agreement plot."""
2
+
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ import matplotlib.figure
6
+
7
+ from ..models.project import DataTable
8
+ from . import styles
9
+
10
+
11
+ @styles.styled
12
+ def plot_bland_altman(
13
+ table: DataTable,
14
+ col_a: str,
15
+ col_b: str,
16
+ title: str = "",
17
+ color: str | None = None,
18
+ percentage: bool = False,
19
+ ) -> matplotlib.figure.Figure:
20
+ """
21
+ Bland-Altman plot comparing two measurement methods.
22
+ percentage=True: plot % difference instead of absolute difference.
23
+ """
24
+ groups = table.group_arrays()
25
+ if col_a not in groups or col_b not in groups:
26
+ fig, ax = plt.subplots()
27
+ ax.text(0.5, 0.5, "Columns not found", ha="center", va="center", transform=ax.transAxes)
28
+ return fig
29
+
30
+ # both methods measured the same sample: pair by row
31
+ a, b = table.paired_arrays(col_a, col_b)
32
+ if len(a) < 2:
33
+ fig, ax = plt.subplots()
34
+ ax.text(0.5, 0.5, "Need at least 2 complete pairs", ha="center", va="center",
35
+ transform=ax.transAxes)
36
+ return fig
37
+
38
+ mean_vals = (a + b) / 2.0
39
+ if percentage:
40
+ diff = 100.0 * (a - b) / mean_vals
41
+ ylabel = "Difference (%)"
42
+ else:
43
+ diff = a - b
44
+ ylabel = f"Difference ({col_a} − {col_b})"
45
+
46
+ mean_diff = float(np.mean(diff))
47
+ std_diff = float(np.std(diff, ddof=1))
48
+ loa_upper = mean_diff + 1.96 * std_diff
49
+ loa_lower = mean_diff - 1.96 * std_diff
50
+
51
+ c = color or styles.color(0)
52
+ fig, ax = plt.subplots(figsize=(5, 4))
53
+
54
+ ax.scatter(mean_vals, diff, color=c, s=28, alpha=0.75, zorder=3,
55
+ linewidths=0.3, edgecolors="white")
56
+
57
+ x_lim = (mean_vals.min() - 0.05 * np.ptp(mean_vals),
58
+ mean_vals.max() + 0.05 * np.ptp(mean_vals))
59
+ ax.set_xlim(*x_lim)
60
+
61
+ for y, ls, lbl in [
62
+ (mean_diff, "-", f"Mean: {mean_diff:.3f}"),
63
+ (loa_upper, "--", f"+1.96 SD: {loa_upper:.3f}"),
64
+ (loa_lower, "--", f"−1.96 SD: {loa_lower:.3f}"),
65
+ ]:
66
+ ax.axhline(y, color="#333333", linewidth=1.2, linestyle=ls)
67
+ ax.text(x_lim[1], y, f" {lbl}", va="center", fontsize=7, color="#333333")
68
+
69
+ ax.set_xlabel(f"Mean of {col_a} and {col_b}")
70
+ ax.set_ylabel(ylabel)
71
+ ax.set_title(title or f"Bland-Altman: {col_a} vs {col_b}")
72
+ fig.tight_layout()
73
+ return fig
staplot/plots/box.py ADDED
@@ -0,0 +1,95 @@
1
+ import numpy as np
2
+ import matplotlib.pyplot as plt
3
+ import matplotlib.figure
4
+
5
+ from ..models.project import DataTable
6
+ from . import styles
7
+ from .significance import add_significance_brackets
8
+
9
+
10
+ @styles.styled
11
+ def plot_box(
12
+ table: DataTable,
13
+ plot_type: str = "box",
14
+ show_points: bool = True,
15
+ title: str = "",
16
+ ylabel: str = "",
17
+ colors: list | None = None,
18
+ sig_pairs: list | None = None,
19
+ ) -> matplotlib.figure.Figure:
20
+ cols = [c for c in table.columns if len(c.valid_values()) > 0]
21
+ names = [c.name for c in cols]
22
+ arrays = [c.valid_values() for c in cols]
23
+
24
+ if not names:
25
+ fig, ax = plt.subplots()
26
+ ax.text(0.5, 0.5, "No data", ha="center", va="center", transform=ax.transAxes)
27
+ return fig
28
+
29
+ fig, ax = plt.subplots(figsize=(max(3.5, len(names) * 0.9), 4))
30
+ palette = [
31
+ (colors[i] if colors and i < len(colors) else styles.color(i))
32
+ for i in range(len(names))
33
+ ]
34
+
35
+ if plot_type == "violin":
36
+ parts = ax.violinplot(arrays, positions=range(len(names)), showmedians=True,
37
+ showextrema=True)
38
+ for i, pc in enumerate(parts["bodies"]):
39
+ pc.set_facecolor(palette[i])
40
+ pc.set_alpha(0.7)
41
+ for key in ("cmedians", "cmins", "cmaxes", "cbars"):
42
+ if key in parts:
43
+ parts[key].set_color("#333333")
44
+ parts[key].set_linewidth(1.2)
45
+ else:
46
+ bp = ax.boxplot(
47
+ arrays,
48
+ # same x as points, ticks and brackets (0..n-1); boxplot's default
49
+ # 1..n drew every box one group to the right of its data
50
+ positions=range(len(names)),
51
+ patch_artist=True,
52
+ medianprops=dict(color="#333333", linewidth=2),
53
+ whiskerprops=dict(linewidth=1.2),
54
+ capprops=dict(linewidth=1.2),
55
+ flierprops=dict(marker="o", markersize=4, alpha=0.5),
56
+ widths=0.5,
57
+ )
58
+ for patch, color in zip(bp["boxes"], palette):
59
+ patch.set_facecolor(color)
60
+ patch.set_alpha(0.75)
61
+
62
+ if show_points:
63
+ rng = np.random.default_rng(42)
64
+ for i, col in enumerate(cols):
65
+ vals, row_idxs = col.valid_values_with_indices()
66
+ jitter = rng.uniform(-0.08, 0.08, size=len(vals))
67
+ sc = ax.scatter(
68
+ np.full(len(vals), i) + jitter,
69
+ vals,
70
+ color="#222222",
71
+ s=18,
72
+ zorder=5,
73
+ alpha=0.65,
74
+ linewidths=0.3,
75
+ edgecolors="white",
76
+ picker=5,
77
+ )
78
+ sc._staplot_meta = {"column": col.name, "rows": row_idxs, "exclude_all": False}
79
+
80
+ ax.set_xticks(range(len(names)))
81
+ rotation = 20 if max(len(n) for n in names) > 8 else 0
82
+ # tilted labels end at their tick; level ones are centred on it
83
+ ax.set_xticklabels(names, rotation=rotation, ha="right" if rotation else "center")
84
+ ax.set_ylabel(ylabel or "Value")
85
+ ax.set_title(title or table.name)
86
+
87
+ if sig_pairs:
88
+ # Whisker tops as bracket heights
89
+ box_tops: dict[str, float] = {}
90
+ for name, arr in zip(names, arrays):
91
+ box_tops[name] = float(np.max(arr)) if len(arr) > 0 else 0.0
92
+ add_significance_brackets(ax, names, sig_pairs, box_tops)
93
+
94
+ fig.tight_layout()
95
+ return fig
@@ -0,0 +1,188 @@
1
+ """Per-column distribution visualisation: histogram + KDE + fit overlay + Q-Q plot."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ import matplotlib.pyplot as plt
7
+ import matplotlib.figure
8
+ from scipy import stats as sp_stats
9
+
10
+ from ..models.project import DataTable
11
+ from . import styles
12
+
13
+
14
+ _SCIPY_DISTS = {
15
+ "Normal": sp_stats.norm,
16
+ "Log-normal": sp_stats.lognorm,
17
+ "Exponential": sp_stats.expon,
18
+ "Gamma": sp_stats.gamma,
19
+ "Weibull": sp_stats.weibull_min,
20
+ }
21
+
22
+
23
+ @styles.styled
24
+ def plot_distribution(
25
+ table: DataTable,
26
+ col_name: str,
27
+ fits: list[dict] | None = None,
28
+ show_normal_ref: bool = True,
29
+ ) -> matplotlib.figure.Figure:
30
+ """
31
+ Two-panel figure for one column:
32
+ Left — histogram + KDE overlay + optional fitted-distribution curve
33
+ Right — Q-Q plot vs Normal
34
+
35
+ *fits* is the list returned by ``stats.distribution.fit_distributions()``.
36
+ """
37
+ col_obj = next((c for c in table.columns if c.name == col_name), None)
38
+ if col_obj is None:
39
+ fig, ax = plt.subplots()
40
+ ax.text(0.5, 0.5, f"Column '{col_name}' not found",
41
+ ha="center", va="center", transform=ax.transAxes)
42
+ return fig
43
+
44
+ arr = col_obj.valid_values()
45
+ n = len(arr)
46
+ if n < 3:
47
+ fig, ax = plt.subplots()
48
+ ax.text(0.5, 0.5, f"Not enough data (n={n})", ha="center", va="center",
49
+ transform=ax.transAxes)
50
+ return fig
51
+
52
+ color = styles.color(0)
53
+ fig, (ax_hist, ax_qq) = plt.subplots(1, 2, figsize=(8.5, 3.6))
54
+
55
+ # ── Left panel: histogram + overlays ─────────────────────────────
56
+ ax_hist.hist(
57
+ arr, bins="auto", density=True, alpha=0.55,
58
+ color=color, edgecolor="white", linewidth=0.5, zorder=2,
59
+ )
60
+
61
+ # KDE
62
+ if n >= 4:
63
+ from scipy.stats import gaussian_kde
64
+ kde = gaussian_kde(arr, bw_method="scott")
65
+ span = max(arr.std() * 3, (arr.max() - arr.min()) * 0.3)
66
+ x_kde = np.linspace(arr.min() - span, arr.max() + span, 300)
67
+ ax_hist.plot(x_kde, kde(x_kde), color=color, linewidth=2.0,
68
+ label="KDE", zorder=4)
69
+
70
+ # Best-fit distribution (first in *fits*)
71
+ if fits:
72
+ best = fits[0]
73
+ dist = _SCIPY_DISTS.get(best["distribution"])
74
+ if dist is not None:
75
+ try:
76
+ params = best.get("params") or dist.fit(arr)
77
+ span2 = max(arr.std() * 3.5, (arr.max() - arr.min()) * 0.4)
78
+ x_fit = np.linspace(max(arr.min() - span2, 1e-9 if best["distribution"] in
79
+ {"Log-normal","Exponential","Gamma","Weibull"} else arr.min() - span2),
80
+ arr.max() + span2, 300)
81
+ ax_hist.plot(
82
+ x_fit, dist.pdf(x_fit, *params),
83
+ color="#d04040", linewidth=1.6, linestyle="--",
84
+ label=f"{best['distribution']} fit", zorder=5,
85
+ )
86
+ except Exception:
87
+ pass
88
+
89
+ # Normal reference curve
90
+ if show_normal_ref:
91
+ mu, sigma = float(np.mean(arr)), float(np.std(arr, ddof=1))
92
+ if sigma > 0:
93
+ x_norm = np.linspace(mu - 4 * sigma, mu + 4 * sigma, 300)
94
+ ax_hist.plot(
95
+ x_norm, sp_stats.norm.pdf(x_norm, mu, sigma),
96
+ color="#888888", linewidth=1.0, linestyle=":",
97
+ alpha=0.9, label="Normal ref.", zorder=3,
98
+ )
99
+
100
+ ax_hist.set_xlabel(col_name)
101
+ ax_hist.set_ylabel("Density")
102
+ ax_hist.set_title(f"Distribution — {col_name} (n={n})")
103
+ ax_hist.legend(fontsize=7, loc="upper right")
104
+
105
+ # ── Right panel: Q-Q plot vs Normal ──────────────────────────────
106
+ (osm, osr), (slope, intercept, r) = sp_stats.probplot(arr, dist="norm")
107
+ ax_qq.scatter(
108
+ osm, osr, s=22, alpha=0.75, color=color,
109
+ linewidths=0.3, edgecolors="white", zorder=3,
110
+ )
111
+ qq_x = np.array([osm.min(), osm.max()])
112
+ ax_qq.plot(qq_x, slope * qq_x + intercept,
113
+ color="#444444", linewidth=1.3, zorder=2)
114
+
115
+ # Colour the scatter by deviation from the line
116
+ residuals = osr - (slope * osm + intercept)
117
+ thresh = 2.0 * residuals.std()
118
+ outlier_mask = np.abs(residuals) > thresh
119
+ if outlier_mask.any():
120
+ ax_qq.scatter(
121
+ osm[outlier_mask], osr[outlier_mask],
122
+ s=28, color="#e05050", zorder=4,
123
+ linewidths=0.5, edgecolors="#800000", alpha=0.9,
124
+ )
125
+
126
+ ax_qq.set_xlabel("Theoretical quantiles (Normal)")
127
+ ax_qq.set_ylabel("Sample quantiles")
128
+ ax_qq.set_title(f"Q-Q plot — r = {r:.3f}")
129
+
130
+ fig.tight_layout(pad=1.2)
131
+ return fig
132
+
133
+
134
+ @styles.styled
135
+ def plot_distribution_grid(
136
+ table: DataTable,
137
+ dist_details: dict, # from run_distribution_check().details
138
+ max_cols: int = 3,
139
+ ) -> matplotlib.figure.Figure:
140
+ """
141
+ Compact grid overview: one mini histogram per column with
142
+ normality verdict colour-coded (green = normal, orange = non-normal).
143
+ """
144
+ valid_cols = [c for c in table.columns if len(c.valid_values()) >= 3]
145
+ if not valid_cols:
146
+ fig, ax = plt.subplots()
147
+ ax.text(0.5, 0.5, "No data", ha="center", va="center",
148
+ transform=ax.transAxes)
149
+ return fig
150
+
151
+ n_cols = min(len(valid_cols), max_cols)
152
+ n_rows = (len(valid_cols) + n_cols - 1) // n_cols
153
+ fig, axes = plt.subplots(n_rows, n_cols,
154
+ figsize=(n_cols * 2.6, n_rows * 2.2),
155
+ squeeze=False)
156
+
157
+ for idx, col in enumerate(valid_cols):
158
+ r, c = divmod(idx, n_cols)
159
+ ax = axes[r][c]
160
+ arr = col.valid_values()
161
+ info = dist_details.get(col.name, {})
162
+ is_normal = info.get("is_normal", True)
163
+ bar_color = styles.color(0) if is_normal else styles.color(1)
164
+
165
+ ax.hist(arr, bins="auto", density=True,
166
+ color=bar_color, alpha=0.65, edgecolor="white", linewidth=0.4)
167
+
168
+ # Tiny normal reference
169
+ mu, sd = float(np.mean(arr)), float(np.std(arr, ddof=1))
170
+ if sd > 0:
171
+ x = np.linspace(mu - 3.5 * sd, mu + 3.5 * sd, 200)
172
+ ax.plot(x, sp_stats.norm.pdf(x, mu, sd),
173
+ color="#555555", linewidth=0.9, linestyle=":")
174
+
175
+ verdict = "normal" if is_normal else "non-normal"
176
+ ax.set_title(f"{col.name}\n({verdict})", fontsize=7.5,
177
+ color="#1a7a1a" if is_normal else "#b84000")
178
+ ax.tick_params(labelsize=6)
179
+ ax.set_ylabel("")
180
+
181
+ # Hide unused axes
182
+ for idx in range(len(valid_cols), n_rows * n_cols):
183
+ r, c = divmod(idx, n_cols)
184
+ axes[r][c].set_visible(False)
185
+
186
+ fig.suptitle(f"Distribution overview — {table.name}", fontsize=9, y=1.01)
187
+ fig.tight_layout(pad=0.6)
188
+ return fig
@@ -0,0 +1,112 @@
1
+ """Grouped bar chart for GroupedDataTable (Prism-style side-by-side bars)."""
2
+
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ import matplotlib.figure
6
+ from scipy import stats as scipy_stats
7
+
8
+ from ..models.project import GroupedDataTable
9
+ from . import styles
10
+
11
+
12
+ @styles.styled
13
+ def plot_grouped_bar(
14
+ table: GroupedDataTable,
15
+ error_type: str = "sem", # "sem" | "sd" | "ci95" | "none"
16
+ show_points: bool = True,
17
+ title: str = "",
18
+ ylabel: str = "",
19
+ colors: list | None = None,
20
+ sig_pairs: list | None = None,
21
+ ) -> matplotlib.figure.Figure:
22
+ """
23
+ Side-by-side bar chart for a GroupedDataTable.
24
+ Factor A (col_groups) → bar colour / legend entry.
25
+ Factor B (row_labels) → X-axis position.
26
+ """
27
+
28
+ if not table.col_groups or not table.row_labels:
29
+ fig, ax = plt.subplots()
30
+ ax.text(0.5, 0.5, "No data", ha="center", va="center",
31
+ transform=ax.transAxes)
32
+ return fig
33
+
34
+ n_cg = len(table.col_groups) # number of colour groups
35
+ n_rows = len(table.row_labels) # number of X positions
36
+
37
+ bar_w = 0.8 / n_cg
38
+ x_base = np.arange(n_rows)
39
+
40
+ fig_w = max(5, n_rows * n_cg * 0.55 + 1.5)
41
+ fig, ax = plt.subplots(figsize=(fig_w, 4))
42
+
43
+ rng = np.random.default_rng(42)
44
+
45
+ for i, cg in enumerate(table.col_groups):
46
+ c = (colors[i] if colors and i < len(colors) else styles.color(i))
47
+ means, errs, point_sets = [], [], []
48
+
49
+ for rl in table.row_labels:
50
+ raw = [v for v in table.data.get(cg, {}).get(rl, [])
51
+ if v is not None and not np.isnan(float(v))]
52
+ arr = np.array(raw, dtype=float)
53
+
54
+ if len(arr) == 0:
55
+ means.append(np.nan)
56
+ errs.append(0.0)
57
+ else:
58
+ m = float(np.mean(arr))
59
+ means.append(m)
60
+ if len(arr) > 1:
61
+ sd = float(np.std(arr, ddof=1))
62
+ sem = sd / np.sqrt(len(arr))
63
+ if error_type == "sd":
64
+ errs.append(sd)
65
+ elif error_type == "ci95":
66
+ errs.append(float(scipy_stats.t.ppf(0.975, len(arr) - 1)) * sem)
67
+ elif error_type == "none":
68
+ errs.append(0.0)
69
+ else:
70
+ errs.append(sem)
71
+ else:
72
+ errs.append(0.0)
73
+ point_sets.append(arr)
74
+
75
+ offset = (i - n_cg / 2.0 + 0.5) * bar_w
76
+ bx = x_base + offset
77
+
78
+ # bars
79
+ ax.bar(bx, means, width=bar_w * 0.88,
80
+ color=c, alpha=0.85, label=cg,
81
+ zorder=3, edgecolor="white", linewidth=0.5)
82
+
83
+ # error bars
84
+ valid = [(bx[j], means[j], errs[j])
85
+ for j in range(n_rows) if not np.isnan(means[j]) and errs[j] > 0]
86
+ if valid:
87
+ vx, vy, ve = zip(*valid)
88
+ ax.errorbar(vx, vy, yerr=ve, fmt="none",
89
+ color="#333333", linewidth=1.2, capsize=3, zorder=4)
90
+
91
+ # jittered data points
92
+ if show_points:
93
+ for bx_j, arr in zip(bx, point_sets):
94
+ if len(arr) == 0:
95
+ continue
96
+ jitter = rng.uniform(-bar_w * 0.18, bar_w * 0.18, len(arr))
97
+ ax.scatter(bx_j + jitter, arr,
98
+ color="white", edgecolors=c,
99
+ s=22, alpha=0.9, linewidths=0.8, zorder=5)
100
+
101
+ ax.set_xticks(x_base)
102
+ ax.set_xticklabels(
103
+ table.row_labels,
104
+ rotation=0 if n_rows <= 6 else 30,
105
+ ha="right" if n_rows > 6 else "center",
106
+ )
107
+ ax.set_ylabel(ylabel or "Value")
108
+ ax.set_title(title or table.name)
109
+ ax.legend(title="Group", fontsize=8, loc="upper right")
110
+ ax.set_xlim(-0.5, n_rows - 0.5)
111
+ fig.tight_layout()
112
+ return fig
@@ -0,0 +1,73 @@
1
+ """Heatmap — values, correlation matrix, or grouped data."""
2
+
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ import matplotlib.figure
6
+ from matplotlib import cm
7
+
8
+ from ..models.project import DataTable
9
+ from . import styles
10
+
11
+
12
+ @styles.styled
13
+ def plot_heatmap(
14
+ table: DataTable,
15
+ mode: str = "values", # "values" | "correlation"
16
+ cmap: str = "RdYlBu_r",
17
+ annotate: bool = True,
18
+ fmt: str = ".2f",
19
+ title: str = "",
20
+ vmin: float | None = None,
21
+ vmax: float | None = None,
22
+ ) -> matplotlib.figure.Figure:
23
+
24
+ df = table.to_dataframe()
25
+ if df.empty:
26
+ fig, ax = plt.subplots()
27
+ ax.text(0.5, 0.5, "No data", ha="center", va="center", transform=ax.transAxes)
28
+ return fig
29
+
30
+ if mode == "correlation":
31
+ mat = df.corr().values
32
+ row_labels = col_labels = list(df.columns)
33
+ cmap = "RdBu_r"
34
+ vmin, vmax = -1.0, 1.0
35
+ fmt = ".2f"
36
+ plot_title = title or f"Correlation matrix: {table.name}"
37
+ else:
38
+ mat = df.values.astype(float)
39
+ row_labels = [str(i + 1) for i in range(mat.shape[0])]
40
+ col_labels = list(df.columns)
41
+ plot_title = title or table.name
42
+
43
+ nrows, ncols = mat.shape
44
+ cell_size = max(0.5, min(1.0, 6.0 / max(nrows, ncols)))
45
+ fig_w = max(4, ncols * cell_size + 1.5)
46
+ fig_h = max(3, nrows * cell_size + 1.0)
47
+ fig, ax = plt.subplots(figsize=(fig_w, fig_h))
48
+
49
+ im = ax.imshow(mat, aspect="auto", cmap=cmap,
50
+ vmin=vmin if vmin is not None else np.nanmin(mat),
51
+ vmax=vmax if vmax is not None else np.nanmax(mat))
52
+
53
+ ax.set_xticks(range(ncols))
54
+ ax.set_xticklabels(col_labels, rotation=40, ha="right", fontsize=8)
55
+ ax.set_yticks(range(nrows))
56
+ ax.set_yticklabels(row_labels, fontsize=8)
57
+
58
+ if annotate and nrows * ncols <= 200:
59
+ thresh = (np.nanmax(mat) + np.nanmin(mat)) / 2
60
+ for i in range(nrows):
61
+ for j in range(ncols):
62
+ val = mat[i, j]
63
+ if np.isnan(val):
64
+ continue
65
+ txt = format(val, fmt)
66
+ color = "white" if val < thresh else "black"
67
+ ax.text(j, i, txt, ha="center", va="center",
68
+ fontsize=max(6, 9 - nrows // 4), color=color)
69
+
70
+ plt.colorbar(im, ax=ax, shrink=0.8)
71
+ ax.set_title(plot_title)
72
+ fig.tight_layout()
73
+ return fig
@@ -0,0 +1,76 @@
1
+ """Frequency histogram with optional KDE overlay."""
2
+
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ import matplotlib.figure
6
+ from scipy.stats import gaussian_kde
7
+
8
+ from ..models.project import DataTable
9
+ from . import styles
10
+
11
+
12
+ @styles.styled
13
+ def plot_histogram(
14
+ table: DataTable,
15
+ bins: int | str = "auto",
16
+ density: bool = False,
17
+ show_kde: bool = True,
18
+ cumulative: bool = False,
19
+ title: str = "",
20
+ xlabel: str = "Value",
21
+ ylabel: str = "",
22
+ colors: list | None = None,
23
+ ) -> matplotlib.figure.Figure:
24
+ groups = table.group_arrays()
25
+ names = [n for n, a in groups.items() if len(a) > 0]
26
+ if not names:
27
+ fig, ax = plt.subplots()
28
+ ax.text(0.5, 0.5, "No data", ha="center", va="center", transform=ax.transAxes)
29
+ return fig
30
+
31
+ fig, ax = plt.subplots(figsize=(5, 4))
32
+
33
+ for i, name in enumerate(names):
34
+ arr = groups[name]
35
+ color = (colors[i] if colors and i < len(colors) else styles.color(i))
36
+
37
+ alpha = 0.55 if len(names) > 1 else 0.75
38
+ ax.hist(
39
+ arr,
40
+ bins=bins,
41
+ density=density,
42
+ cumulative=cumulative,
43
+ alpha=alpha,
44
+ color=color,
45
+ label=name,
46
+ edgecolor="white",
47
+ linewidth=0.5,
48
+ )
49
+
50
+ if show_kde and not cumulative and len(arr) >= 4:
51
+ try:
52
+ kde = gaussian_kde(arr, bw_method="scott")
53
+ x_line = np.linspace(arr.min() - arr.std(), arr.max() + arr.std(), 300)
54
+ kde_y = kde(x_line)
55
+ if not density:
56
+ # scale KDE to match histogram counts
57
+ bin_count = bins if isinstance(bins, int) else int(np.sqrt(len(arr)))
58
+ bin_w = (arr.max() - arr.min()) / max(bin_count, 1)
59
+ kde_y = kde_y * len(arr) * bin_w
60
+ ax.plot(x_line, kde_y, color=color, linewidth=2.0, alpha=0.9)
61
+ except Exception:
62
+ pass
63
+
64
+ ax.set_xlabel(xlabel)
65
+ if ylabel:
66
+ ax.set_ylabel(ylabel)
67
+ elif cumulative:
68
+ ax.set_ylabel("Cumulative frequency")
69
+ else:
70
+ ax.set_ylabel("Density" if density else "Count")
71
+
72
+ ax.set_title(title or table.name)
73
+ if len(names) > 1:
74
+ ax.legend()
75
+ fig.tight_layout()
76
+ return fig
staplot/plots/qq.py ADDED
@@ -0,0 +1,61 @@
1
+ """Q-Q normal probability plots."""
2
+
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ import matplotlib.figure
6
+ from scipy import stats
7
+
8
+ from ..models.project import DataTable
9
+ from . import styles
10
+
11
+
12
+ @styles.styled
13
+ def plot_qq(
14
+ table: DataTable,
15
+ title: str = "",
16
+ colors: list | None = None,
17
+ ) -> matplotlib.figure.Figure:
18
+ groups = table.group_arrays()
19
+ names = [n for n, a in groups.items() if len(a) >= 3]
20
+ n_plots = len(names)
21
+ if n_plots == 0:
22
+ fig, ax = plt.subplots()
23
+ ax.text(0.5, 0.5, "No data (need n ≥ 3)", ha="center", va="center", transform=ax.transAxes)
24
+ return fig
25
+
26
+ ncols = min(n_plots, 3)
27
+ nrows = int(np.ceil(n_plots / ncols))
28
+ fig, axes = plt.subplots(nrows, ncols, figsize=(ncols * 3.5, nrows * 3.5), squeeze=False)
29
+
30
+ for idx, name in enumerate(names):
31
+ row, col = divmod(idx, ncols)
32
+ ax = axes[row][col]
33
+ arr = groups[name]
34
+ color = (colors[idx] if colors and idx < len(colors) else styles.color(idx))
35
+
36
+ (osm, osr), (slope, intercept, _) = stats.probplot(arr, dist="norm")
37
+ ax.scatter(osm, osr, color=color, s=22, zorder=3, alpha=0.85, linewidths=0.3, edgecolors="white")
38
+ x_line = np.array([osm[0], osm[-1]])
39
+ ax.plot(x_line, slope * x_line + intercept, color="#555555", linewidth=1.5, zorder=2)
40
+
41
+ # Shapiro p-value annotation
42
+ if len(arr) >= 3:
43
+ _, p_sw = stats.shapiro(arr)
44
+ pstr = f"p = {p_sw:.4f}" if p_sw >= 0.0001 else "p < 0.0001"
45
+ verdict = "Normal" if p_sw > 0.05 else "Non-normal"
46
+ ax.text(0.05, 0.95, f"S-W {pstr}\n{verdict}",
47
+ transform=ax.transAxes, fontsize=7, va="top",
48
+ color="green" if p_sw > 0.05 else "red")
49
+
50
+ ax.set_title(name, fontsize=9)
51
+ ax.set_xlabel("Theoretical quantiles", fontsize=8)
52
+ ax.set_ylabel("Sample quantiles", fontsize=8)
53
+
54
+ # Hide unused axes
55
+ for idx in range(n_plots, nrows * ncols):
56
+ r, c = divmod(idx, ncols)
57
+ axes[r][c].set_visible(False)
58
+
59
+ fig.suptitle(title or f"Q-Q Plots: {table.name}", fontsize=10, y=1.01)
60
+ fig.tight_layout()
61
+ return fig