dataframe-toolkit 0.24.0__tar.gz → 0.25.0__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 (65) hide show
  1. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/PKG-INFO +11 -3
  2. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/README.md +10 -2
  3. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/pyproject.toml +1 -1
  4. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/pyproject.toml.orig +1 -1
  5. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/box_cmd.py +13 -0
  6. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/heatmap_cmd.py +167 -16
  7. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/skills/dftk/SKILL.md +3 -2
  8. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/__init__.py +0 -0
  9. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/cli.py +0 -0
  10. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/__init__.py +0 -0
  11. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/annotate_cmd.py +0 -0
  12. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/append_cmd.py +0 -0
  13. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/base.py +0 -0
  14. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/binx_cmd.py +0 -0
  15. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/chi_cmd.py +0 -0
  16. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/clean_cmd.py +0 -0
  17. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/cleannames_cmd.py +0 -0
  18. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/concat_cmd.py +0 -0
  19. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/corr_cmd.py +0 -0
  20. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/dataset_cmd.py +0 -0
  21. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/describe_cmd.py +0 -0
  22. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/eval_cmd.py +0 -0
  23. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/explode_cmd.py +0 -0
  24. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/fit_cmd.py +0 -0
  25. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/forest_cmd.py +0 -0
  26. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/func_cmd.py +0 -0
  27. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/help.py +0 -0
  28. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/hist_cmd.py +0 -0
  29. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/implode_cmd.py +0 -0
  30. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/info_cmd.py +0 -0
  31. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/interp_cmd.py +0 -0
  32. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/line_cmd.py +0 -0
  33. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/locus_cmd.py +0 -0
  34. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/manhattan_cmd.py +0 -0
  35. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/melt_cmd.py +0 -0
  36. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/merge_cmd.py +0 -0
  37. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/pairs_cmd.py +0 -0
  38. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/phewas_cmd.py +0 -0
  39. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/pivot_cmd.py +0 -0
  40. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/print_cmd.py +0 -0
  41. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/qq_cmd.py +0 -0
  42. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/query_cmd.py +0 -0
  43. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/randvar_cmd.py +0 -0
  44. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/sample_cmd.py +0 -0
  45. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/scale_cmd.py +0 -0
  46. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/scat_cmd.py +0 -0
  47. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/segid_cmd.py +0 -0
  48. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/skill_cmd.py +0 -0
  49. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/split_cmd.py +0 -0
  50. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/stat_cmd.py +0 -0
  51. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/test_cmd.py +0 -0
  52. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/transpose_cmd.py +0 -0
  53. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/wstat_cmd.py +0 -0
  54. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/common/__init__.py +0 -0
  55. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/common/copula.py +0 -0
  56. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/common/docformats.py +0 -0
  57. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/common/evalfuncs.py +0 -0
  58. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/common/gwas.py +0 -0
  59. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/common/io.py +0 -0
  60. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/common/plot.py +0 -0
  61. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/common/seed.py +0 -0
  62. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/common/seq.py +0 -0
  63. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/common/stats.py +0 -0
  64. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/io.py +0 -0
  65. {dataframe_toolkit-0.24.0 → dataframe_toolkit-0.25.0}/src/dftk/skills/dftk/references/snakemake.md +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: dataframe-toolkit
3
- Version: 0.24.0
3
+ Version: 0.25.0
4
4
  Summary: A command-line toolkit for DataFrame analysis and manipulation
5
5
  Keywords: dataframe,statistics,data analysis,CLI,TSV,pandas
6
6
  Author: Gunnar Pálsson
@@ -166,7 +166,7 @@ publication-quality output.
166
166
  | `box` | Box or violin plot (`--kind violin`) of a value by category; `-g` boxes side by side, `--points` every point jittered on top, `--count` n under each category, `--order` |
167
167
  | `hist` | Histogram or KDE (`--kde`); normalisation, cumulative mode, mean±σ annotation (`--stats`) |
168
168
  | `chi` | Corner-resolved chi-plot: whether tail dependence sits in the lower or upper corner |
169
- | `heatmap` | Coloured grid of values from a long (`-x -y -v`) or wide (`-y`) table; correlograms from `corr --all`, `--annot`, `--lower` |
169
+ | `heatmap` | Coloured grid of values from a long (`-x -y -v`) or wide (`-y`) table; correlograms from `corr --all`, `--annot`, `--lower`; `--subgraphcol` panels on one colour scale |
170
170
  | `pairs` | Scatter-plot matrix with KDEs (or histograms) on the diagonal; `-g` colours groups, `--upper corr` puts r in the upper triangle |
171
171
  | `qq` | QQ plot of p-values: observed against expected -log10(p), confidence band, genomic inflation λ; `-g` one curve and λ per group |
172
172
  | `forest` | Forest plot: one row per estimate with its interval (`--se` or `--ci lo,hi`), `--exp` for odds/hazard ratios on a log axis, `--text`/`--textcol` numbers on the right, `-g` several series per row, `--section` headers |
@@ -174,7 +174,7 @@ publication-quality output.
174
174
  | `locus` | Regional association plot: -log10(p) in one region coloured by r² with the lead variant (`--ldcol`), lead as a diamond, `--lead`/`--label` by ID or `chr:pos` |
175
175
  | `manhattan` | Genome-wide -log10(p) by position (`Chr`, `pos`, `Pval`, or `--mlogpcol`/`--chi2col`); significance lines, thinning for millions of variants, `-g`/`--subgraphcol` for several scans |
176
176
 
177
- `scat`, `line` and `hist` draw dashed reference lines with `--vline X` and `--hline Y`, each labelled when written `X:LABEL` (`--vline 412:carriers`); `forest` takes `--vline`.
177
+ `scat`, `line` and `hist` draw dashed reference lines with `--vline X` and `--hline Y`, each labelled when written `X:LABEL` (`--vline 412:carriers`); `forest` takes `--vline` and `box` `--hline`.
178
178
 
179
179
  ### Utilities
180
180
 
@@ -480,6 +480,14 @@ dftk dataset penguins -o | dftk pivot -i species -g island -v body_mass_g -f cou
480
480
  | dftk heatmap -y species --annot --cmap Blues -f penguin_counts.png
481
481
  ```
482
482
 
483
+ `--subgraphcol` draws one heatmap per value of a column, side by side. Every panel has the same rows, columns and colour scale, with one colour bar, so a colour means the same value in every panel:
484
+
485
+ ```bash
486
+ dftk dataset penguins -o | dftk pivot -i species island sex -v body_mass_g -f mean -o \
487
+ | dftk heatmap -x island -y species -v mean_body_mass_g --subgraphcol sex \
488
+ --annot --fmt .0f -f penguin_mass_by_sex.png
489
+ ```
490
+
483
491
  ### Manhattan plots
484
492
 
485
493
  `manhattan` draws -log10(p) of every variant along the genome, chromosomes end to end in order (1–22, X, Y, MT; a `chr` prefix is ignored). The columns are `Chr`, `pos` and `Pval` unless named with `--chrcol`, `--poscol` and `--pcol`; a missing default is looked for under common spellings (`CHR`, `#CHROM`, `BP`, `P`, …). `dataset gwas` is a synthetic scan to try it on:
@@ -136,7 +136,7 @@ publication-quality output.
136
136
  | `box` | Box or violin plot (`--kind violin`) of a value by category; `-g` boxes side by side, `--points` every point jittered on top, `--count` n under each category, `--order` |
137
137
  | `hist` | Histogram or KDE (`--kde`); normalisation, cumulative mode, mean±σ annotation (`--stats`) |
138
138
  | `chi` | Corner-resolved chi-plot: whether tail dependence sits in the lower or upper corner |
139
- | `heatmap` | Coloured grid of values from a long (`-x -y -v`) or wide (`-y`) table; correlograms from `corr --all`, `--annot`, `--lower` |
139
+ | `heatmap` | Coloured grid of values from a long (`-x -y -v`) or wide (`-y`) table; correlograms from `corr --all`, `--annot`, `--lower`; `--subgraphcol` panels on one colour scale |
140
140
  | `pairs` | Scatter-plot matrix with KDEs (or histograms) on the diagonal; `-g` colours groups, `--upper corr` puts r in the upper triangle |
141
141
  | `qq` | QQ plot of p-values: observed against expected -log10(p), confidence band, genomic inflation λ; `-g` one curve and λ per group |
142
142
  | `forest` | Forest plot: one row per estimate with its interval (`--se` or `--ci lo,hi`), `--exp` for odds/hazard ratios on a log axis, `--text`/`--textcol` numbers on the right, `-g` several series per row, `--section` headers |
@@ -144,7 +144,7 @@ publication-quality output.
144
144
  | `locus` | Regional association plot: -log10(p) in one region coloured by r² with the lead variant (`--ldcol`), lead as a diamond, `--lead`/`--label` by ID or `chr:pos` |
145
145
  | `manhattan` | Genome-wide -log10(p) by position (`Chr`, `pos`, `Pval`, or `--mlogpcol`/`--chi2col`); significance lines, thinning for millions of variants, `-g`/`--subgraphcol` for several scans |
146
146
 
147
- `scat`, `line` and `hist` draw dashed reference lines with `--vline X` and `--hline Y`, each labelled when written `X:LABEL` (`--vline 412:carriers`); `forest` takes `--vline`.
147
+ `scat`, `line` and `hist` draw dashed reference lines with `--vline X` and `--hline Y`, each labelled when written `X:LABEL` (`--vline 412:carriers`); `forest` takes `--vline` and `box` `--hline`.
148
148
 
149
149
  ### Utilities
150
150
 
@@ -450,6 +450,14 @@ dftk dataset penguins -o | dftk pivot -i species -g island -v body_mass_g -f cou
450
450
  | dftk heatmap -y species --annot --cmap Blues -f penguin_counts.png
451
451
  ```
452
452
 
453
+ `--subgraphcol` draws one heatmap per value of a column, side by side. Every panel has the same rows, columns and colour scale, with one colour bar, so a colour means the same value in every panel:
454
+
455
+ ```bash
456
+ dftk dataset penguins -o | dftk pivot -i species island sex -v body_mass_g -f mean -o \
457
+ | dftk heatmap -x island -y species -v mean_body_mass_g --subgraphcol sex \
458
+ --annot --fmt .0f -f penguin_mass_by_sex.png
459
+ ```
460
+
453
461
  ### Manhattan plots
454
462
 
455
463
  `manhattan` draws -log10(p) of every variant along the genome, chromosomes end to end in order (1–22, X, Y, MT; a `chr` prefix is ignored). The columns are `Chr`, `pos` and `Pval` unless named with `--chrcol`, `--poscol` and `--pcol`; a missing default is looked for under common spellings (`CHR`, `#CHROM`, `BP`, `P`, …). `dataset gwas` is a synthetic scan to try it on:
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "dataframe-toolkit"
3
- version = "0.24.0"
3
+ version = "0.25.0"
4
4
  description = "A command-line toolkit for DataFrame analysis and manipulation"
5
5
  readme = "README.md"
6
6
  keywords = [
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "dataframe-toolkit"
3
- version = "0.24.0"
3
+ version = "0.25.0"
4
4
  description = "A command-line toolkit for DataFrame analysis and manipulation"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -19,6 +19,8 @@ from dftk.common.io import check_cols, io, option_columns
19
19
  from dftk.common.plot import (
20
20
  WONG_PALETTE,
21
21
  add_figure_arguments,
22
+ add_refline_arguments,
23
+ apply_reflines,
22
24
  apply_style,
23
25
  make_figure,
24
26
  save_or_show,
@@ -53,6 +55,11 @@ Tips by day, with every bill drawn on top, and how many there are:
53
55
  dftk dataset tips -o | dftk box -x day -y tip --points --count \\
54
56
  --order Thur Fri Sat Sun -f tips.png
55
57
 
58
+ A reference line: the mean tip over all days is about 3 dollars:
59
+
60
+ dftk dataset tips -o | dftk box -x day -y tip --hline 3:mean \\
61
+ --order Thur Fri Sat Sun -f tips_mean.png
62
+
56
63
  Smokers and non-smokers side by side within each day:
57
64
 
58
65
  dftk dataset tips -o | dftk box -x day -y tip -g smoker \\
@@ -187,6 +194,7 @@ class BoxCommand(BaseCommand):
187
194
  )
188
195
 
189
196
  add_figure_arguments(parser)
197
+ add_refline_arguments(parser, vertical=False)
190
198
  parser.set_defaults(size="7x4.5")
191
199
 
192
200
  def execute(self, args: argparse.Namespace) -> None:
@@ -319,6 +327,11 @@ def draw(ax, data: pd.DataFrame, args, order, hue_order) -> None:
319
327
  title_fontsize="small",
320
328
  loc=tuple(args.legendloc) if args.legendloc else "best",
321
329
  )
330
+ before = len(ax.texts)
331
+ apply_reflines(ax, args)
332
+ for label in ax.texts[before:]:
333
+ # The line runs behind the boxes; its label stays readable over one
334
+ label.set(zorder=5, bbox=dict(fc="white", ec="none", alpha=0.8, pad=1))
322
335
  if args.ylim is not None:
323
336
  ax.set_ylim(*args.ylim)
324
337
  ax.spines[["top", "right"]].set_visible(False)
@@ -10,6 +10,9 @@ Two input shapes:
10
10
  wide (-y COL) one row per heatmap row; every other numeric
11
11
  column (or --select) is a heatmap column,
12
12
  as pivot gives it or a matrix file holds it
13
+
14
+ --subgraphcol draws one heatmap per value of a column, side by side, with the
15
+ same rows, columns and colour scale in every panel and one colour bar.
13
16
  """
14
17
 
15
18
  import argparse
@@ -23,12 +26,21 @@ from dftk.common.plot import (
23
26
  add_figure_arguments,
24
27
  apply_style,
25
28
  make_figure,
29
+ make_grouplabel,
26
30
  save_or_show,
31
+ subgraph_groups,
32
+ subgraph_layout,
27
33
  )
28
34
 
29
35
 
30
- def _matrix(df: pd.DataFrame, args: argparse.Namespace) -> pd.DataFrame:
31
- """The heatmap as a DataFrame: index = y labels, columns = x labels."""
36
+ def _matrix(
37
+ df: pd.DataFrame, args: argparse.Namespace, exclude: tuple[str, ...] = ()
38
+ ) -> pd.DataFrame:
39
+ """The heatmap as a DataFrame: index = y labels, columns = x labels.
40
+
41
+ *exclude*: columns that are never heatmap columns in wide input
42
+ (the --subgraphcol columns).
43
+ """
32
44
  if args.xcol is None and args.value is None:
33
45
  if args.ycol is None:
34
46
  raise ValueError(
@@ -40,6 +52,7 @@ def _matrix(df: pd.DataFrame, args: argparse.Namespace) -> pd.DataFrame:
40
52
  c
41
53
  for c in df.columns
42
54
  if c != args.ycol
55
+ and c not in exclude
43
56
  and pd.api.types.is_numeric_dtype(df[c])
44
57
  and not pd.api.types.is_bool_dtype(df[c])
45
58
  ]
@@ -72,14 +85,20 @@ def _fmt(values: np.ndarray, fmt: str | None) -> str:
72
85
  return "g" if finite.size and np.all(finite == np.round(finite)) else ".2f"
73
86
 
74
87
 
75
- def _heatmap(ax, fig, matrix: pd.DataFrame, args: argparse.Namespace) -> None:
88
+ def _shown(matrix: pd.DataFrame, args: argparse.Namespace) -> np.ma.MaskedArray:
89
+ """The cells drawn: missing values, and with --lower the upper triangle,
90
+ masked."""
76
91
  values = matrix.to_numpy()
77
92
  shown = np.ma.masked_invalid(values)
78
93
  if args.lower:
79
94
  if matrix.shape[0] != matrix.shape[1]:
80
95
  raise ValueError("--lower needs a square heatmap (as corr --all gives)")
81
96
  shown = np.ma.masked_where(np.triu(np.ones_like(values), k=1) > 0, shown)
97
+ return shown
98
+
82
99
 
100
+ def _scale(values: np.ndarray, args: argparse.Namespace) -> dict:
101
+ """Colour map and limits from all the cells drawn (of every panel)."""
83
102
  vmin, vmax, center = args.vmin, args.vmax, args.center
84
103
  finite = values[np.isfinite(values)]
85
104
  if center is None and finite.size and finite.min() < 0 < finite.max():
@@ -90,22 +109,42 @@ def _heatmap(ax, fig, matrix: pd.DataFrame, args: argparse.Namespace) -> None:
90
109
  half = max(abs(finite.max() - center), abs(finite.min() - center))
91
110
  vmin = center - half if vmin is None else vmin
92
111
  vmax = center + half if vmax is None else vmax
93
-
94
- mesh = ax.pcolormesh(shown, cmap=cmap, vmin=vmin, vmax=vmax)
95
- fig.colorbar(mesh, ax=ax, label=args.value or "")
112
+ elif finite.size:
113
+ # Explicit limits, so that every panel shares them
114
+ vmin = finite.min() if vmin is None else vmin
115
+ vmax = finite.max() if vmax is None else vmax
116
+ return {"cmap": cmap, "vmin": vmin, "vmax": vmax}
117
+
118
+
119
+ def _heatmap(
120
+ ax,
121
+ matrix: pd.DataFrame,
122
+ shown: np.ma.MaskedArray,
123
+ args: argparse.Namespace,
124
+ scale: dict,
125
+ fmt: str,
126
+ xticklabels: bool = True,
127
+ yticklabels: bool = True,
128
+ ):
129
+ """Draw one heatmap; return the mesh (for the colour bar)."""
130
+ mesh = ax.pcolormesh(shown, **scale)
96
131
 
97
132
  ax.set_xticks(np.arange(matrix.shape[1]) + 0.5)
98
- ax.set_xticklabels([str(c) for c in matrix.columns], rotation=45, ha="right")
133
+ if xticklabels:
134
+ ax.set_xticklabels([str(c) for c in matrix.columns], rotation=45, ha="right")
135
+ ax.set_xlabel(args.xlabel if args.xlabel is not None else (args.xcol or ""))
136
+ else:
137
+ ax.set_xticklabels([])
99
138
  ax.set_yticks(np.arange(matrix.shape[0]) + 0.5)
100
- ax.set_yticklabels([str(i) for i in matrix.index])
139
+ if yticklabels:
140
+ ax.set_yticklabels([str(i) for i in matrix.index])
141
+ ax.set_ylabel(args.ylabel if args.ylabel is not None else (args.ycol or ""))
142
+ else:
143
+ ax.set_yticklabels([])
101
144
  ax.invert_yaxis() # first row at the top, as in the table
102
- ax.set_xlabel(args.xlabel if args.xlabel is not None else (args.xcol or ""))
103
- ax.set_ylabel(args.ylabel if args.ylabel is not None else (args.ycol or ""))
104
- ax.set_title(args.title or "")
105
145
  ax.set_aspect("equal" if args.square else "auto")
106
146
 
107
147
  if args.annot:
108
- fmt = _fmt(values, args.fmt)
109
148
  for (i, j), v in np.ndenumerate(shown.filled(np.nan)):
110
149
  if np.isfinite(v):
111
150
  # Dark text on light cells, light text on dark cells
@@ -119,6 +158,38 @@ def _heatmap(ax, fig, matrix: pd.DataFrame, args: argparse.Namespace) -> None:
119
158
  va="center",
120
159
  color="black" if light else "white",
121
160
  )
161
+ return mesh
162
+
163
+
164
+ def _panels(
165
+ df: pd.DataFrame, args: argparse.Namespace
166
+ ) -> list[tuple[str, pd.DataFrame]]:
167
+ """[(title, matrix)]: one panel without --subgraphcol, else one per value,
168
+ all with the rows and columns of the whole table in first-seen order."""
169
+ if not args.subgraphcol:
170
+ return [("", _matrix(df, args))]
171
+ check_cols(df, args.subgraphcol, "--subgraphcol")
172
+ clash = set(args.subgraphcol) & {args.xcol, args.ycol, args.value}
173
+ if clash:
174
+ raise ValueError(
175
+ f"--subgraphcol {', '.join(sorted(clash))} is also -x, -y or -v"
176
+ )
177
+ exclude = tuple(args.subgraphcol)
178
+ panels = [
179
+ (
180
+ make_grouplabel(key, args.subgraphcol, args.subgraphformat),
181
+ _matrix(sub, args, exclude),
182
+ )
183
+ for key, sub in subgraph_groups(df, args.subgraphcol, args.subgraphorder)
184
+ ]
185
+ if not panels:
186
+ raise ValueError(f"--subgraphcol {' '.join(args.subgraphcol)} has no values")
187
+ # Every panel gets the rows and columns of the whole table, in the order
188
+ # they first appear there, so that the panels line up cell for cell
189
+ df = df.dropna(subset=args.subgraphcol) # as the panels (groupby) do
190
+ rows = pd.unique(df[args.ycol])
191
+ cols = pd.unique(df[args.xcol]) if args.xcol else panels[0][1].columns
192
+ return [(t, m.reindex(index=rows, columns=cols)) for t, m in panels]
122
193
 
123
194
 
124
195
  _EPILOG = """\
@@ -154,6 +225,19 @@ largest |r|, and a weak correlation looks as strong as a strong one would:
154
225
  | dftk heatmap -x col1 -y col2 -v correlation --annot --lower --square \\
155
226
  --vmin -1 --vmax 1
156
227
 
228
+ PANELS
229
+ ------
230
+ --subgraphcol draws one heatmap per value of a column, side by side
231
+ (--ncols per row, --subgraphorder, --subgraphformat for the titles). Every
232
+ panel has the rows and columns of the whole table, in the same places, and
233
+ the same colour scale, with one colour bar: a colour means the same value in
234
+ every panel. Mean body mass by species and island, one panel per sex:
235
+
236
+ dftk dataset penguins -o \\
237
+ | dftk pivot -i species island sex -v body_mass_g -f mean -o \\
238
+ | dftk heatmap -x island -y species -v mean_body_mass_g \\
239
+ --subgraphcol sex --annot --fmt .0f
240
+
157
241
  COLOURS AND NUMBERS
158
242
  -------------------
159
243
  --cmap takes any matplotlib colour map (viridis, magma, RdBu_r, coolwarm,
@@ -226,6 +310,38 @@ class HeatmapCommand(BaseCommand):
226
310
  )
227
311
  g.add_argument("--square", action="store_true", help="Square cells.")
228
312
 
313
+ s = parser.add_argument_group("panels")
314
+ s.add_argument(
315
+ "--subgraphcol",
316
+ nargs="+",
317
+ default=None,
318
+ metavar="COL",
319
+ help="One heatmap per value of this column, with the same rows, "
320
+ "columns and colour scale.",
321
+ )
322
+ s.add_argument(
323
+ "--subgraphorder",
324
+ nargs="+",
325
+ default=None,
326
+ metavar="VAL",
327
+ help="Panel order for --subgraphcol. Values not listed appear last "
328
+ "in sorted order.",
329
+ )
330
+ s.add_argument(
331
+ "--subgraphformat",
332
+ default=None,
333
+ metavar="TEMPLATE",
334
+ help="Panel title template, with {colname} placeholders, e.g. "
335
+ "'Genotype {genotype}'.",
336
+ )
337
+ s.add_argument(
338
+ "--ncols",
339
+ type=int,
340
+ default=None,
341
+ metavar="N",
342
+ help="Panels per row (default: min(panels, 3)).",
343
+ )
344
+
229
345
  add_figure_arguments(parser)
230
346
 
231
347
  def execute(self, args: argparse.Namespace) -> None:
@@ -233,8 +349,13 @@ class HeatmapCommand(BaseCommand):
233
349
  if args.select:
234
350
  check_cols(df, args.select, "--select")
235
351
  keep = [args.ycol] if args.ycol else []
352
+ keep += [c for c in args.subgraphcol or [] if c not in keep]
236
353
  df = df[keep + [c for c in args.select if c not in keep]]
237
- matrix = _matrix(df, args)
354
+ panels = _panels(df, args)
355
+ shown = [_shown(m, args) for _, m in panels]
356
+ drawn = np.concatenate([s.filled(np.nan).ravel() for s in shown])
357
+ scale = _scale(drawn, args)
358
+ fmt = _fmt(drawn, args.fmt)
238
359
 
239
360
  if args.file:
240
361
  import matplotlib
@@ -247,7 +368,37 @@ class HeatmapCommand(BaseCommand):
247
368
  plt.rc("text", usetex=True)
248
369
 
249
370
  apply_style(args)
250
- fig, axes = make_figure(args)
251
- _heatmap(axes[0][0], fig, matrix, args)
252
- fig.tight_layout()
371
+ if not args.subgraphcol:
372
+ fig, axes = make_figure(args)
373
+ ax = axes[0][0]
374
+ mesh = _heatmap(ax, panels[0][1], shown[0], args, scale, fmt)
375
+ ax.set_title(args.title or "")
376
+ fig.colorbar(mesh, ax=ax, label=args.value or "")
377
+ fig.tight_layout()
378
+ save_or_show(fig, args)
379
+ return
380
+
381
+ nrows, ncols = subgraph_layout(len(panels), args.ncols)
382
+ fig, axes = make_figure(args, nrows=nrows, ncols=ncols)
383
+ # Room for one shared colour bar; "compressed" also closes the gaps that
384
+ # --square leaves between panels
385
+ fig.set_layout_engine("compressed" if args.square else "constrained")
386
+ used = []
387
+ for idx, ((title, matrix), cells) in enumerate(zip(panels, shown, strict=True)):
388
+ row, col = divmod(idx, ncols)
389
+ ax = axes[row][col]
390
+ # Tick labels on the outer edge only: the left column, and the
391
+ # lowest panel of each column
392
+ lowest = idx + ncols >= len(panels)
393
+ mesh = _heatmap(
394
+ ax, matrix, cells, args, scale, fmt,
395
+ xticklabels=lowest, yticklabels=col == 0,
396
+ ) # fmt: skip
397
+ ax.set_title(title)
398
+ used.append(ax)
399
+ for idx in range(len(panels), nrows * ncols):
400
+ axes[idx // ncols][idx % ncols].set_visible(False)
401
+ fig.colorbar(mesh, ax=used, label=args.value or "")
402
+ if args.title:
403
+ fig.suptitle(args.title)
253
404
  save_or_show(fig, args)
@@ -150,7 +150,8 @@ for 95 % CIs; `--fit -w W --nointercept` weighted line through the origin, e.g.
150
150
  an IVW Mendelian-randomisation slope with `W = 1/se_y**2` from `eval`), `line`, `hist`
151
151
  (also KDE), `box` (box or `--kind violin` plot of `-y VALUE` by `-x CATEGORY`, `-g`
152
152
  side by side, `--points` jittered on top, `--count` n per box), `chi` (tail-dependence chi-plot), `heatmap` (coloured grid from a
153
- long table `-x COL -y COL -v VALUE`, or a wide one with `-y ROWS`; a
153
+ long table `-x COL -y COL -v VALUE`, or a wide one with `-y ROWS`; `--subgraphcol`
154
+ panels share rows, columns and one colour scale; a
154
155
  correlogram is `corr --all -o | heatmap -x col1 -y col2 -v correlation
155
156
  --annot --vmin -1 --vmax 1`), `pairs` (scatter-plot matrix with KDEs on the diagonal; `-c COL…`,
156
157
  `-g COL`, `--upper corr`), `manhattan` (genome-wide -log10(p); columns
@@ -168,7 +169,7 @@ colours by LD with the lead, `--lead`/`--label` take an ID or `chr6:32600000`),
168
169
  `--textcol Pval n` numbers on the right, `-g` series per row, `--section` headers;
169
170
  `fit -o | forest -y marker -x effect --ci cilo,cihi` plots coefficients). `-g COL`
170
171
  overlays groups, `--subgraphcol COL` makes panels. `scat`, `line`, `hist` take
171
- `--vline X[:LABEL]` / `--hline Y[:LABEL]` reference lines (`forest` takes `--vline`).
172
+ `--vline X[:LABEL]` / `--hline Y[:LABEL]` reference lines (`forest` takes `--vline`, `box` `--hline`).
172
173
 
173
174
  Other: `dataset NAME` loads a bundled example table, `annotate FILE.parquet`
174
175
  reads and writes provenance metadata, `clean` removes leftover temp pipe