staplot 0.1.1__tar.gz → 0.1.3__tar.gz

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 (95) hide show
  1. {staplot-0.1.1/staplot.egg-info → staplot-0.1.3}/PKG-INFO +25 -1
  2. {staplot-0.1.1 → staplot-0.1.3}/README.md +22 -0
  3. {staplot-0.1.1 → staplot-0.1.3}/pyproject.toml +3 -1
  4. staplot-0.1.3/staplot/__init__.py +1 -0
  5. {staplot-0.1.1 → staplot-0.1.3}/staplot/api.py +289 -13
  6. staplot-0.1.3/staplot/plots/extras.py +293 -0
  7. staplot-0.1.3/staplot/plots/layers.py +155 -0
  8. {staplot-0.1.1 → staplot-0.1.3}/staplot/plots/lines.py +5 -3
  9. {staplot-0.1.1 → staplot-0.1.3}/staplot/plots/significance.py +2 -0
  10. staplot-0.1.3/staplot/stats/nested.py +85 -0
  11. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/main_window.py +35 -15
  12. staplot-0.1.3/staplot/ui/plot_editor.py +1037 -0
  13. {staplot-0.1.1 → staplot-0.1.3/staplot.egg-info}/PKG-INFO +25 -1
  14. {staplot-0.1.1 → staplot-0.1.3}/staplot.egg-info/SOURCES.txt +9 -0
  15. {staplot-0.1.1 → staplot-0.1.3}/staplot.egg-info/entry_points.txt +1 -0
  16. {staplot-0.1.1 → staplot-0.1.3}/staplot.egg-info/requires.txt +3 -0
  17. {staplot-0.1.1 → staplot-0.1.3}/tests/test_bracket_layout_20261119.py +10 -0
  18. staplot-0.1.3/tests/test_layers_y2_20261120.py +90 -0
  19. staplot-0.1.3/tests/test_more_kinds_20261120.py +105 -0
  20. staplot-0.1.3/tests/test_plot_editor.py +101 -0
  21. staplot-0.1.3/tests/test_plot_editor_layers_20261120.py +49 -0
  22. staplot-0.1.3/tests/test_subjects_20261120.py +37 -0
  23. staplot-0.1.1/staplot/__init__.py +0 -1
  24. {staplot-0.1.1 → staplot-0.1.3}/LICENSE +0 -0
  25. {staplot-0.1.1 → staplot-0.1.3}/setup.cfg +0 -0
  26. {staplot-0.1.1 → staplot-0.1.3}/staplot/main.py +0 -0
  27. {staplot-0.1.1 → staplot-0.1.3}/staplot/models/__init__.py +0 -0
  28. {staplot-0.1.1 → staplot-0.1.3}/staplot/models/project.py +0 -0
  29. {staplot-0.1.1 → staplot-0.1.3}/staplot/plots/__init__.py +0 -0
  30. {staplot-0.1.1 → staplot-0.1.3}/staplot/plots/bar.py +0 -0
  31. {staplot-0.1.1 → staplot-0.1.3}/staplot/plots/before_after.py +0 -0
  32. {staplot-0.1.1 → staplot-0.1.3}/staplot/plots/bland_altman.py +0 -0
  33. {staplot-0.1.1 → staplot-0.1.3}/staplot/plots/box.py +0 -0
  34. {staplot-0.1.1 → staplot-0.1.3}/staplot/plots/distribution_plot.py +0 -0
  35. {staplot-0.1.1 → staplot-0.1.3}/staplot/plots/grouped_bar.py +0 -0
  36. {staplot-0.1.1 → staplot-0.1.3}/staplot/plots/heatmap.py +0 -0
  37. {staplot-0.1.1 → staplot-0.1.3}/staplot/plots/histogram.py +0 -0
  38. {staplot-0.1.1 → staplot-0.1.3}/staplot/plots/qq.py +0 -0
  39. {staplot-0.1.1 → staplot-0.1.3}/staplot/plots/residuals.py +0 -0
  40. {staplot-0.1.1 → staplot-0.1.3}/staplot/plots/roc_plot.py +0 -0
  41. {staplot-0.1.1 → staplot-0.1.3}/staplot/plots/scatter.py +0 -0
  42. {staplot-0.1.1 → staplot-0.1.3}/staplot/plots/styles.py +0 -0
  43. {staplot-0.1.1 → staplot-0.1.3}/staplot/plots/survival.py +0 -0
  44. {staplot-0.1.1 → staplot-0.1.3}/staplot/plots/volcano.py +0 -0
  45. {staplot-0.1.1 → staplot-0.1.3}/staplot/stats/__init__.py +0 -0
  46. {staplot-0.1.1 → staplot-0.1.3}/staplot/stats/anova.py +0 -0
  47. {staplot-0.1.1 → staplot-0.1.3}/staplot/stats/chi_square.py +0 -0
  48. {staplot-0.1.1 → staplot-0.1.3}/staplot/stats/correlation.py +0 -0
  49. {staplot-0.1.1 → staplot-0.1.3}/staplot/stats/curve_fit.py +0 -0
  50. {staplot-0.1.1 → staplot-0.1.3}/staplot/stats/descriptive.py +0 -0
  51. {staplot-0.1.1 → staplot-0.1.3}/staplot/stats/distribution.py +0 -0
  52. {staplot-0.1.1 → staplot-0.1.3}/staplot/stats/multiple_comparisons.py +0 -0
  53. {staplot-0.1.1 → staplot-0.1.3}/staplot/stats/normality.py +0 -0
  54. {staplot-0.1.1 → staplot-0.1.3}/staplot/stats/outliers.py +0 -0
  55. {staplot-0.1.1 → staplot-0.1.3}/staplot/stats/power.py +0 -0
  56. {staplot-0.1.1 → staplot-0.1.3}/staplot/stats/regression.py +0 -0
  57. {staplot-0.1.1 → staplot-0.1.3}/staplot/stats/repeated_measures.py +0 -0
  58. {staplot-0.1.1 → staplot-0.1.3}/staplot/stats/roc.py +0 -0
  59. {staplot-0.1.1 → staplot-0.1.3}/staplot/stats/tests.py +0 -0
  60. {staplot-0.1.1 → staplot-0.1.3}/staplot/stats/two_way_anova.py +0 -0
  61. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/__init__.py +0 -0
  62. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/analysis_dialog.py +0 -0
  63. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/axis_dialog.py +0 -0
  64. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/computed_column_dialog.py +0 -0
  65. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/contingency_table_widget.py +0 -0
  66. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/data_table_widget.py +0 -0
  67. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/distribution_inspector.py +0 -0
  68. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/figure_layout_widget.py +0 -0
  69. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/graph_gallery.py +0 -0
  70. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/graph_options_dialog.py +0 -0
  71. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/grouped_table_widget.py +0 -0
  72. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/layout_dialog.py +0 -0
  73. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/multiple_comparisons_dialog.py +0 -0
  74. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/navigator.py +0 -0
  75. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/plot_canvas.py +0 -0
  76. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/power_dialog.py +0 -0
  77. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/report_dialog.py +0 -0
  78. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/reshape_dialog.py +0 -0
  79. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/results_widget.py +0 -0
  80. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/standard_curve_dialog.py +0 -0
  81. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/test_wizard.py +0 -0
  82. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/transform_dialog.py +0 -0
  83. {staplot-0.1.1 → staplot-0.1.3}/staplot/ui/undo_commands.py +0 -0
  84. {staplot-0.1.1 → staplot-0.1.3}/staplot.egg-info/dependency_links.txt +0 -0
  85. {staplot-0.1.1 → staplot-0.1.3}/staplot.egg-info/top_level.txt +0 -0
  86. {staplot-0.1.1 → staplot-0.1.3}/tests/test_chatgpt_regressions.py +0 -0
  87. {staplot-0.1.1 → staplot-0.1.3}/tests/test_missing_values.py +0 -0
  88. {staplot-0.1.1 → staplot-0.1.3}/tests/test_plot_code.py +0 -0
  89. {staplot-0.1.1 → staplot-0.1.3}/tests/test_plot_layout.py +0 -0
  90. {staplot-0.1.1 → staplot-0.1.3}/tests/test_read_table.py +0 -0
  91. {staplot-0.1.1 → staplot-0.1.3}/tests/test_review_fixes.py +0 -0
  92. {staplot-0.1.1 → staplot-0.1.3}/tests/test_stats_text_default.py +0 -0
  93. {staplot-0.1.1 → staplot-0.1.3}/tests/test_styles_scoped.py +0 -0
  94. {staplot-0.1.1 → staplot-0.1.3}/tests/test_table_import.py +0 -0
  95. {staplot-0.1.1 → staplot-0.1.3}/tests/test_tick_labels.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: staplot
3
- Version: 0.1.1
3
+ Version: 0.1.3
4
4
  Summary: Statistical analysis and publication-quality plotting — a GraphPad Prism replacement
5
5
  Author: Benoit Aigouy
6
6
  License: BSD-2-Clause
@@ -21,6 +21,8 @@ Requires-Dist: pandas
21
21
  Provides-Extra: excel
22
22
  Requires-Dist: openpyxl; extra == "excel"
23
23
  Requires-Dist: xlrd; extra == "excel"
24
+ Provides-Extra: icons
25
+ Requires-Dist: qtawesome; extra == "icons"
24
26
  Dynamic: license-file
25
27
 
26
28
  # staplot
@@ -57,6 +59,28 @@ Desktop app:
57
59
  staplot
58
60
  ```
59
61
 
62
+ Plot editor: a table beside its plot; click any part of the plot (a group, the
63
+ points, the brackets, a title, an axis label, the tick labels, the legend, the plot
64
+ area) to change its colour, text, size or font; edit the table's cells and the plot
65
+ follows. Toolbar *Edit a plot* in the app, or:
66
+
67
+ ```
68
+ python -m staplot.ui.plot_editor counts.csv box
69
+ ```
70
+
71
+ From Python: `staplot.ui.plot_editor.PlotEditor(path, kind, kwargs)`; after OK,
72
+ `kwargs()` / `changed_kwargs()` are `api.plot`'s arguments and `text_parts()` the size
73
+ and font per part of the text. PyFigures opens it on a double-click on a data plot.
74
+ Icons come from `qtawesome` when it is installed (optional).
75
+
76
+ Beyond the basic kinds, `api.plot` takes `layers` (mean / median lines, mean ± error over
77
+ the groups), `y2` (a measure on a right-hand axis), `invert_y` / `invert_x`, `ybreak`
78
+ (a broken y axis), `y_step` / `y_format` / `log_base`, `error_side="up"`, and the kinds
79
+ `stacked` (`percent`), `dose_response` (4-parameter logistic fit, EC50), `histogram`,
80
+ `heatmap`. `api.table_from_csv(path, columns=[group, value], subject="animal")` makes the
81
+ animals the replicates (tests on their means, a SuperPlot, plus a mixed model).
82
+ `api.image_plot(path, pixel_size=0.2, unit="µm")` draws an image with its coordinate axes.
83
+
60
84
  From Python (no GUI needed, safe to run headless):
61
85
 
62
86
  ```python
@@ -32,6 +32,28 @@ Desktop app:
32
32
  staplot
33
33
  ```
34
34
 
35
+ Plot editor: a table beside its plot; click any part of the plot (a group, the
36
+ points, the brackets, a title, an axis label, the tick labels, the legend, the plot
37
+ area) to change its colour, text, size or font; edit the table's cells and the plot
38
+ follows. Toolbar *Edit a plot* in the app, or:
39
+
40
+ ```
41
+ python -m staplot.ui.plot_editor counts.csv box
42
+ ```
43
+
44
+ From Python: `staplot.ui.plot_editor.PlotEditor(path, kind, kwargs)`; after OK,
45
+ `kwargs()` / `changed_kwargs()` are `api.plot`'s arguments and `text_parts()` the size
46
+ and font per part of the text. PyFigures opens it on a double-click on a data plot.
47
+ Icons come from `qtawesome` when it is installed (optional).
48
+
49
+ Beyond the basic kinds, `api.plot` takes `layers` (mean / median lines, mean ± error over
50
+ the groups), `y2` (a measure on a right-hand axis), `invert_y` / `invert_x`, `ybreak`
51
+ (a broken y axis), `y_step` / `y_format` / `log_base`, `error_side="up"`, and the kinds
52
+ `stacked` (`percent`), `dose_response` (4-parameter logistic fit, EC50), `histogram`,
53
+ `heatmap`. `api.table_from_csv(path, columns=[group, value], subject="animal")` makes the
54
+ animals the replicates (tests on their means, a SuperPlot, plus a mixed model).
55
+ `api.image_plot(path, pixel_size=0.2, unit="µm")` draws an image with its coordinate axes.
56
+
35
57
  From Python (no GUI needed, safe to run headless):
36
58
 
37
59
  ```python
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "staplot"
7
- version = "0.1.1"
7
+ version = "0.1.3"
8
8
  description = "Statistical analysis and publication-quality plotting — a GraphPad Prism replacement"
9
9
  readme = "README.md"
10
10
  license = {text = "BSD-2-Clause"}
@@ -28,12 +28,14 @@ dependencies = [
28
28
 
29
29
  [project.optional-dependencies]
30
30
  excel = ["openpyxl", "xlrd"]
31
+ icons = ["qtawesome"]
31
32
 
32
33
  [project.urls]
33
34
  Homepage = "https://github.com/baigouy/staplot"
34
35
 
35
36
  [project.scripts]
36
37
  staplot = "staplot.main:main"
38
+ staplot-editor = "staplot.ui.plot_editor:main"
37
39
 
38
40
  [tool.setuptools.packages.find]
39
41
  where = ["."]
@@ -0,0 +1 @@
1
+ __version__ = "0.1.3"
@@ -58,7 +58,10 @@ __all__ = [
58
58
  "PLOT_KINDS",
59
59
  ]
60
60
 
61
- PLOT_KINDS = ("bar", "box", "violin", "scatter", "grouped", "split_violin", "paired", "line")
61
+ PLOT_KINDS = ("bar", "box", "violin", "scatter", "grouped", "split_violin", "paired", "line",
62
+ "stacked", "dose_response", "histogram", "heatmap")
63
+ # the kinds drawn from a two-factor table (factor A, factor B, value)
64
+ TWO_FACTOR_KINDS = ("grouped", "split_violin", "line", "stacked")
62
65
  VIOLIN_SIDES = ("both", "left", "right")
63
66
  # the parts of a plot whose colour can be set (element_colors); the groups' own colours
64
67
  # are *colors*
@@ -77,6 +80,9 @@ PLOT_ELEMENTS = {
77
80
  "mean": "the mean marker (show_mean)",
78
81
  "pair_lines": "the lines joining each subject's values (paired)",
79
82
  "reference": "the reference lines (hlines)",
83
+ "layers": "the extra layers (mean / median lines, mean ± error: layers)",
84
+ "y2": "the measure on the right-hand axis (y2)",
85
+ "subject_means": "each subject's mean (subject=: several values per animal / embryo)",
80
86
  }
81
87
  _PART_TAGS = set(PLOT_ELEMENTS) | {"bar", "box", "violin"}
82
88
 
@@ -531,7 +537,7 @@ def csv_cleaning_report(path: str, layout: str = "auto", columns=None, where=Non
531
537
 
532
538
 
533
539
  def table_from_csv(path: str, layout: str = "auto", name: str | None = None, columns=None,
534
- where=None, skip_rows=None) -> DataTable:
540
+ where=None, skip_rows=None, subject: str | None = None) -> DataTable:
535
541
  """Build a column DataTable from a CSV.
536
542
 
537
543
  *columns*: the columns used, of a wider table (e.g. ["genotype", "area"]: long
@@ -546,6 +552,8 @@ def table_from_csv(path: str, layout: str = "auto", name: str | None = None, col
546
552
  non-numeric; wide otherwise.
547
553
  """
548
554
  import pandas as pd
555
+ if subject:
556
+ return _table_with_subjects(path, columns, where, skip_rows, subject, name)
549
557
  df = _read_csv(path, columns, where, skip_rows)
550
558
  nm = name or os.path.splitext(os.path.basename(str(path)))[0]
551
559
  if df.shape[1] == 0:
@@ -574,6 +582,29 @@ def table_from_csv(path: str, layout: str = "auto", name: str | None = None, col
574
582
  return table_from_columns(columns, name=nm)
575
583
 
576
584
 
585
+ def _table_with_subjects(path, columns, where, skip_rows, subject, name=None):
586
+ """A long table (group, value) whose values belong to subjects (*subject*: the column
587
+ naming the animal / embryo / experiment): each column keeps its values' subjects."""
588
+ import pandas as pd
589
+ if not columns or len(columns) != 2:
590
+ raise ValueError("subject= needs columns=[group, value] (and the subject column named by subject)")
591
+ df = _read_csv(path, list(columns) + [subject], where, skip_rows)
592
+ gcol, vcol, scol = df.columns[0], df.columns[1], df.columns[2]
593
+ vals = pd.to_numeric(df[vcol], errors="coerce")
594
+ groups: dict = {}
595
+ subs: dict = {}
596
+ for g, v, sub in zip(df[gcol], vals, df[scol]):
597
+ if not _has_label(g):
598
+ continue
599
+ groups.setdefault(str(g).strip(), []).append(v)
600
+ subs.setdefault(str(g).strip(), []).append(None if not _has_label(sub) else str(sub).strip())
601
+ t = table_from_columns(groups, name=name or os.path.splitext(os.path.basename(str(path)))[0])
602
+ for col in t.columns:
603
+ col.subjects = subs[col.name]
604
+ t.value_name, t.group_name, t.subject_name = str(vcol), str(gcol), str(scol)
605
+ return t
606
+
607
+
577
608
  def grouped_table_from_csv(path: str, name: str | None = None, columns=None,
578
609
  where=None, skip_rows=None) -> GroupedDataTable:
579
610
  """Build a two-factor GroupedDataTable from a *long* CSV with three columns:
@@ -695,9 +726,12 @@ def suggest_kind(source, columns=None, where=None, skip_rows=None) -> dict:
695
726
  if not numeric:
696
727
  return {"kind": None, "n_min": None, "reason": "no column of numbers to plot"}
697
728
  return {"kind": None, "n_min": None,
729
+ # the plot this table needs, named with its own columns (a seaborn plot
730
+ # was suggested instead; PyFigures MCP check 2026-11-21)
698
731
  "reason": (f"a tidy table with factors ({', '.join(text)}) and measures "
699
- f"({', '.join(numeric)}): say which measure against which factor "
700
- f"(in PyFigures: a seaborn plot, e.g. catplot)")}
732
+ f"({', '.join(numeric)}): pick one factor and one measure, "
733
+ f"columns=[{text[0]!r}, {numeric[-1]!r}]; another factor as a third column "
734
+ f"(grouped, split_violin) or as facet= (one plot per value)")}
701
735
  table = table_from_csv(source)
702
736
  else:
703
737
  table = source
@@ -1029,7 +1063,11 @@ def plot(table, kind: str = "bar", *, error: str = "sd", annotate: bool = True,
1029
1063
  show_points: bool = True, violin_inner: str = "lines", violin_side: str = "both",
1030
1064
  element_colors: dict | None = None, ax=None, show_n: bool = False, show_mean: bool = False,
1031
1065
  p_format: str = "stars", hlines=None, control: str | None = None, point_style: str = "jitter",
1032
- normalize: str | None = None, pairs=None, stats_text: bool = False):
1066
+ normalize: str | None = None, pairs=None, stats_text: bool = False,
1067
+ layers=None, y2: dict | None = None, invert_y: bool = False, invert_x: bool = False,
1068
+ ybreak=None, y_step: float | None = None, y_format: str | None = None, log_base: float | None = None,
1069
+ error_side: str = "both", percent: bool = False, bins=None, cmap: str | None = None,
1070
+ log_x: bool = True):
1033
1071
  """Render *table* to a matplotlib Figure and return ``(fig, stats_record)``.
1034
1072
 
1035
1073
  *kind*: ``"bar"`` | ``"box"`` | ``"violin"`` | ``"scatter"`` | ``"grouped"`` |
@@ -1095,7 +1133,185 @@ def plot(table, kind: str = "bar", *, error: str = "sd", annotate: bool = True,
1095
1133
  *stats_text*: two-factor plots (grouped, split_violin, line): the two-way ANOVA
1096
1134
  written under the axes as well. Off by default: the plot shows stars only (the
1097
1135
  groups compared at each x level), the ANOVA goes in the stats record / legend text.
1136
+ *layers*: more over the groups of a bar / box / violin / paired plot (several views of
1137
+ the same data): ``["mean_line"]`` joins the means, ``"median_line"`` the medians,
1138
+ ``"mean_error"`` adds mean ± error (:data:`plots.layers.LAYERS`).
1139
+ *y2*: another measure on a right-hand axis, at the same x (group names or the x
1140
+ values of a line plot): ``{"csv": path, "columns": [x, value], "kind": "line" |
1141
+ "points" | "bar", "label": ..., "color": ..., "error": ..., "ylim": ..., "log": ...}``;
1142
+ ``columns`` of one per x level work too. Two y axes are easily misread: use them
1143
+ only for two measures with different units.
1144
+ *invert_y* / *invert_x*: the axis upside down / right to left (depth, rank, a
1145
+ scale read downwards); the right-hand axis (y2) keeps its own direction.
1146
+ *ybreak*: ``[low, high]``: the y axis broken between these values (one tall group no
1147
+ longer flattens the others): two stacked axes, the part above *high* small.
1148
+ *y_step*: the distance between y ticks; *y_format*: ``"plain"``, ``"sci"`` (×10ⁿ),
1149
+ ``"percent"`` or a format (``"{:.1f}"``); *log_base*: 2, 10, e (with or sets a log axis).
1150
+ *error_side*: ``"up"`` / ``"down"``: only the upper / lower half of each error bar.
1151
+ Kinds: *stacked* (two-factor table: one bar per x level stacked by the other factor,
1152
+ the sum of each cell; *percent* = each bar as 100 %; chi-square / Fisher test of the
1153
+ counts); *dose_response* (first column the dose, then one column per response; mean ±
1154
+ error per dose and a 4-parameter logistic fit with its EC50; *log_x* log dose axis);
1155
+ *histogram* (one per column; *bins*); *heatmap* (the table's values; *cmap*).
1098
1156
  """
1157
+ if ybreak:
1158
+ # these were silently left out of a broken axis (PyFigures MCP check 2026-11-21)
1159
+ if y2:
1160
+ raise ValueError("a broken y axis (ybreak) and a right-hand axis (y2) cannot be combined: "
1161
+ "keep one, or show the second measure in its own plot")
1162
+ if invert_y or log_y:
1163
+ raise ValueError("a broken y axis (ybreak) cannot also be inverted or logarithmic")
1164
+ return _plot_broken(table, kind, ybreak, dict(
1165
+ error=error, annotate=annotate, only_significant=only_significant, stats_mode=stats_mode,
1166
+ title=title, ylabel=ylabel, xlabel=xlabel, colors=colors, show_title=show_title, order=order,
1167
+ show_ylabel=show_ylabel, show_xlabel=show_xlabel, rename=rename, show_points=show_points,
1168
+ violin_inner=violin_inner, violin_side=violin_side, element_colors=element_colors,
1169
+ show_n=show_n, show_mean=show_mean, p_format=p_format, hlines=hlines, control=control,
1170
+ point_style=point_style, normalize=normalize, pairs=pairs, stats_text=stats_text, layers=layers,
1171
+ error_side=error_side, y_step=y_step, y_format=y_format, percent=percent),
1172
+ dict(aspect=aspect, width=width, height=height, font_scale=font_scale,
1173
+ xtick_rotation=xtick_rotation, legend=legend), ax=ax)
1174
+ result = _plot_no_extras(table, kind, error=error, annotate=annotate, only_significant=only_significant,
1175
+ stats_mode=stats_mode, title=title, ylabel=ylabel, xlabel=xlabel, colors=colors,
1176
+ show_title=show_title, aspect=aspect, width=width, height=height,
1177
+ font_scale=font_scale, order=order, ylim=ylim, log_y=log_y,
1178
+ xtick_rotation=xtick_rotation, legend=legend, show_ylabel=show_ylabel,
1179
+ show_xlabel=show_xlabel, rename=rename, show_points=show_points,
1180
+ violin_inner=violin_inner, violin_side=violin_side,
1181
+ element_colors=element_colors, ax=ax, show_n=show_n, show_mean=show_mean,
1182
+ p_format=p_format, hlines=hlines, control=control, point_style=point_style,
1183
+ normalize=normalize, pairs=pairs, stats_text=stats_text,
1184
+ kind_options={"percent": percent, "bins": bins, "cmap": cmap, "log_x": log_x})
1185
+ if layers or y2:
1186
+ result = _with_extras(result, table, kind, ax, layers, y2, error, element_colors, order, normalize, rename)
1187
+ from .plots.extras import one_sided_errors, set_y_ticks
1188
+ one_sided_errors(result[0], error_side)
1189
+ if y_step or y_format or log_base:
1190
+ set_y_ticks(ax if ax is not None else result[0].axes[0], y_step, y_format, log_base)
1191
+ if invert_y or invert_x:
1192
+ main = ax if ax is not None else result[0].axes[0]
1193
+ if invert_y and not main.yaxis_inverted():
1194
+ main.invert_yaxis()
1195
+ if invert_x and not main.xaxis_inverted():
1196
+ main.invert_xaxis()
1197
+ return result
1198
+
1199
+
1200
+ def _plot_broken(table, kind, ybreak, kwargs, layout, ax=None):
1201
+ """:func:`plot` with its y axis broken between ybreak = [low, high]: the plot drawn
1202
+ twice, in a small upper axes (above *high*) and the main one (below *low*)."""
1203
+ import matplotlib.pyplot as plt
1204
+ from .plots.extras import broken_axes_marks
1205
+ if ax is not None:
1206
+ raise ValueError("ybreak is for a single plot, not facets")
1207
+ try:
1208
+ low, high = (float(v) for v in ybreak)
1209
+ except (TypeError, ValueError):
1210
+ raise ValueError("ybreak is [low, high]: the y axis jumps from low to high") from None
1211
+ if not low < high:
1212
+ raise ValueError("ybreak: low must be below high")
1213
+ if kind not in ("bar", "box", "violin", "paired", "grouped", "line", "scatter", "stacked"):
1214
+ raise ValueError(f"ybreak does not apply to a {kind} plot")
1215
+ fig, (top, bottom) = plt.subplots(2, 1, sharex=True, figsize=(3.6, 3.4),
1216
+ gridspec_kw={"height_ratios": [1, 2.6], "hspace": 0.06})
1217
+ title, ylabel = kwargs.pop("title", ""), kwargs.pop("ylabel", "")
1218
+ show_title = kwargs.pop("show_title", True)
1219
+ error_side, y_step, y_format = kwargs.pop("error_side", "both"), kwargs.pop("y_step", None), kwargs.pop("y_format", None)
1220
+ percent = kwargs.pop("percent", False)
1221
+ layers = kwargs.pop("layers", None)
1222
+ _f, rec = plot(table, kind, ax=top, ylabel="", title="", show_title=False, layers=layers,
1223
+ percent=percent, **kwargs)
1224
+ kw_low = dict(kwargs, annotate=False)
1225
+ plot(table, kind, ax=bottom, ylabel="", title="", show_title=False, layers=layers, percent=percent, **kw_low)
1226
+ lo0 = bottom.get_ylim()[0]
1227
+ hi0 = max(top.get_ylim()[1], high * 1.05)
1228
+ bottom.set_ylim(lo0, low)
1229
+ top.set_ylim(high, hi0)
1230
+ bottom._staplot_fixed_top = low # the brackets' re-stacking keeps the break
1231
+ top._staplot_top0 = hi0
1232
+ if top.get_legend() is not None and bottom.get_legend() is not None:
1233
+ bottom.get_legend().remove()
1234
+ for a in (top, bottom): # one label for both halves, the title on top
1235
+ a.set_title("")
1236
+ a.set_ylabel("")
1237
+ from matplotlib.text import Text
1238
+ top.set_xlabel("") # its x label (the "Bars: mean ± SD" note) under the plot only
1239
+ keep = set(top.get_yticklabels()) | {top.title, top.yaxis.label}
1240
+ for t in top.findobj(Text): # the footnote ("Bars: mean ± SD") once, under the plot
1241
+ if t not in keep and plot_part(t) != "brackets" and t not in top.get_xticklabels():
1242
+ t.set_visible(False)
1243
+ broken_axes_marks(top, bottom)
1244
+ label = ylabel or getattr(table, "value_name", "") or "Value"
1245
+ if kwargs.get("show_ylabel", True) is not False:
1246
+ # on the lower axes, centred on both halves: matplotlib keeps an axis label clear of
1247
+ # the tick labels (a figure supylabel sat on them once the panel was cropped)
1248
+ bottom.set_ylabel(label)
1249
+ b, t = bottom.get_position(), top.get_position()
1250
+ bottom.yaxis.label.set_y(((t.y1 + b.y0) / 2 - b.y0) / b.height)
1251
+ if title and show_title:
1252
+ top.set_title(title)
1253
+ from .plots.extras import one_sided_errors, set_y_ticks
1254
+ one_sided_errors(fig, error_side)
1255
+ if y_step or y_format:
1256
+ for a in (top, bottom):
1257
+ set_y_ticks(a, y_step, y_format)
1258
+ fig.tight_layout()
1259
+ _apply_layout(fig, **{k: v for k, v in layout.items() if k != "aspect"})
1260
+ if layout.get("aspect"):
1261
+ _w, h = fig.get_size_inches()
1262
+ fig.set_size_inches(max(0.2, float(layout["aspect"])) * h, h)
1263
+ fig.tight_layout()
1264
+ rec = dict(rec or {})
1265
+ rec["ybreak"] = [low, high]
1266
+ return fig, rec
1267
+
1268
+
1269
+ def image_plot(path, **kwargs):
1270
+ """An image (a mask, a segmentation, a micrograph) with its coordinate axes, in
1271
+ pixels or calibrated units: :func:`staplot.plots.extras.image_plot`."""
1272
+ from .plots.extras import image_plot as _image_plot
1273
+ return _image_plot(path, **kwargs)
1274
+
1275
+
1276
+ def _with_extras(result, table, kind, ax, layers, y2, error, element_colors, order, normalize, rename=None):
1277
+ """The layers and right-hand axis of :func:`plot`, on the drawn plot."""
1278
+ from .plots.layers import add_layers, add_y2
1279
+ fig, rec = result
1280
+ main = ax if ax is not None else fig.axes[0]
1281
+ colors = element_colors or {}
1282
+ if layers:
1283
+ if not isinstance(table, DataTable) or kind not in ("bar", "box", "violin", "paired"):
1284
+ raise ValueError("layers go over the groups of a bar, box, violin or paired plot")
1285
+ # the groups as _plot_one drew them: normalized, renamed, then in order
1286
+ t = table
1287
+ if normalize:
1288
+ t, _lbl = normalized(t, normalize)
1289
+ if rename:
1290
+ t = _renamed(t, rename)
1291
+ order = [rename.get(o, o) for o in order] if order else order
1292
+ if order:
1293
+ t = _reordered(t, order)
1294
+ add_layers(main, t.group_arrays(), layers, error=error, color=colors.get("layers"))
1295
+ if y2:
1296
+ spec = dict(y2)
1297
+ if colors.get("y2") and not spec.get("color"):
1298
+ spec["color"] = colors["y2"]
1299
+ add_y2(fig, main, spec, read_table, select_columns, error=error)
1300
+ if ax is None:
1301
+ fig.tight_layout()
1302
+ return fig, rec
1303
+
1304
+
1305
+ def _plot_no_extras(table, kind: str = "bar", *, error: str = "sd", annotate: bool = True,
1306
+ only_significant: bool = True, stats_mode: str = "auto", title: str = "",
1307
+ ylabel: str = "", xlabel: str = "", colors=None, show_title: bool = True,
1308
+ aspect=None, width=None, height=None, font_scale=None, order=None, ylim=None,
1309
+ log_y: bool = False, xtick_rotation=None, legend=None, show_ylabel: bool = True,
1310
+ show_xlabel: bool = True, rename=None, show_points: bool = True,
1311
+ violin_inner: str = "lines", violin_side: str = "both", element_colors=None, ax=None,
1312
+ show_n: bool = False, show_mean: bool = False, p_format: str = "stars", hlines=None,
1313
+ control=None, point_style: str = "jitter", normalize=None, pairs=None,
1314
+ stats_text: bool = False, kind_options=None):
1099
1315
  if normalize:
1100
1316
  if not isinstance(table, DataTable):
1101
1317
  raise ValueError("normalize applies to bar, box, violin and paired plots (one factor)")
@@ -1110,7 +1326,7 @@ def plot(table, kind: str = "bar", *, error: str = "sd", annotate: bool = True,
1110
1326
  show_title=show_title, order=order, show_ylabel=show_ylabel,
1111
1327
  show_xlabel=show_xlabel, rename=rename, show_points=show_points,
1112
1328
  violin_inner=violin_inner, violin_side=violin_side, facet_ax=ax,
1113
- control=control, pairs=pairs, stats_text=stats_text),
1329
+ control=control, pairs=pairs, stats_text=stats_text, kind_options=kind_options),
1114
1330
  table, kind, ax, element_colors, **extras))
1115
1331
  return _untagged(_details(_plot_one(table, kind, error=error, annotate=annotate, only_significant=only_significant,
1116
1332
  stats_mode=stats_mode, title=title, ylabel=ylabel, xlabel=xlabel, colors=colors,
@@ -1119,7 +1335,7 @@ def plot(table, kind: str = "bar", *, error: str = "sd", annotate: bool = True,
1119
1335
  xtick_rotation=xtick_rotation, legend=legend, show_ylabel=show_ylabel,
1120
1336
  show_xlabel=show_xlabel, rename=rename, show_points=show_points,
1121
1337
  violin_inner=violin_inner, violin_side=violin_side, element_colors=element_colors,
1122
- control=control, pairs=pairs, stats_text=stats_text),
1338
+ control=control, pairs=pairs, stats_text=stats_text, kind_options=kind_options),
1123
1339
  table, kind, None, element_colors, **extras))
1124
1340
 
1125
1341
 
@@ -1325,8 +1541,9 @@ def _plot_one(table, kind: str = "bar", *, error: str = "sd", annotate: bool = T
1325
1541
  log_y: bool = False, xtick_rotation=None, legend=None, show_ylabel: bool = True,
1326
1542
  show_xlabel: bool = True, rename=None, show_points: bool = True,
1327
1543
  violin_inner: str = "lines", violin_side: str = "both", element_colors=None,
1328
- facet_ax=None, control=None, pairs=None, stats_text=False):
1544
+ facet_ax=None, control=None, pairs=None, stats_text=False, kind_options=None):
1329
1545
  kind = kind.lower()
1546
+ kind_options = dict(kind_options or {})
1330
1547
  if isinstance(colors, dict):
1331
1548
  colors = _colors_by_name(table, kind, colors, rename)
1332
1549
  # the y label the table gives (its value column: "area (um2)") when none is asked
@@ -1344,9 +1561,15 @@ def _plot_one(table, kind: str = "bar", *, error: str = "sd", annotate: bool = T
1344
1561
 
1345
1562
  stats_record = None
1346
1563
  sig_pairs = None
1564
+ from .stats.nested import has_subjects, means_table, mixed_model
1565
+ nested = has_subjects(table) and kind in ("bar", "box", "violin")
1347
1566
  if annotate and kind in ("bar", "box", "violin"):
1348
- stats_record = auto_test(table, only_significant=only_significant,
1567
+ # several values per subject: the subjects' means are the replicates
1568
+ stats_record = auto_test(means_table(table) if nested else table, only_significant=only_significant,
1349
1569
  parametric=parametric, control=control)
1570
+ if nested:
1571
+ stats_record["unit"] = "subject means"
1572
+ stats_record["mixed_model"] = mixed_model(table)
1350
1573
  sig_pairs = stats_record["sig_pairs"] or None
1351
1574
  if pairs:
1352
1575
  sig_pairs = _chosen_pairs(stats_record, pairs, only_significant) or None
@@ -1418,6 +1641,33 @@ def _plot_one(table, kind: str = "bar", *, error: str = "sd", annotate: bool = T
1418
1641
  stats_record["split_comparisons"] = pairs
1419
1642
  if stats_text and "error" not in stats_record:
1420
1643
  _annotate_two_way(fig, stats_record, getattr(table, "factor_names", None), ax=facet_ax)
1644
+ elif kind == "stacked":
1645
+ if isinstance(table, DataTable):
1646
+ raise ValueError("a stacked bar plot needs a two-factor table: the bars (x), the stacks "
1647
+ "(colours), the count / value, e.g. columns=['genotype', 'phenotype', 'n']")
1648
+ from .plots.extras import plot_stacked, chi_square
1649
+ names = getattr(table, "factor_names", None)
1650
+ fig, counts = plot_stacked(table, percent=bool(kind_options.get("percent")), title=title,
1651
+ ylabel=ylabel if ylabel and ylabel != getattr(table, "value_name", "") else "",
1652
+ xlabel=xlabel or (names[1] if names else ""), colors=colors,
1653
+ legend_title=names[0] if names else "")
1654
+ if annotate:
1655
+ stats_record = chi_square(counts["counts"])
1656
+ stats_record["counts"] = counts["counts"]
1657
+ elif kind == "dose_response":
1658
+ if not isinstance(table, DataTable):
1659
+ raise ValueError("a dose-response plot takes the dose column then one column per response")
1660
+ from .plots.extras import plot_dose_response
1661
+ fig, stats_record = plot_dose_response(table, error=error, title=title, xlabel=xlabel, ylabel=ylabel,
1662
+ colors=colors, log_x=kind_options.get("log_x", True) is not False,
1663
+ annotate=annotate)
1664
+ elif kind == "histogram":
1665
+ fig = _plots.plot_histogram(table, bins=kind_options.get("bins") or "auto", title=title,
1666
+ xlabel=xlabel or getattr(table, "value_name", "") or "Value",
1667
+ ylabel=ylabel, colors=colors)
1668
+ elif kind == "heatmap":
1669
+ fig = _plots.plot_heatmap(table, cmap=kind_options.get("cmap") or "RdYlBu_r", title=title,
1670
+ annotate=bool(annotate))
1421
1671
  elif kind == "grouped":
1422
1672
  fig = _plots.plot_grouped_bar(table, error_type=error, title=title,
1423
1673
  ylabel=ylabel, colors=colors)
@@ -1436,6 +1686,9 @@ def _plot_one(table, kind: str = "bar", *, error: str = "sd", annotate: bool = T
1436
1686
  stats_record["within_x"], error)
1437
1687
  if stats_text and "error" not in stats_record:
1438
1688
  _annotate_two_way(fig, stats_record, getattr(table, "factor_names", None), ax=facet_ax)
1689
+ if nested:
1690
+ from .stats.nested import draw_subject_means
1691
+ draw_subject_means(facet_ax if facet_ax is not None else fig.axes[0], table)
1439
1692
  if facet_ax is not None:
1440
1693
  # one facet: the figure's size, layout and colours are set once, by plot_facets
1441
1694
  if not show_ylabel:
@@ -1520,7 +1773,7 @@ def facet_tables(path: str, kind: str, facet: str, facet_row: str | None = None,
1520
1773
  (and of *facet_row*), "day = 7" ..."""
1521
1774
  col, levels = facet_levels(path, facet, where, skip_rows)
1522
1775
  row_col, row_levels = (facet_levels(path, facet_row, where, skip_rows) if facet_row else (None, [None]))
1523
- two = kind in ("grouped", "split_violin", "line")
1776
+ two = kind in TWO_FACTOR_KINDS
1524
1777
  if columns is None:
1525
1778
  columns = [str(c) for c in read_table(path, skip_rows).columns if str(c) not in (col, row_col)]
1526
1779
  out = []
@@ -1596,8 +1849,12 @@ def plot_facets(path: str, kind: str = "box", facet: str = "", *, columns=None,
1596
1849
  per_w = 2.2 if kind in ("bar", "box", "violin") else 3.0
1597
1850
  # own y axes while drawing (each facet's brackets need their room), one range after
1598
1851
  fig, axes = plt.subplots(nr, nc, figsize=(per_w * nc + 0.6, 3.0 * nr + 0.4), squeeze=False)
1852
+ if kwargs.get("y2"):
1853
+ # every facet shares one y range: a right-hand axis would be pulled into it
1854
+ raise ValueError("y2 (a right-hand axis) is for a single plot, not facets")
1599
1855
  layout_keys = ("aspect", "width", "height", "font_scale", "ylim", "log_y", "xtick_rotation", "legend",
1600
1856
  "element_colors")
1857
+ inverted = {k: bool(kwargs.pop(k, False)) for k in ("invert_y", "invert_x")}
1601
1858
  layout = {k: kwargs.pop(k) for k in layout_keys if k in kwargs}
1602
1859
  title = kwargs.pop("title", "") # over the whole figure; each facet shows its value
1603
1860
  kwargs.pop("show_title", None)
@@ -1645,6 +1902,11 @@ def plot_facets(path: str, kind: str = "box", facet: str = "", *, columns=None,
1645
1902
  _apply_layout(fig, **{k: v for k, v in layout.items() if k != "element_colors"})
1646
1903
  if layout.get("element_colors"):
1647
1904
  apply_element_colors(fig, layout["element_colors"])
1905
+ for a in fig.axes:
1906
+ if a.get_visible() and inverted["invert_y"] and not a.yaxis_inverted():
1907
+ a.invert_yaxis()
1908
+ if a.get_visible() and inverted["invert_x"] and not a.xaxis_inverted():
1909
+ a.invert_xaxis()
1648
1910
  if title:
1649
1911
  fig.suptitle(title)
1650
1912
  top = min(top, 1 - 0.35 / fig.get_size_inches()[1])
@@ -1887,6 +2149,10 @@ def _apply_layout(fig, *, width=None, height=None, font_scale=None, ylim=None, l
1887
2149
  lo, hi = (list(ylim) + [None, None])[:2]
1888
2150
  cur_lo, cur_hi = ax.get_ylim()
1889
2151
  ax.set_ylim(cur_lo if lo is None else float(lo), cur_hi if hi is None else float(hi))
2152
+ if hi is not None:
2153
+ # the top the user asked for: the brackets re-stacked at each draw keep it
2154
+ # (they set the top back to their own, 30 -> 18.3, 2026-11-20)
2155
+ ax._staplot_fixed_top = float(hi)
1890
2156
  if xtick_rotation is not None:
1891
2157
  for t in ax.get_xticklabels():
1892
2158
  angle = float(xtick_rotation) % 180
@@ -1926,7 +2192,10 @@ def plot_code(path: str, kind: str = "bar", *, error: str = "sd", annotate: bool
1926
2192
  facet: str | None = None, facet_row: str | None = None, ncols: int | None = None,
1927
2193
  show_n: bool = False, show_mean: bool = False, p_format: str = "stars", hlines=None,
1928
2194
  control: str | None = None, point_style: str = "jitter", normalize: str | None = None,
1929
- pairs=None, stats_text: bool = False) -> str:
2195
+ pairs=None, stats_text: bool = False, layers=None, y2: dict | None = None,
2196
+ invert_y: bool = False, invert_x: bool = False, ybreak=None, y_step=None, y_format=None,
2197
+ log_base=None, error_side: str = "both", percent: bool = False, bins=None, cmap=None,
2198
+ log_x: bool = True) -> str:
1930
2199
  """The Python code of a plot (user: "can staplot print the code it used to generate
1931
2200
  the fig"): a runnable script whose first part redraws the figure with staplot, and
1932
2201
  whose second part reads the table with pandas as staplot does (separator, decimal
@@ -1963,7 +2232,14 @@ def plot_code(path: str, kind: str = "bar", *, error: str = "sd", annotate: bool
1963
2232
  ("control", control, None), ("point_style", point_style, "jitter"),
1964
2233
  ("normalize", normalize, None),
1965
2234
  ("pairs", [list(p) for p in pairs] if pairs else None, None),
1966
- ("stats_text", stats_text, False)):
2235
+ ("stats_text", stats_text, False),
2236
+ ("layers", list(layers) if layers else None, None),
2237
+ ("y2", dict(y2) if y2 else None, None),
2238
+ ("invert_y", invert_y, False), ("invert_x", invert_x, False),
2239
+ ("ybreak", list(ybreak) if ybreak else None, None), ("y_step", y_step, None),
2240
+ ("y_format", y_format, None), ("log_base", log_base, None),
2241
+ ("error_side", error_side, "both"), ("percent", percent, False),
2242
+ ("bins", bins, None), ("cmap", cmap, None), ("log_x", log_x, True)):
1967
2243
  if value != default:
1968
2244
  args.append(f"{name}={value!r}")
1969
2245
  if facet:
@@ -2007,7 +2283,7 @@ def plot_code(path: str, kind: str = "bar", *, error: str = "sd", annotate: bool
2007
2283
  control=control, order=order)
2008
2284
  out += one[one.index("# --- 2."):].splitlines()
2009
2285
  return "\n".join(out)
2010
- builder = "grouped_table_from_csv" if kind in ("grouped", "split_violin", "line") else "table_from_csv"
2286
+ builder = "grouped_table_from_csv" if kind in TWO_FACTOR_KINDS else "table_from_csv"
2011
2287
  out = [f"# Made by staplot {__version__} from {os.path.basename(split_sheet(path)[0])}"
2012
2288
  + (f" (sheet {split_sheet(path)[1]})" if split_sheet(path)[1] else "") + ".",
2013
2289
  "# Part 1 redraws the figure; part 2 runs the statistics without staplot.",