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,72 @@
1
+ """Residual diagnostic plots after regression or ANOVA."""
2
+
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ import matplotlib.figure
6
+ from scipy import stats
7
+
8
+ from . import styles
9
+
10
+
11
+ @styles.styled
12
+ def plot_residuals(
13
+ fitted: np.ndarray,
14
+ residuals: np.ndarray,
15
+ title: str = "Residual Diagnostics",
16
+ color: str | None = None,
17
+ ) -> matplotlib.figure.Figure:
18
+ """Four-panel residual diagnostic figure."""
19
+ c = color or styles.color(0)
20
+ std_res = residuals / (np.std(residuals, ddof=1) or 1.0)
21
+
22
+ fig, axes = plt.subplots(2, 2, figsize=(8, 6))
23
+
24
+ # 1. Residuals vs Fitted
25
+ ax = axes[0][0]
26
+ ax.scatter(fitted, residuals, color=c, s=22, alpha=0.75, linewidths=0.3, edgecolors="white")
27
+ ax.axhline(0, color="#888", linewidth=1, linestyle="--")
28
+ ax.set_xlabel("Fitted values"); ax.set_ylabel("Residuals")
29
+ ax.set_title("Residuals vs Fitted")
30
+
31
+ # 2. Q-Q of residuals
32
+ ax = axes[0][1]
33
+ (osm, osr), (slope, intercept, _) = stats.probplot(residuals, dist="norm")
34
+ ax.scatter(osm, osr, color=c, s=22, alpha=0.75, linewidths=0.3, edgecolors="white")
35
+ x_line = np.array([osm[0], osm[-1]])
36
+ ax.plot(x_line, slope * x_line + intercept, color="#555", linewidth=1.5)
37
+ ax.set_xlabel("Theoretical quantiles"); ax.set_ylabel("Sample quantiles")
38
+ ax.set_title("Normal Q-Q")
39
+
40
+ # 3. Scale-Location (√|std residuals| vs fitted)
41
+ ax = axes[1][0]
42
+ ax.scatter(fitted, np.sqrt(np.abs(std_res)), color=c, s=22, alpha=0.75,
43
+ linewidths=0.3, edgecolors="white")
44
+ ax.set_xlabel("Fitted values"); ax.set_ylabel("√|Standardised residuals|")
45
+ ax.set_title("Scale-Location")
46
+
47
+ # 4. Histogram of residuals
48
+ ax = axes[1][1]
49
+ ax.hist(residuals, bins="auto", color=c, alpha=0.7, edgecolor="white")
50
+ x_line2 = np.linspace(residuals.min(), residuals.max(), 200)
51
+ from scipy.stats import gaussian_kde
52
+ try:
53
+ kde = gaussian_kde(residuals)
54
+ scale = len(residuals) * (residuals.max() - residuals.min()) / max(int(np.sqrt(len(residuals))), 1)
55
+ ax.plot(x_line2, kde(x_line2) * scale, color="#333", linewidth=1.5)
56
+ except Exception:
57
+ pass
58
+ ax.set_xlabel("Residuals"); ax.set_ylabel("Count")
59
+ ax.set_title("Residual distribution")
60
+
61
+ fig.suptitle(title, fontsize=11)
62
+ fig.tight_layout()
63
+ return fig
64
+
65
+
66
+ def residuals_from_curve_fit(result) -> matplotlib.figure.Figure | None:
67
+ """Generate residual plot from a curve-fit AnalysisResult."""
68
+ d = result.details
69
+ if "r2" not in d:
70
+ return None
71
+ # We don't store raw residuals in the result yet — return None gracefully
72
+ return None
@@ -0,0 +1,40 @@
1
+ """ROC curve 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 ..stats.roc import compute_roc
9
+ from . import styles
10
+
11
+
12
+ @styles.styled
13
+ def plot_roc(
14
+ table: DataTable,
15
+ label_col: str,
16
+ score_col: str,
17
+ title: str = "",
18
+ color: str | None = None,
19
+ ) -> matplotlib.figure.Figure:
20
+ try:
21
+ labels, scores = table.paired_arrays(label_col, score_col)
22
+ fpr, tpr, auc = compute_roc(labels, scores)
23
+ except ValueError as e:
24
+ fig, ax = plt.subplots()
25
+ ax.text(0.5, 0.5, str(e), ha="center", va="center", wrap=True,
26
+ transform=ax.transAxes)
27
+ return fig
28
+ c = color or styles.color(0)
29
+
30
+ fig, ax = plt.subplots(figsize=(4.5, 4.5))
31
+ ax.plot(fpr, tpr, color=c, linewidth=2.0, label=f"AUC = {auc:.3f}")
32
+ ax.plot([0, 1], [0, 1], color="#aaaaaa", linewidth=1.0, linestyle="--", label="Random")
33
+ ax.set_xlim(-0.02, 1.02)
34
+ ax.set_ylim(-0.02, 1.02)
35
+ ax.set_xlabel("1 − Specificity (FPR)")
36
+ ax.set_ylabel("Sensitivity (TPR)")
37
+ ax.set_title(title or f"ROC: {score_col}")
38
+ ax.legend(fontsize=9)
39
+ fig.tight_layout()
40
+ return fig
@@ -0,0 +1,61 @@
1
+ import numpy as np
2
+ import matplotlib.pyplot as plt
3
+ import matplotlib.figure
4
+ from scipy import stats
5
+
6
+ from ..models.project import DataTable
7
+ from ..stats.descriptive import format_p
8
+ from . import styles
9
+
10
+
11
+ @styles.styled
12
+ def plot_scatter(
13
+ table: DataTable,
14
+ x_col: str | None = None,
15
+ y_cols: list[str] | None = None,
16
+ show_regression: bool = True,
17
+ title: str = "",
18
+ xlabel: str = "",
19
+ ylabel: str = "",
20
+ colors: list | None = None,
21
+ ) -> matplotlib.figure.Figure:
22
+ groups = table.group_arrays()
23
+ col_names = list(groups.keys())
24
+
25
+ if not col_names:
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
+ x_name = x_col or col_names[0]
31
+ y_names = y_cols or col_names[1:] if len(col_names) > 1 else col_names
32
+
33
+ fig, ax = plt.subplots(figsize=(5, 4))
34
+
35
+ for i, y_name in enumerate(y_names):
36
+ if x_name not in groups or y_name not in groups:
37
+ continue
38
+ # each point is one row: drop rows where x or y is missing / excluded
39
+ xi, yi = table.paired_arrays(x_name, y_name)
40
+ if len(xi) < 1:
41
+ continue
42
+ color = (colors[i] if colors and i < len(colors) else styles.color(i))
43
+
44
+ ax.scatter(xi, yi, color=color, s=30, zorder=3, alpha=0.8,
45
+ linewidths=0.4, edgecolors="white", label=y_name)
46
+
47
+ if show_regression and len(xi) >= 3:
48
+ slope, intercept, r, p_val, _ = stats.linregress(xi, yi)
49
+ x_line = np.linspace(xi.min(), xi.max(), 200)
50
+ ax.plot(x_line, slope * x_line + intercept, color=color, linewidth=1.5,
51
+ linestyle="--", alpha=0.8,
52
+ # format_p: "p=0.0000" printed for any p < 5e-5
53
+ label=f" R²={r**2:.3f}, {format_p(p_val)}")
54
+
55
+ ax.set_xlabel(xlabel or x_name)
56
+ ax.set_ylabel(ylabel or ", ".join(y_names))
57
+ ax.set_title(title or table.name)
58
+ if len(y_names) > 1 or show_regression:
59
+ ax.legend(fontsize=8)
60
+ fig.tight_layout()
61
+ return fig
@@ -0,0 +1,94 @@
1
+ """Prism-style significance brackets drawn on bar / box axes."""
2
+
3
+ import numpy as np
4
+ from matplotlib.axes import Axes
5
+
6
+ from ..stats.descriptive import significance_stars, format_p
7
+
8
+
9
+ def add_significance_brackets(
10
+ ax: Axes,
11
+ group_names: list[str],
12
+ pairs: list[tuple[str, str, float]],
13
+ heights: dict[str, float],
14
+ y_step_frac: float = 0.10,
15
+ tip_frac: float = 0.04,
16
+ fontsize: float = 9,
17
+ use_stars: bool = True,
18
+ color: str = "#222222",
19
+ lw: float = 1.2,
20
+ ):
21
+ """
22
+ Draw significance brackets above a bar / box plot.
23
+
24
+ Parameters
25
+ ----------
26
+ group_names : ordered list of group names (matches x-tick order)
27
+ pairs : list of (name_a, name_b, p_value)
28
+ heights : dict {name: y_top} — top of bar+error or whisker top
29
+ y_step_frac : gap between bracket levels as fraction of y-range
30
+ tip_frac : downward tick length as fraction of y-range
31
+ """
32
+ if not pairs:
33
+ return
34
+
35
+ name_to_x = {n: float(i) for i, n in enumerate(group_names)}
36
+ y_lo, y_hi = ax.get_ylim()
37
+ y_range = y_hi - y_lo
38
+ step = y_step_frac * y_range
39
+ tip = tip_frac * y_range
40
+
41
+ # Sort by span (short = lower brackets)
42
+ sorted_pairs = sorted(pairs, key=lambda t: abs(name_to_x.get(t[1], 0) - name_to_x.get(t[0], 0)))
43
+
44
+ # Track the "ceiling" at each group index position
45
+ ceiling = {n: heights.get(n, y_hi * 0.6) for n in group_names}
46
+
47
+ drawn: list[tuple[float, float, float, float, str]] = [] # (xa, xb, y, p, label)
48
+
49
+ for ga, gb, p_val in sorted_pairs:
50
+ if ga not in name_to_x or gb not in name_to_x:
51
+ continue
52
+ xa, xb = name_to_x[ga], name_to_x[gb]
53
+ lo_name, hi_name = (ga, gb) if xa < xb else (gb, ga)
54
+ lo_x, hi_x = min(xa, xb), max(xa, xb)
55
+
56
+ # All groups in the span
57
+ span_names = [n for n in group_names if lo_x <= name_to_x[n] <= hi_x]
58
+
59
+ # Bracket must sit above everything in its span + any brackets underneath
60
+ base = max(ceiling[n] for n in span_names) + step * 0.25
61
+
62
+ y_bracket = base
63
+ y_top_of_bracket = y_bracket + step * 0.4
64
+
65
+ # Update ceiling for all names in span
66
+ for n in span_names:
67
+ ceiling[n] = y_top_of_bracket + step * 0.15
68
+
69
+ label = significance_stars(p_val) if use_stars else format_p(p_val)
70
+ drawn.append((lo_x, hi_x, y_bracket, p_val, label))
71
+
72
+ for xa, xb, y, p_val, label in drawn:
73
+ # Horizontal bar
74
+ ax.plot([xa, xb], [y, y], "-", color=color, lw=lw, clip_on=False)
75
+ # Left tick
76
+ ax.plot([xa, xa], [y - tip, y], "-", color=color, lw=lw, clip_on=False)
77
+ # Right tick
78
+ ax.plot([xb, xb], [y - tip, y], "-", color=color, lw=lw, clip_on=False)
79
+ # Label
80
+ mid = (xa + xb) / 2
81
+ bold = label not in ("ns", "n/a")
82
+ ax.text(
83
+ mid, y + tip * 0.3, label,
84
+ ha="center", va="bottom",
85
+ fontsize=fontsize,
86
+ fontweight="bold" if bold else "normal",
87
+ color=color,
88
+ )
89
+
90
+ # Expand y-axis to show topmost bracket + padding
91
+ if drawn:
92
+ new_top = max(ceiling.values()) + step * 0.4
93
+ if new_top > y_hi:
94
+ ax.set_ylim(top=new_top)
@@ -0,0 +1,154 @@
1
+ """Publication-quality matplotlib style — clean, minimal, journal-ready.
2
+
3
+ The style is applied only while staplot builds a plot (:func:`styled` /
4
+ :func:`context`), never to matplotlib's global rcParams: staplot is used as a
5
+ library (e.g. PyFigures data-plot panels) and must not change how every later
6
+ matplotlib figure of the process looks."""
7
+
8
+ import functools
9
+
10
+ import matplotlib as mpl
11
+ from matplotlib import font_manager
12
+
13
+ _SANS = ["Arial", "Helvetica", "DejaVu Sans"]
14
+ # only installed ones: a family list warns about every missing family at draw time
15
+ _installed = {f.name for f in font_manager.fontManager.ttflist}
16
+ _FONT_FAMILY = [f for f in _SANS if f in _installed] or ["DejaVu Sans"]
17
+
18
+ # Base publication style
19
+ PUBLICATION_RC = {
20
+ "figure.dpi": 150,
21
+ "figure.facecolor": "white",
22
+ "axes.facecolor": "white",
23
+ "axes.edgecolor": "#333333",
24
+ "axes.linewidth": 1.2,
25
+ "axes.spines.top": False,
26
+ "axes.spines.right": False,
27
+ "axes.grid": False,
28
+ "axes.titlesize": 11,
29
+ "axes.labelsize": 10,
30
+ "axes.labelcolor": "#222222",
31
+ "xtick.labelsize": 9,
32
+ "ytick.labelsize": 9,
33
+ "xtick.direction": "out",
34
+ "ytick.direction": "out",
35
+ "xtick.major.size": 4,
36
+ "ytick.major.size": 4,
37
+ "legend.fontsize": 9,
38
+ "legend.frameon": False,
39
+ # concrete families, not "sans-serif": texts keep their family, but a generic
40
+ # one is looked up in rcParams["font.sans-serif"] when the figure is DRAWN,
41
+ # i.e. after the style context has closed
42
+ "font.family": _FONT_FAMILY,
43
+ "font.sans-serif": _SANS,
44
+ "lines.linewidth": 1.5,
45
+ "lines.markersize": 5,
46
+ "errorbar.capsize": 4,
47
+ "savefig.dpi": 300,
48
+ "savefig.bbox": "tight",
49
+ "savefig.facecolor": "white",
50
+ }
51
+
52
+ # Colorblind-friendly palette (Wong 2011)
53
+ PALETTE = [
54
+ "#0072B2", # blue
55
+ "#E69F00", # orange
56
+ "#009E73", # green
57
+ "#CC79A7", # pink
58
+ "#56B4E9", # sky blue
59
+ "#F0E442", # yellow
60
+ "#D55E00", # vermilion
61
+ "#000000", # black
62
+ ]
63
+
64
+
65
+ # ── Journal / venue presets ───────────────────────────────────────────
66
+ JOURNAL_PRESETS: dict[str, dict] = {
67
+ "Default (Staplot)": PUBLICATION_RC,
68
+
69
+ "Nature / Science": {
70
+ **PUBLICATION_RC,
71
+ "axes.titlesize": 8,
72
+ "axes.labelsize": 7,
73
+ "xtick.labelsize": 6,
74
+ "ytick.labelsize": 6,
75
+ "legend.fontsize": 6,
76
+ "lines.linewidth": 1.0,
77
+ "lines.markersize": 3,
78
+ "figure.dpi": 300,
79
+ },
80
+
81
+ "Cell / JCB": {
82
+ **PUBLICATION_RC,
83
+ "axes.titlesize": 10,
84
+ "axes.labelsize": 9,
85
+ "xtick.labelsize": 8,
86
+ "ytick.labelsize": 8,
87
+ "legend.fontsize": 8,
88
+ "lines.linewidth": 1.5,
89
+ "errorbar.capsize": 3,
90
+ },
91
+
92
+ "Classic (Prism-like)": {
93
+ **PUBLICATION_RC,
94
+ "axes.spines.top": True,
95
+ "axes.spines.right": True,
96
+ "axes.grid": True,
97
+ "axes.grid.axis": "y",
98
+ "grid.alpha": 0.3,
99
+ "grid.linestyle": "--",
100
+ "xtick.direction": "in",
101
+ "ytick.direction": "in",
102
+ },
103
+
104
+ "Monochrome": {
105
+ **PUBLICATION_RC,
106
+ "axes.prop_cycle": mpl.cycler(
107
+ color=["#000000", "#444444", "#888888", "#aaaaaa"]
108
+ ),
109
+ },
110
+ }
111
+
112
+ _current_preset: str = "Default (Staplot)"
113
+
114
+
115
+ def rc(preset: str | None = None) -> dict:
116
+ """The rcParams of *preset* (or of the current preset)."""
117
+ return dict(JOURNAL_PRESETS.get(preset or _current_preset, PUBLICATION_RC))
118
+
119
+
120
+ def context(preset: str | None = None):
121
+ """``with context():`` — the preset's rcParams, restored on exit."""
122
+ return mpl.rc_context(rc(preset))
123
+
124
+
125
+ def styled(func):
126
+ """Decorator: build the plot inside the current preset's :func:`context`."""
127
+ @functools.wraps(func)
128
+ def wrapper(*args, **kwargs):
129
+ with context():
130
+ return func(*args, **kwargs)
131
+ return wrapper
132
+
133
+
134
+ def apply(preset: str | None = None) -> dict:
135
+ """Select *preset* (if given) and return its rcParams.
136
+
137
+ Formerly updated matplotlib's global rcParams; plots now apply the preset
138
+ themselves, only while they are built (:func:`styled`)."""
139
+ if preset is not None:
140
+ set_preset(preset)
141
+ return rc()
142
+
143
+
144
+ def set_preset(preset: str):
145
+ global _current_preset
146
+ _current_preset = preset
147
+
148
+
149
+ def current_preset() -> str:
150
+ return _current_preset
151
+
152
+
153
+ def color(index: int) -> str:
154
+ return PALETTE[index % len(PALETTE)]
@@ -0,0 +1,78 @@
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
+
8
+
9
+ def _km_estimate(times: np.ndarray, events: np.ndarray):
10
+ """Kaplan-Meier estimator. events: 1=event occurred, 0=censored."""
11
+ order = np.argsort(times)
12
+ times, events = times[order], events[order]
13
+
14
+ unique_t = np.unique(times[events == 1])
15
+ n = len(times)
16
+ survival = 1.0
17
+ km_t = [0.0]
18
+ km_s = [1.0]
19
+
20
+ for t in unique_t:
21
+ at_risk = np.sum(times >= t)
22
+ deaths = np.sum((times == t) & (events == 1))
23
+ if at_risk > 0:
24
+ survival *= 1 - deaths / at_risk
25
+ km_t.append(float(t))
26
+ km_s.append(float(survival))
27
+
28
+ return np.array(km_t), np.array(km_s)
29
+
30
+
31
+ @styles.styled
32
+ def plot_survival(
33
+ table: DataTable,
34
+ time_col: str | None = None,
35
+ event_col: str | None = None,
36
+ group_col: str | None = None,
37
+ title: str = "",
38
+ xlabel: str = "Time",
39
+ ylabel: str = "Survival probability",
40
+ colors: list | None = None,
41
+ ) -> matplotlib.figure.Figure:
42
+ col_names = [c.name for c in table.columns]
43
+ if not col_names:
44
+ fig, ax = plt.subplots()
45
+ ax.text(0.5, 0.5, "No data", ha="center", va="center", transform=ax.transAxes)
46
+ return fig
47
+
48
+ fig, ax = plt.subplots(figsize=(5, 4))
49
+
50
+ if time_col and event_col:
51
+ # a subject's time and event flag come from the same row
52
+ times, events = table.paired_arrays(time_col, event_col)
53
+ km_t, km_s = _km_estimate(times, events)
54
+ ax.step(km_t, km_s, where="post", color=styles.color(0), linewidth=2)
55
+ censored = times[events == 0]
56
+ km_s_cens = np.interp(censored, km_t, km_s)
57
+ ax.scatter(censored, km_s_cens, marker="+", color=styles.color(0), s=60, zorder=4)
58
+ else:
59
+ # Treat each column as a separate survival group (values = event times, no censoring)
60
+ groups = table.group_arrays()
61
+ for i, (name, arr) in enumerate(groups.items()):
62
+ arr = arr[~np.isnan(arr)]
63
+ if len(arr) == 0:
64
+ continue
65
+ events = np.ones(len(arr))
66
+ km_t, km_s = _km_estimate(arr, events)
67
+ color = (colors[i] if colors and i < len(colors) else styles.color(i))
68
+ ax.step(km_t, km_s, where="post", color=color, linewidth=2, label=name)
69
+ if len(groups) > 1:
70
+ ax.legend()
71
+
72
+ ax.set_xlim(left=0)
73
+ ax.set_ylim(0, 1.05)
74
+ ax.set_xlabel(xlabel)
75
+ ax.set_ylabel(ylabel)
76
+ ax.set_title(title or table.name)
77
+ fig.tight_layout()
78
+ return fig
@@ -0,0 +1,110 @@
1
+ """Volcano plot — fold-change vs significance."""
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_volcano(
13
+ table: DataTable,
14
+ fc_col: str,
15
+ p_col: str,
16
+ fc_thresh: float = 1.0, # |log2 FC| threshold
17
+ p_thresh: float = 0.05, # p-value threshold (on raw p, not −log10)
18
+ title: str = "",
19
+ label_col: str | None = None,
20
+ label_top: int = 10,
21
+ color_up: str | None = None,
22
+ color_down: str | None = None,
23
+ color_ns: str = "#aaaaaa",
24
+ ) -> matplotlib.figure.Figure:
25
+ """
26
+ fc_col : log2(fold-change) column
27
+ p_col : raw p-value column (will be −log10 transformed)
28
+ fc_thresh: |log2FC| threshold for colouring (default 1 = 2×)
29
+ p_thresh : p-value significance threshold (default 0.05)
30
+ label_col: optional column of feature names for labelling top hits
31
+ label_top: how many top hits (by p-value) to label
32
+ """
33
+ groups = table.group_arrays()
34
+
35
+ if fc_col not in groups or p_col not in groups:
36
+ fig, ax = plt.subplots()
37
+ ax.text(0.5, 0.5, "Columns not found",
38
+ ha="center", va="center", transform=ax.transAxes)
39
+ return fig
40
+
41
+ # fold change, p-value and name of a feature come from the same row
42
+ fc_vals, fc_rows = table.get_column(fc_col).valid_values_with_indices()
43
+ pv_vals, pv_rows = table.get_column(p_col).valid_values_with_indices()
44
+ fc_map, pv_map = dict(zip(fc_rows, fc_vals)), dict(zip(pv_rows, pv_vals))
45
+ rows = np.array(sorted(r for r in set(fc_rows) & set(pv_rows) if pv_map[r] > 0), dtype=int)
46
+ fc = np.array([fc_map[r] for r in rows], dtype=float)
47
+ pv = np.array([pv_map[r] for r in rows], dtype=float)
48
+ log_p = -np.log10(pv)
49
+
50
+ # colours
51
+ c_up = color_up or styles.color(1) # orange
52
+ c_down = color_down or styles.color(0) # blue
53
+
54
+ up = (fc >= fc_thresh) & (pv <= p_thresh)
55
+ down = (fc <= -fc_thresh) & (pv <= p_thresh)
56
+ ns = ~(up | down)
57
+
58
+ fig, ax = plt.subplots(figsize=(5.5, 5))
59
+
60
+ ax.scatter(fc[ns], log_p[ns], color=color_ns, s=16, alpha=0.6,
61
+ linewidths=0, zorder=2)
62
+ ax.scatter(fc[down], log_p[down], color=c_down, s=18, alpha=0.8,
63
+ linewidths=0.2, edgecolors="white", zorder=3,
64
+ label=f"Down ({int(down.sum())})")
65
+ ax.scatter(fc[up], log_p[up], color=c_up, s=18, alpha=0.8,
66
+ linewidths=0.2, edgecolors="white", zorder=3,
67
+ label=f"Up ({int(up.sum())})")
68
+
69
+ # threshold lines
70
+ ax.axhline(-np.log10(p_thresh), color="#555", linewidth=0.9,
71
+ linestyle="--", zorder=1)
72
+ ax.axvline( fc_thresh, color="#555", linewidth=0.9,
73
+ linestyle="--", zorder=1)
74
+ ax.axvline(-fc_thresh, color="#555", linewidth=0.9,
75
+ linestyle="--", zorder=1)
76
+
77
+ # annotations for top hits
78
+ if label_col is not None and label_col in groups:
79
+ # labels may be text — read the raw values
80
+ labels_raw = [str(v) if v is not None else "" for v in table.get_column(label_col).values]
81
+ sig_idx = np.where(up | down)[0]
82
+ order = np.argsort(-log_p[sig_idx])[:label_top]
83
+ for k in order:
84
+ real_i = rows[sig_idx[k]] # original row of this feature
85
+ if real_i < len(labels_raw):
86
+ lbl = labels_raw[real_i]
87
+ ax.annotate(
88
+ lbl,
89
+ (fc[sig_idx[k]], log_p[sig_idx[k]]),
90
+ textcoords="offset points", xytext=(4, 4),
91
+ fontsize=6, color="#222",
92
+ )
93
+ elif label_top > 0 and (up.any() or down.any()):
94
+ # Label top hits by index number if no label column
95
+ sig_i = np.where(up | down)[0]
96
+ top_k = sig_i[np.argsort(-log_p[sig_i])[:label_top]]
97
+ for k in top_k:
98
+ ax.annotate(
99
+ str(rows[k]), # original row number
100
+ (fc[k], log_p[k]),
101
+ textcoords="offset points", xytext=(4, 3),
102
+ fontsize=6, color="#444",
103
+ )
104
+
105
+ ax.set_xlabel(r"$\log_2$(Fold Change)")
106
+ ax.set_ylabel(r"$-\log_{10}$(p-value)")
107
+ ax.set_title(title or f"Volcano: {fc_col} vs {p_col}")
108
+ ax.legend(fontsize=8)
109
+ fig.tight_layout()
110
+ return fig
@@ -0,0 +1,15 @@
1
+ from .descriptive import describe, format_p, significance_stars
2
+ from .tests import run_ttest, run_mann_whitney, run_wilcoxon
3
+ from .anova import run_one_way_anova, run_kruskal_wallis
4
+ from .curve_fit import run_curve_fit, MODELS
5
+ from .two_way_anova import run_two_way_anova
6
+ from .normality import run_normality
7
+ from .correlation import run_correlation
8
+ from .chi_square import run_chi_square, run_fisher_exact
9
+ from .repeated_measures import run_rm_anova, run_friedman
10
+ from .outliers import run_grubbs
11
+ from .power import run_power_ttest, run_power_anova
12
+ from .roc import run_roc, run_log_rank
13
+ from .regression import run_multiple_regression
14
+ from .multiple_comparisons import run_multiple_comparisons
15
+ from .distribution import run_distribution_check, fit_distributions, describe_shape