staplot 0.1.1__py3-none-any.whl → 0.1.2__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.
- staplot/__init__.py +1 -1
- staplot/api.py +274 -11
- staplot/plots/extras.py +293 -0
- staplot/plots/layers.py +155 -0
- staplot/plots/lines.py +5 -3
- staplot/plots/significance.py +2 -0
- staplot/stats/nested.py +85 -0
- staplot/ui/main_window.py +35 -15
- staplot/ui/plot_editor.py +1037 -0
- {staplot-0.1.1.dist-info → staplot-0.1.2.dist-info}/METADATA +25 -1
- {staplot-0.1.1.dist-info → staplot-0.1.2.dist-info}/RECORD +15 -11
- {staplot-0.1.1.dist-info → staplot-0.1.2.dist-info}/entry_points.txt +1 -0
- {staplot-0.1.1.dist-info → staplot-0.1.2.dist-info}/WHEEL +0 -0
- {staplot-0.1.1.dist-info → staplot-0.1.2.dist-info}/licenses/LICENSE +0 -0
- {staplot-0.1.1.dist-info → staplot-0.1.2.dist-info}/top_level.txt +0 -0
staplot/__init__.py
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
__version__ = "0.1.
|
|
1
|
+
__version__ = "0.1.2"
|
staplot/api.py
CHANGED
|
@@ -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:
|
|
@@ -1029,7 +1060,11 @@ def plot(table, kind: str = "bar", *, error: str = "sd", annotate: bool = True,
|
|
|
1029
1060
|
show_points: bool = True, violin_inner: str = "lines", violin_side: str = "both",
|
|
1030
1061
|
element_colors: dict | None = None, ax=None, show_n: bool = False, show_mean: bool = False,
|
|
1031
1062
|
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
|
|
1063
|
+
normalize: str | None = None, pairs=None, stats_text: bool = False,
|
|
1064
|
+
layers=None, y2: dict | None = None, invert_y: bool = False, invert_x: bool = False,
|
|
1065
|
+
ybreak=None, y_step: float | None = None, y_format: str | None = None, log_base: float | None = None,
|
|
1066
|
+
error_side: str = "both", percent: bool = False, bins=None, cmap: str | None = None,
|
|
1067
|
+
log_x: bool = True):
|
|
1033
1068
|
"""Render *table* to a matplotlib Figure and return ``(fig, stats_record)``.
|
|
1034
1069
|
|
|
1035
1070
|
*kind*: ``"bar"`` | ``"box"`` | ``"violin"`` | ``"scatter"`` | ``"grouped"`` |
|
|
@@ -1095,7 +1130,175 @@ def plot(table, kind: str = "bar", *, error: str = "sd", annotate: bool = True,
|
|
|
1095
1130
|
*stats_text*: two-factor plots (grouped, split_violin, line): the two-way ANOVA
|
|
1096
1131
|
written under the axes as well. Off by default: the plot shows stars only (the
|
|
1097
1132
|
groups compared at each x level), the ANOVA goes in the stats record / legend text.
|
|
1133
|
+
*layers*: more over the groups of a bar / box / violin / paired plot (several views of
|
|
1134
|
+
the same data): ``["mean_line"]`` joins the means, ``"median_line"`` the medians,
|
|
1135
|
+
``"mean_error"`` adds mean ± error (:data:`plots.layers.LAYERS`).
|
|
1136
|
+
*y2*: another measure on a right-hand axis, at the same x (group names or the x
|
|
1137
|
+
values of a line plot): ``{"csv": path, "columns": [x, value], "kind": "line" |
|
|
1138
|
+
"points" | "bar", "label": ..., "color": ..., "error": ..., "ylim": ..., "log": ...}``;
|
|
1139
|
+
``columns`` of one per x level work too. Two y axes are easily misread: use them
|
|
1140
|
+
only for two measures with different units.
|
|
1141
|
+
*invert_y* / *invert_x*: the axis upside down / right to left (depth, rank, a
|
|
1142
|
+
scale read downwards); the right-hand axis (y2) keeps its own direction.
|
|
1143
|
+
*ybreak*: ``[low, high]``: the y axis broken between these values (one tall group no
|
|
1144
|
+
longer flattens the others): two stacked axes, the part above *high* small.
|
|
1145
|
+
*y_step*: the distance between y ticks; *y_format*: ``"plain"``, ``"sci"`` (×10ⁿ),
|
|
1146
|
+
``"percent"`` or a format (``"{:.1f}"``); *log_base*: 2, 10, e (with or sets a log axis).
|
|
1147
|
+
*error_side*: ``"up"`` / ``"down"``: only the upper / lower half of each error bar.
|
|
1148
|
+
Kinds: *stacked* (two-factor table: one bar per x level stacked by the other factor,
|
|
1149
|
+
the sum of each cell; *percent* = each bar as 100 %; chi-square / Fisher test of the
|
|
1150
|
+
counts); *dose_response* (first column the dose, then one column per response; mean ±
|
|
1151
|
+
error per dose and a 4-parameter logistic fit with its EC50; *log_x* log dose axis);
|
|
1152
|
+
*histogram* (one per column; *bins*); *heatmap* (the table's values; *cmap*).
|
|
1098
1153
|
"""
|
|
1154
|
+
if ybreak:
|
|
1155
|
+
return _plot_broken(table, kind, ybreak, dict(
|
|
1156
|
+
error=error, annotate=annotate, only_significant=only_significant, stats_mode=stats_mode,
|
|
1157
|
+
title=title, ylabel=ylabel, xlabel=xlabel, colors=colors, show_title=show_title, order=order,
|
|
1158
|
+
show_ylabel=show_ylabel, show_xlabel=show_xlabel, rename=rename, show_points=show_points,
|
|
1159
|
+
violin_inner=violin_inner, violin_side=violin_side, element_colors=element_colors,
|
|
1160
|
+
show_n=show_n, show_mean=show_mean, p_format=p_format, hlines=hlines, control=control,
|
|
1161
|
+
point_style=point_style, normalize=normalize, pairs=pairs, stats_text=stats_text, layers=layers,
|
|
1162
|
+
error_side=error_side, y_step=y_step, y_format=y_format, percent=percent),
|
|
1163
|
+
dict(aspect=aspect, width=width, height=height, font_scale=font_scale,
|
|
1164
|
+
xtick_rotation=xtick_rotation, legend=legend), ax=ax)
|
|
1165
|
+
result = _plot_no_extras(table, kind, error=error, annotate=annotate, only_significant=only_significant,
|
|
1166
|
+
stats_mode=stats_mode, title=title, ylabel=ylabel, xlabel=xlabel, colors=colors,
|
|
1167
|
+
show_title=show_title, aspect=aspect, width=width, height=height,
|
|
1168
|
+
font_scale=font_scale, order=order, ylim=ylim, log_y=log_y,
|
|
1169
|
+
xtick_rotation=xtick_rotation, legend=legend, show_ylabel=show_ylabel,
|
|
1170
|
+
show_xlabel=show_xlabel, rename=rename, show_points=show_points,
|
|
1171
|
+
violin_inner=violin_inner, violin_side=violin_side,
|
|
1172
|
+
element_colors=element_colors, ax=ax, show_n=show_n, show_mean=show_mean,
|
|
1173
|
+
p_format=p_format, hlines=hlines, control=control, point_style=point_style,
|
|
1174
|
+
normalize=normalize, pairs=pairs, stats_text=stats_text,
|
|
1175
|
+
kind_options={"percent": percent, "bins": bins, "cmap": cmap, "log_x": log_x})
|
|
1176
|
+
if layers or y2:
|
|
1177
|
+
result = _with_extras(result, table, kind, ax, layers, y2, error, element_colors, order, normalize, rename)
|
|
1178
|
+
from .plots.extras import one_sided_errors, set_y_ticks
|
|
1179
|
+
one_sided_errors(result[0], error_side)
|
|
1180
|
+
if y_step or y_format or log_base:
|
|
1181
|
+
set_y_ticks(ax if ax is not None else result[0].axes[0], y_step, y_format, log_base)
|
|
1182
|
+
if invert_y or invert_x:
|
|
1183
|
+
main = ax if ax is not None else result[0].axes[0]
|
|
1184
|
+
if invert_y and not main.yaxis_inverted():
|
|
1185
|
+
main.invert_yaxis()
|
|
1186
|
+
if invert_x and not main.xaxis_inverted():
|
|
1187
|
+
main.invert_xaxis()
|
|
1188
|
+
return result
|
|
1189
|
+
|
|
1190
|
+
|
|
1191
|
+
def _plot_broken(table, kind, ybreak, kwargs, layout, ax=None):
|
|
1192
|
+
""":func:`plot` with its y axis broken between ybreak = [low, high]: the plot drawn
|
|
1193
|
+
twice, in a small upper axes (above *high*) and the main one (below *low*)."""
|
|
1194
|
+
import matplotlib.pyplot as plt
|
|
1195
|
+
from .plots.extras import broken_axes_marks
|
|
1196
|
+
if ax is not None:
|
|
1197
|
+
raise ValueError("ybreak is for a single plot, not facets")
|
|
1198
|
+
try:
|
|
1199
|
+
low, high = (float(v) for v in ybreak)
|
|
1200
|
+
except (TypeError, ValueError):
|
|
1201
|
+
raise ValueError("ybreak is [low, high]: the y axis jumps from low to high") from None
|
|
1202
|
+
if not low < high:
|
|
1203
|
+
raise ValueError("ybreak: low must be below high")
|
|
1204
|
+
if kind not in ("bar", "box", "violin", "paired", "grouped", "line", "scatter", "stacked"):
|
|
1205
|
+
raise ValueError(f"ybreak does not apply to a {kind} plot")
|
|
1206
|
+
fig, (top, bottom) = plt.subplots(2, 1, sharex=True, figsize=(3.6, 3.4),
|
|
1207
|
+
gridspec_kw={"height_ratios": [1, 2.6], "hspace": 0.06})
|
|
1208
|
+
title, ylabel = kwargs.pop("title", ""), kwargs.pop("ylabel", "")
|
|
1209
|
+
show_title = kwargs.pop("show_title", True)
|
|
1210
|
+
error_side, y_step, y_format = kwargs.pop("error_side", "both"), kwargs.pop("y_step", None), kwargs.pop("y_format", None)
|
|
1211
|
+
percent = kwargs.pop("percent", False)
|
|
1212
|
+
layers = kwargs.pop("layers", None)
|
|
1213
|
+
_f, rec = plot(table, kind, ax=top, ylabel="", title="", show_title=False, layers=layers,
|
|
1214
|
+
percent=percent, **kwargs)
|
|
1215
|
+
kw_low = dict(kwargs, annotate=False)
|
|
1216
|
+
plot(table, kind, ax=bottom, ylabel="", title="", show_title=False, layers=layers, percent=percent, **kw_low)
|
|
1217
|
+
lo0 = bottom.get_ylim()[0]
|
|
1218
|
+
hi0 = max(top.get_ylim()[1], high * 1.05)
|
|
1219
|
+
bottom.set_ylim(lo0, low)
|
|
1220
|
+
top.set_ylim(high, hi0)
|
|
1221
|
+
bottom._staplot_fixed_top = low # the brackets' re-stacking keeps the break
|
|
1222
|
+
top._staplot_top0 = hi0
|
|
1223
|
+
if top.get_legend() is not None and bottom.get_legend() is not None:
|
|
1224
|
+
bottom.get_legend().remove()
|
|
1225
|
+
for a in (top, bottom): # one label for both halves, the title on top
|
|
1226
|
+
a.set_title("")
|
|
1227
|
+
a.set_ylabel("")
|
|
1228
|
+
from matplotlib.text import Text
|
|
1229
|
+
top.set_xlabel("") # its x label (the "Bars: mean ± SD" note) under the plot only
|
|
1230
|
+
keep = set(top.get_yticklabels()) | {top.title, top.yaxis.label}
|
|
1231
|
+
for t in top.findobj(Text): # the footnote ("Bars: mean ± SD") once, under the plot
|
|
1232
|
+
if t not in keep and plot_part(t) != "brackets" and t not in top.get_xticklabels():
|
|
1233
|
+
t.set_visible(False)
|
|
1234
|
+
broken_axes_marks(top, bottom)
|
|
1235
|
+
label = ylabel or getattr(table, "value_name", "") or "Value"
|
|
1236
|
+
if kwargs.get("show_ylabel", True) is not False:
|
|
1237
|
+
fig.supylabel(label, fontsize=bottom.yaxis.label.get_fontsize() or 9)
|
|
1238
|
+
if title and show_title:
|
|
1239
|
+
top.set_title(title)
|
|
1240
|
+
from .plots.extras import one_sided_errors, set_y_ticks
|
|
1241
|
+
one_sided_errors(fig, error_side)
|
|
1242
|
+
if y_step or y_format:
|
|
1243
|
+
for a in (top, bottom):
|
|
1244
|
+
set_y_ticks(a, y_step, y_format)
|
|
1245
|
+
fig.tight_layout()
|
|
1246
|
+
_apply_layout(fig, **{k: v for k, v in layout.items() if k != "aspect"})
|
|
1247
|
+
if layout.get("aspect"):
|
|
1248
|
+
_w, h = fig.get_size_inches()
|
|
1249
|
+
fig.set_size_inches(max(0.2, float(layout["aspect"])) * h, h)
|
|
1250
|
+
fig.tight_layout()
|
|
1251
|
+
rec = dict(rec or {})
|
|
1252
|
+
rec["ybreak"] = [low, high]
|
|
1253
|
+
return fig, rec
|
|
1254
|
+
|
|
1255
|
+
|
|
1256
|
+
def image_plot(path, **kwargs):
|
|
1257
|
+
"""An image (a mask, a segmentation, a micrograph) with its coordinate axes, in
|
|
1258
|
+
pixels or calibrated units: :func:`staplot.plots.extras.image_plot`."""
|
|
1259
|
+
from .plots.extras import image_plot as _image_plot
|
|
1260
|
+
return _image_plot(path, **kwargs)
|
|
1261
|
+
|
|
1262
|
+
|
|
1263
|
+
def _with_extras(result, table, kind, ax, layers, y2, error, element_colors, order, normalize, rename=None):
|
|
1264
|
+
"""The layers and right-hand axis of :func:`plot`, on the drawn plot."""
|
|
1265
|
+
from .plots.layers import add_layers, add_y2
|
|
1266
|
+
fig, rec = result
|
|
1267
|
+
main = ax if ax is not None else fig.axes[0]
|
|
1268
|
+
colors = element_colors or {}
|
|
1269
|
+
if layers:
|
|
1270
|
+
if not isinstance(table, DataTable) or kind not in ("bar", "box", "violin", "paired"):
|
|
1271
|
+
raise ValueError("layers go over the groups of a bar, box, violin or paired plot")
|
|
1272
|
+
# the groups as _plot_one drew them: normalized, renamed, then in order
|
|
1273
|
+
t = table
|
|
1274
|
+
if normalize:
|
|
1275
|
+
t, _lbl = normalized(t, normalize)
|
|
1276
|
+
if rename:
|
|
1277
|
+
t = _renamed(t, rename)
|
|
1278
|
+
order = [rename.get(o, o) for o in order] if order else order
|
|
1279
|
+
if order:
|
|
1280
|
+
t = _reordered(t, order)
|
|
1281
|
+
add_layers(main, t.group_arrays(), layers, error=error, color=colors.get("layers"))
|
|
1282
|
+
if y2:
|
|
1283
|
+
spec = dict(y2)
|
|
1284
|
+
if colors.get("y2") and not spec.get("color"):
|
|
1285
|
+
spec["color"] = colors["y2"]
|
|
1286
|
+
add_y2(fig, main, spec, read_table, select_columns, error=error)
|
|
1287
|
+
if ax is None:
|
|
1288
|
+
fig.tight_layout()
|
|
1289
|
+
return fig, rec
|
|
1290
|
+
|
|
1291
|
+
|
|
1292
|
+
def _plot_no_extras(table, kind: str = "bar", *, error: str = "sd", annotate: bool = True,
|
|
1293
|
+
only_significant: bool = True, stats_mode: str = "auto", title: str = "",
|
|
1294
|
+
ylabel: str = "", xlabel: str = "", colors=None, show_title: bool = True,
|
|
1295
|
+
aspect=None, width=None, height=None, font_scale=None, order=None, ylim=None,
|
|
1296
|
+
log_y: bool = False, xtick_rotation=None, legend=None, show_ylabel: bool = True,
|
|
1297
|
+
show_xlabel: bool = True, rename=None, show_points: bool = True,
|
|
1298
|
+
violin_inner: str = "lines", violin_side: str = "both", element_colors=None, ax=None,
|
|
1299
|
+
show_n: bool = False, show_mean: bool = False, p_format: str = "stars", hlines=None,
|
|
1300
|
+
control=None, point_style: str = "jitter", normalize=None, pairs=None,
|
|
1301
|
+
stats_text: bool = False, kind_options=None):
|
|
1099
1302
|
if normalize:
|
|
1100
1303
|
if not isinstance(table, DataTable):
|
|
1101
1304
|
raise ValueError("normalize applies to bar, box, violin and paired plots (one factor)")
|
|
@@ -1110,7 +1313,7 @@ def plot(table, kind: str = "bar", *, error: str = "sd", annotate: bool = True,
|
|
|
1110
1313
|
show_title=show_title, order=order, show_ylabel=show_ylabel,
|
|
1111
1314
|
show_xlabel=show_xlabel, rename=rename, show_points=show_points,
|
|
1112
1315
|
violin_inner=violin_inner, violin_side=violin_side, facet_ax=ax,
|
|
1113
|
-
control=control, pairs=pairs, stats_text=stats_text),
|
|
1316
|
+
control=control, pairs=pairs, stats_text=stats_text, kind_options=kind_options),
|
|
1114
1317
|
table, kind, ax, element_colors, **extras))
|
|
1115
1318
|
return _untagged(_details(_plot_one(table, kind, error=error, annotate=annotate, only_significant=only_significant,
|
|
1116
1319
|
stats_mode=stats_mode, title=title, ylabel=ylabel, xlabel=xlabel, colors=colors,
|
|
@@ -1119,7 +1322,7 @@ def plot(table, kind: str = "bar", *, error: str = "sd", annotate: bool = True,
|
|
|
1119
1322
|
xtick_rotation=xtick_rotation, legend=legend, show_ylabel=show_ylabel,
|
|
1120
1323
|
show_xlabel=show_xlabel, rename=rename, show_points=show_points,
|
|
1121
1324
|
violin_inner=violin_inner, violin_side=violin_side, element_colors=element_colors,
|
|
1122
|
-
control=control, pairs=pairs, stats_text=stats_text),
|
|
1325
|
+
control=control, pairs=pairs, stats_text=stats_text, kind_options=kind_options),
|
|
1123
1326
|
table, kind, None, element_colors, **extras))
|
|
1124
1327
|
|
|
1125
1328
|
|
|
@@ -1325,8 +1528,9 @@ def _plot_one(table, kind: str = "bar", *, error: str = "sd", annotate: bool = T
|
|
|
1325
1528
|
log_y: bool = False, xtick_rotation=None, legend=None, show_ylabel: bool = True,
|
|
1326
1529
|
show_xlabel: bool = True, rename=None, show_points: bool = True,
|
|
1327
1530
|
violin_inner: str = "lines", violin_side: str = "both", element_colors=None,
|
|
1328
|
-
facet_ax=None, control=None, pairs=None, stats_text=False):
|
|
1531
|
+
facet_ax=None, control=None, pairs=None, stats_text=False, kind_options=None):
|
|
1329
1532
|
kind = kind.lower()
|
|
1533
|
+
kind_options = dict(kind_options or {})
|
|
1330
1534
|
if isinstance(colors, dict):
|
|
1331
1535
|
colors = _colors_by_name(table, kind, colors, rename)
|
|
1332
1536
|
# the y label the table gives (its value column: "area (um2)") when none is asked
|
|
@@ -1344,9 +1548,15 @@ def _plot_one(table, kind: str = "bar", *, error: str = "sd", annotate: bool = T
|
|
|
1344
1548
|
|
|
1345
1549
|
stats_record = None
|
|
1346
1550
|
sig_pairs = None
|
|
1551
|
+
from .stats.nested import has_subjects, means_table, mixed_model
|
|
1552
|
+
nested = has_subjects(table) and kind in ("bar", "box", "violin")
|
|
1347
1553
|
if annotate and kind in ("bar", "box", "violin"):
|
|
1348
|
-
|
|
1554
|
+
# several values per subject: the subjects' means are the replicates
|
|
1555
|
+
stats_record = auto_test(means_table(table) if nested else table, only_significant=only_significant,
|
|
1349
1556
|
parametric=parametric, control=control)
|
|
1557
|
+
if nested:
|
|
1558
|
+
stats_record["unit"] = "subject means"
|
|
1559
|
+
stats_record["mixed_model"] = mixed_model(table)
|
|
1350
1560
|
sig_pairs = stats_record["sig_pairs"] or None
|
|
1351
1561
|
if pairs:
|
|
1352
1562
|
sig_pairs = _chosen_pairs(stats_record, pairs, only_significant) or None
|
|
@@ -1418,6 +1628,33 @@ def _plot_one(table, kind: str = "bar", *, error: str = "sd", annotate: bool = T
|
|
|
1418
1628
|
stats_record["split_comparisons"] = pairs
|
|
1419
1629
|
if stats_text and "error" not in stats_record:
|
|
1420
1630
|
_annotate_two_way(fig, stats_record, getattr(table, "factor_names", None), ax=facet_ax)
|
|
1631
|
+
elif kind == "stacked":
|
|
1632
|
+
if isinstance(table, DataTable):
|
|
1633
|
+
raise ValueError("a stacked bar plot needs a two-factor table: the bars (x), the stacks "
|
|
1634
|
+
"(colours), the count / value, e.g. columns=['genotype', 'phenotype', 'n']")
|
|
1635
|
+
from .plots.extras import plot_stacked, chi_square
|
|
1636
|
+
names = getattr(table, "factor_names", None)
|
|
1637
|
+
fig, counts = plot_stacked(table, percent=bool(kind_options.get("percent")), title=title,
|
|
1638
|
+
ylabel=ylabel if ylabel and ylabel != getattr(table, "value_name", "") else "",
|
|
1639
|
+
xlabel=xlabel or (names[1] if names else ""), colors=colors,
|
|
1640
|
+
legend_title=names[0] if names else "")
|
|
1641
|
+
if annotate:
|
|
1642
|
+
stats_record = chi_square(counts["counts"])
|
|
1643
|
+
stats_record["counts"] = counts["counts"]
|
|
1644
|
+
elif kind == "dose_response":
|
|
1645
|
+
if not isinstance(table, DataTable):
|
|
1646
|
+
raise ValueError("a dose-response plot takes the dose column then one column per response")
|
|
1647
|
+
from .plots.extras import plot_dose_response
|
|
1648
|
+
fig, stats_record = plot_dose_response(table, error=error, title=title, xlabel=xlabel, ylabel=ylabel,
|
|
1649
|
+
colors=colors, log_x=kind_options.get("log_x", True) is not False,
|
|
1650
|
+
annotate=annotate)
|
|
1651
|
+
elif kind == "histogram":
|
|
1652
|
+
fig = _plots.plot_histogram(table, bins=kind_options.get("bins") or "auto", title=title,
|
|
1653
|
+
xlabel=xlabel or getattr(table, "value_name", "") or "Value",
|
|
1654
|
+
ylabel=ylabel, colors=colors)
|
|
1655
|
+
elif kind == "heatmap":
|
|
1656
|
+
fig = _plots.plot_heatmap(table, cmap=kind_options.get("cmap") or "RdYlBu_r", title=title,
|
|
1657
|
+
annotate=bool(annotate))
|
|
1421
1658
|
elif kind == "grouped":
|
|
1422
1659
|
fig = _plots.plot_grouped_bar(table, error_type=error, title=title,
|
|
1423
1660
|
ylabel=ylabel, colors=colors)
|
|
@@ -1436,6 +1673,9 @@ def _plot_one(table, kind: str = "bar", *, error: str = "sd", annotate: bool = T
|
|
|
1436
1673
|
stats_record["within_x"], error)
|
|
1437
1674
|
if stats_text and "error" not in stats_record:
|
|
1438
1675
|
_annotate_two_way(fig, stats_record, getattr(table, "factor_names", None), ax=facet_ax)
|
|
1676
|
+
if nested:
|
|
1677
|
+
from .stats.nested import draw_subject_means
|
|
1678
|
+
draw_subject_means(facet_ax if facet_ax is not None else fig.axes[0], table)
|
|
1439
1679
|
if facet_ax is not None:
|
|
1440
1680
|
# one facet: the figure's size, layout and colours are set once, by plot_facets
|
|
1441
1681
|
if not show_ylabel:
|
|
@@ -1520,7 +1760,7 @@ def facet_tables(path: str, kind: str, facet: str, facet_row: str | None = None,
|
|
|
1520
1760
|
(and of *facet_row*), "day = 7" ..."""
|
|
1521
1761
|
col, levels = facet_levels(path, facet, where, skip_rows)
|
|
1522
1762
|
row_col, row_levels = (facet_levels(path, facet_row, where, skip_rows) if facet_row else (None, [None]))
|
|
1523
|
-
two = kind in
|
|
1763
|
+
two = kind in TWO_FACTOR_KINDS
|
|
1524
1764
|
if columns is None:
|
|
1525
1765
|
columns = [str(c) for c in read_table(path, skip_rows).columns if str(c) not in (col, row_col)]
|
|
1526
1766
|
out = []
|
|
@@ -1596,8 +1836,12 @@ def plot_facets(path: str, kind: str = "box", facet: str = "", *, columns=None,
|
|
|
1596
1836
|
per_w = 2.2 if kind in ("bar", "box", "violin") else 3.0
|
|
1597
1837
|
# own y axes while drawing (each facet's brackets need their room), one range after
|
|
1598
1838
|
fig, axes = plt.subplots(nr, nc, figsize=(per_w * nc + 0.6, 3.0 * nr + 0.4), squeeze=False)
|
|
1839
|
+
if kwargs.get("y2"):
|
|
1840
|
+
# every facet shares one y range: a right-hand axis would be pulled into it
|
|
1841
|
+
raise ValueError("y2 (a right-hand axis) is for a single plot, not facets")
|
|
1599
1842
|
layout_keys = ("aspect", "width", "height", "font_scale", "ylim", "log_y", "xtick_rotation", "legend",
|
|
1600
1843
|
"element_colors")
|
|
1844
|
+
inverted = {k: bool(kwargs.pop(k, False)) for k in ("invert_y", "invert_x")}
|
|
1601
1845
|
layout = {k: kwargs.pop(k) for k in layout_keys if k in kwargs}
|
|
1602
1846
|
title = kwargs.pop("title", "") # over the whole figure; each facet shows its value
|
|
1603
1847
|
kwargs.pop("show_title", None)
|
|
@@ -1645,6 +1889,11 @@ def plot_facets(path: str, kind: str = "box", facet: str = "", *, columns=None,
|
|
|
1645
1889
|
_apply_layout(fig, **{k: v for k, v in layout.items() if k != "element_colors"})
|
|
1646
1890
|
if layout.get("element_colors"):
|
|
1647
1891
|
apply_element_colors(fig, layout["element_colors"])
|
|
1892
|
+
for a in fig.axes:
|
|
1893
|
+
if a.get_visible() and inverted["invert_y"] and not a.yaxis_inverted():
|
|
1894
|
+
a.invert_yaxis()
|
|
1895
|
+
if a.get_visible() and inverted["invert_x"] and not a.xaxis_inverted():
|
|
1896
|
+
a.invert_xaxis()
|
|
1648
1897
|
if title:
|
|
1649
1898
|
fig.suptitle(title)
|
|
1650
1899
|
top = min(top, 1 - 0.35 / fig.get_size_inches()[1])
|
|
@@ -1887,6 +2136,10 @@ def _apply_layout(fig, *, width=None, height=None, font_scale=None, ylim=None, l
|
|
|
1887
2136
|
lo, hi = (list(ylim) + [None, None])[:2]
|
|
1888
2137
|
cur_lo, cur_hi = ax.get_ylim()
|
|
1889
2138
|
ax.set_ylim(cur_lo if lo is None else float(lo), cur_hi if hi is None else float(hi))
|
|
2139
|
+
if hi is not None:
|
|
2140
|
+
# the top the user asked for: the brackets re-stacked at each draw keep it
|
|
2141
|
+
# (they set the top back to their own, 30 -> 18.3, 2026-11-20)
|
|
2142
|
+
ax._staplot_fixed_top = float(hi)
|
|
1890
2143
|
if xtick_rotation is not None:
|
|
1891
2144
|
for t in ax.get_xticklabels():
|
|
1892
2145
|
angle = float(xtick_rotation) % 180
|
|
@@ -1926,7 +2179,10 @@ def plot_code(path: str, kind: str = "bar", *, error: str = "sd", annotate: bool
|
|
|
1926
2179
|
facet: str | None = None, facet_row: str | None = None, ncols: int | None = None,
|
|
1927
2180
|
show_n: bool = False, show_mean: bool = False, p_format: str = "stars", hlines=None,
|
|
1928
2181
|
control: str | None = None, point_style: str = "jitter", normalize: str | None = None,
|
|
1929
|
-
pairs=None, stats_text: bool = False
|
|
2182
|
+
pairs=None, stats_text: bool = False, layers=None, y2: dict | None = None,
|
|
2183
|
+
invert_y: bool = False, invert_x: bool = False, ybreak=None, y_step=None, y_format=None,
|
|
2184
|
+
log_base=None, error_side: str = "both", percent: bool = False, bins=None, cmap=None,
|
|
2185
|
+
log_x: bool = True) -> str:
|
|
1930
2186
|
"""The Python code of a plot (user: "can staplot print the code it used to generate
|
|
1931
2187
|
the fig"): a runnable script whose first part redraws the figure with staplot, and
|
|
1932
2188
|
whose second part reads the table with pandas as staplot does (separator, decimal
|
|
@@ -1963,7 +2219,14 @@ def plot_code(path: str, kind: str = "bar", *, error: str = "sd", annotate: bool
|
|
|
1963
2219
|
("control", control, None), ("point_style", point_style, "jitter"),
|
|
1964
2220
|
("normalize", normalize, None),
|
|
1965
2221
|
("pairs", [list(p) for p in pairs] if pairs else None, None),
|
|
1966
|
-
("stats_text", stats_text, False)
|
|
2222
|
+
("stats_text", stats_text, False),
|
|
2223
|
+
("layers", list(layers) if layers else None, None),
|
|
2224
|
+
("y2", dict(y2) if y2 else None, None),
|
|
2225
|
+
("invert_y", invert_y, False), ("invert_x", invert_x, False),
|
|
2226
|
+
("ybreak", list(ybreak) if ybreak else None, None), ("y_step", y_step, None),
|
|
2227
|
+
("y_format", y_format, None), ("log_base", log_base, None),
|
|
2228
|
+
("error_side", error_side, "both"), ("percent", percent, False),
|
|
2229
|
+
("bins", bins, None), ("cmap", cmap, None), ("log_x", log_x, True)):
|
|
1967
2230
|
if value != default:
|
|
1968
2231
|
args.append(f"{name}={value!r}")
|
|
1969
2232
|
if facet:
|
|
@@ -2007,7 +2270,7 @@ def plot_code(path: str, kind: str = "bar", *, error: str = "sd", annotate: bool
|
|
|
2007
2270
|
control=control, order=order)
|
|
2008
2271
|
out += one[one.index("# --- 2."):].splitlines()
|
|
2009
2272
|
return "\n".join(out)
|
|
2010
|
-
builder = "grouped_table_from_csv" if kind in
|
|
2273
|
+
builder = "grouped_table_from_csv" if kind in TWO_FACTOR_KINDS else "table_from_csv"
|
|
2011
2274
|
out = [f"# Made by staplot {__version__} from {os.path.basename(split_sheet(path)[0])}"
|
|
2012
2275
|
+ (f" (sheet {split_sheet(path)[1]})" if split_sheet(path)[1] else "") + ".",
|
|
2013
2276
|
"# Part 1 redraws the figure; part 2 runs the statistics without staplot.",
|