dataframe-toolkit 0.23.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.23.0 → dataframe_toolkit-0.25.0}/PKG-INFO +21 -3
  2. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/README.md +20 -2
  3. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/pyproject.toml +1 -1
  4. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/pyproject.toml.orig +1 -1
  5. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/__init__.py +2 -0
  6. dataframe_toolkit-0.25.0/src/dftk/commands/box_cmd.py +339 -0
  7. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/forest_cmd.py +4 -0
  8. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/heatmap_cmd.py +167 -16
  9. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/hist_cmd.py +8 -0
  10. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/line_cmd.py +13 -0
  11. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/manhattan_cmd.py +1 -0
  12. dataframe_toolkit-0.25.0/src/dftk/commands/phewas_cmd.py +421 -0
  13. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/scat_cmd.py +139 -15
  14. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/common/plot.py +76 -0
  15. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/skills/dftk/SKILL.md +11 -4
  16. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/__init__.py +0 -0
  17. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/cli.py +0 -0
  18. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/annotate_cmd.py +0 -0
  19. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/append_cmd.py +0 -0
  20. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/base.py +0 -0
  21. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/binx_cmd.py +0 -0
  22. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/chi_cmd.py +0 -0
  23. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/clean_cmd.py +0 -0
  24. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/cleannames_cmd.py +0 -0
  25. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/concat_cmd.py +0 -0
  26. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/corr_cmd.py +0 -0
  27. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/dataset_cmd.py +0 -0
  28. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/describe_cmd.py +0 -0
  29. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/eval_cmd.py +0 -0
  30. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/explode_cmd.py +0 -0
  31. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/fit_cmd.py +0 -0
  32. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/func_cmd.py +0 -0
  33. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/help.py +0 -0
  34. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/implode_cmd.py +0 -0
  35. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/info_cmd.py +0 -0
  36. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/interp_cmd.py +0 -0
  37. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/locus_cmd.py +0 -0
  38. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/melt_cmd.py +0 -0
  39. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/merge_cmd.py +0 -0
  40. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/pairs_cmd.py +0 -0
  41. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/pivot_cmd.py +0 -0
  42. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/print_cmd.py +0 -0
  43. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/qq_cmd.py +0 -0
  44. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/query_cmd.py +0 -0
  45. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/randvar_cmd.py +0 -0
  46. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/sample_cmd.py +0 -0
  47. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/scale_cmd.py +0 -0
  48. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/segid_cmd.py +0 -0
  49. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/skill_cmd.py +0 -0
  50. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/split_cmd.py +0 -0
  51. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/stat_cmd.py +0 -0
  52. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/test_cmd.py +0 -0
  53. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/transpose_cmd.py +0 -0
  54. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/commands/wstat_cmd.py +0 -0
  55. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/common/__init__.py +0 -0
  56. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/common/copula.py +0 -0
  57. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/common/docformats.py +0 -0
  58. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/common/evalfuncs.py +0 -0
  59. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/common/gwas.py +0 -0
  60. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/common/io.py +0 -0
  61. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/common/seed.py +0 -0
  62. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/common/seq.py +0 -0
  63. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/common/stats.py +0 -0
  64. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.25.0}/src/dftk/io.py +0 -0
  65. {dataframe_toolkit-0.23.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.23.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
@@ -161,17 +161,21 @@ publication-quality output.
161
161
 
162
162
  | Command | Description |
163
163
  |---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
164
- | `scat` | Scatter plot; OLS/robust or LOWESS fit (`--fit lowess`, one per group with `-g`), hexagonal binning for large tables (`--hexbin`), bubble size (`--sizecol`), colour (`--colorcol`) |
164
+ | `scat` | Scatter plot; OLS/robust or LOWESS fit (`--fit lowess`, one per group with `-g`), hexagonal binning for large tables (`--hexbin`), bubble size (`--sizecol`), colour (`--colorcol`), error bars (`--xerr`/`--yerr`, `--errscale 1.96`), weighted fit (`--fit -w W`) |
165
165
  | `line` | Line plot; optional error bars (`--yerr`) or intervals (`--yci lo,hi`), `-ls none -m o` for points only, and fit overlay |
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` |
166
167
  | `hist` | Histogram or KDE (`--kde`); normalisation, cumulative mode, mean±σ annotation (`--stats`) |
167
168
  | `chi` | Corner-resolved chi-plot: whether tail dependence sits in the lower or upper corner |
168
- | `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 |
169
170
  | `pairs` | Scatter-plot matrix with KDEs (or histograms) on the diagonal; `-g` colours groups, `--upper corr` puts r in the upper triangle |
170
171
  | `qq` | QQ plot of p-values: observed against expected -log10(p), confidence band, genomic inflation λ; `-g` one curve and λ per group |
171
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 |
173
+ | `phewas` | PheWAS plot: -log10(p) of each phenotype grouped by category (one colour each), ▲/▼ by the sign of `--betacol`, Bonferroni line, hits labelled |
172
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` |
173
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 |
174
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` and `box` `--hline`.
178
+
175
179
  ### Utilities
176
180
 
177
181
  | Command | Description |
@@ -476,6 +480,14 @@ dftk dataset penguins -o | dftk pivot -i species -g island -v body_mass_g -f cou
476
480
  | dftk heatmap -y species --annot --cmap Blues -f penguin_counts.png
477
481
  ```
478
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
+
479
491
  ### Manhattan plots
480
492
 
481
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:
@@ -518,6 +530,12 @@ dftk dataset gwas -o | dftk query -q "Chr == '6' and pos > 31.6e6 and pos < 33.6
518
530
  | dftk locus --ldcol r2 -f locus.png
519
531
  ```
520
532
 
533
+ `phewas` draws a phenome-wide scan: -log10(p) of each phenotype, the phenotypes grouped by category along the x axis in one colour per category (columns `category`, `phenotype` and `Pval` unless named with `-c`, `-l` and the p-value options of `manhattan`). With `--betacol beta` the points are triangles pointing up or down with the sign of the effect. The significance line is Bonferroni (0.05 / number of tests) unless `--sig` gives a p-value, and the phenotypes above it are labelled, at most `--label N` (default 10). One row per phenotype: pick one genotype or mask with `query` first.
534
+
535
+ ```bash
536
+ dftk dataset phewas -o | dftk query -q "genotype == 'het'" -o | dftk phewas --betacol beta -f phewas.png
537
+ ```
538
+
521
539
  `forest` draws one row per estimate: a point with its interval, labels down the left, top to bottom in file order (sort first to order them), and a reference line at 0. Give the interval as two columns (`--ci lo,hi`) or a standard error (`--se se`, ± 1.96 SE, `--level` to change). `--exp` turns log odds ratios (or any log-scale estimate) into ratios on a log axis with the reference at 1; `--text` writes `estimate [lo, hi]` to the right and `--textcol` adds columns such as the p-value or the number of carriers. `-g` puts several series on each row (het and hom carriers, two cohorts), `--section` groups rows under bold headers, `--weighted` sizes the markers by 1/SE². Coefficients from `fit`:
522
540
 
523
541
  `dataset phewas` is a simulated phenome-wide scan of loss-of-function carriers (heterozygous and homozygous rows per phenotype, log odds ratios, five real effects) to try it on:
@@ -131,17 +131,21 @@ publication-quality output.
131
131
 
132
132
  | Command | Description |
133
133
  |---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
134
- | `scat` | Scatter plot; OLS/robust or LOWESS fit (`--fit lowess`, one per group with `-g`), hexagonal binning for large tables (`--hexbin`), bubble size (`--sizecol`), colour (`--colorcol`) |
134
+ | `scat` | Scatter plot; OLS/robust or LOWESS fit (`--fit lowess`, one per group with `-g`), hexagonal binning for large tables (`--hexbin`), bubble size (`--sizecol`), colour (`--colorcol`), error bars (`--xerr`/`--yerr`, `--errscale 1.96`), weighted fit (`--fit -w W`) |
135
135
  | `line` | Line plot; optional error bars (`--yerr`) or intervals (`--yci lo,hi`), `-ls none -m o` for points only, and fit overlay |
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` |
136
137
  | `hist` | Histogram or KDE (`--kde`); normalisation, cumulative mode, mean±σ annotation (`--stats`) |
137
138
  | `chi` | Corner-resolved chi-plot: whether tail dependence sits in the lower or upper corner |
138
- | `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 |
139
140
  | `pairs` | Scatter-plot matrix with KDEs (or histograms) on the diagonal; `-g` colours groups, `--upper corr` puts r in the upper triangle |
140
141
  | `qq` | QQ plot of p-values: observed against expected -log10(p), confidence band, genomic inflation λ; `-g` one curve and λ per group |
141
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 |
143
+ | `phewas` | PheWAS plot: -log10(p) of each phenotype grouped by category (one colour each), ▲/▼ by the sign of `--betacol`, Bonferroni line, hits labelled |
142
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` |
143
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 |
144
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` and `box` `--hline`.
148
+
145
149
  ### Utilities
146
150
 
147
151
  | Command | Description |
@@ -446,6 +450,14 @@ dftk dataset penguins -o | dftk pivot -i species -g island -v body_mass_g -f cou
446
450
  | dftk heatmap -y species --annot --cmap Blues -f penguin_counts.png
447
451
  ```
448
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
+
449
461
  ### Manhattan plots
450
462
 
451
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:
@@ -488,6 +500,12 @@ dftk dataset gwas -o | dftk query -q "Chr == '6' and pos > 31.6e6 and pos < 33.6
488
500
  | dftk locus --ldcol r2 -f locus.png
489
501
  ```
490
502
 
503
+ `phewas` draws a phenome-wide scan: -log10(p) of each phenotype, the phenotypes grouped by category along the x axis in one colour per category (columns `category`, `phenotype` and `Pval` unless named with `-c`, `-l` and the p-value options of `manhattan`). With `--betacol beta` the points are triangles pointing up or down with the sign of the effect. The significance line is Bonferroni (0.05 / number of tests) unless `--sig` gives a p-value, and the phenotypes above it are labelled, at most `--label N` (default 10). One row per phenotype: pick one genotype or mask with `query` first.
504
+
505
+ ```bash
506
+ dftk dataset phewas -o | dftk query -q "genotype == 'het'" -o | dftk phewas --betacol beta -f phewas.png
507
+ ```
508
+
491
509
  `forest` draws one row per estimate: a point with its interval, labels down the left, top to bottom in file order (sort first to order them), and a reference line at 0. Give the interval as two columns (`--ci lo,hi`) or a standard error (`--se se`, ± 1.96 SE, `--level` to change). `--exp` turns log odds ratios (or any log-scale estimate) into ratios on a log axis with the reference at 1; `--text` writes `estimate [lo, hi]` to the right and `--textcol` adds columns such as the p-value or the number of carriers. `-g` puts several series on each row (het and hom carriers, two cohorts), `--section` groups rows under bold headers, `--weighted` sizes the markers by 1/SE². Coefficients from `fit`:
492
510
 
493
511
  `dataset phewas` is a simulated phenome-wide scan of loss-of-function carriers (heterozygous and homozygous rows per phenotype, log odds ratios, five real effects) to try it on:
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "dataframe-toolkit"
3
- version = "0.23.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.23.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 = [
@@ -62,12 +62,14 @@ COMMAND_GROUPS: list[tuple[str, list[tuple[str, str]]]] = [
62
62
  ("scat", "scat_cmd:ScatCommand"),
63
63
  ("line", "line_cmd:LineCommand"),
64
64
  ("hist", "hist_cmd:HistCommand"),
65
+ ("box", "box_cmd:BoxCommand"),
65
66
  ("chi", "chi_cmd:ChiCommand"),
66
67
  ("heatmap", "heatmap_cmd:HeatmapCommand"),
67
68
  ("pairs", "pairs_cmd:PairsCommand"),
68
69
  ("manhattan", "manhattan_cmd:ManhattanCommand"),
69
70
  ("qq", "qq_cmd:QqCommand"),
70
71
  ("locus", "locus_cmd:LocusCommand"),
72
+ ("phewas", "phewas_cmd:PhewasCommand"),
71
73
  ("forest", "forest_cmd:ForestCommand"),
72
74
  ],
73
75
  ),
@@ -0,0 +1,339 @@
1
+ """
2
+ dftk.commands.box_cmd — dftk box subcommand.
3
+
4
+ Box plot (or violin plot) of a value by category, with the individual
5
+ points jittered on top if wanted: e.g. protein level by loss-of-function
6
+ genotype (0/1/2), tips by day. Drawn with seaborn, which is imported
7
+ only when the command runs.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import logging
14
+
15
+ import pandas as pd
16
+
17
+ from dftk.commands.base import BaseCommand
18
+ from dftk.common.io import check_cols, io, option_columns
19
+ from dftk.common.plot import (
20
+ WONG_PALETTE,
21
+ add_figure_arguments,
22
+ add_refline_arguments,
23
+ apply_reflines,
24
+ apply_style,
25
+ make_figure,
26
+ save_or_show,
27
+ )
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ _BOX_COLOUR = WONG_PALETTE[1] # sky blue, without -g
32
+ _POINT_COLOUR = "0.15"
33
+
34
+ _EPILOG = """\
35
+ Input: one row per observation. -y is the value, -x the category (one
36
+ box each, in sorted order unless --order gives one; numbers such as a
37
+ genotype 0/1/2 are categories too). Without -x, a single box of all
38
+ rows. Rows without a value or category are left out.
39
+
40
+ The box spans the quartiles with a line at the median, and the whiskers
41
+ reach the furthest point within 1.5 times the box's height (Tukey);
42
+ points beyond them are drawn on their own, unless --points draws every
43
+ point anyway. --kind violin draws the distribution's density instead.
44
+
45
+ -g splits every box into one per group, side by side and in colour.
46
+
47
+ EXAMPLES
48
+ --------
49
+ Basic box plot of a value by category:
50
+
51
+ dftk box data.tsv -x genotype -y protein -f box.png
52
+
53
+ Tips by day, with every bill drawn on top, and how many there are:
54
+
55
+ dftk dataset tips -o | dftk box -x day -y tip --points --count \\
56
+ --order Thur Fri Sat Sun -f tips.png
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
+
63
+ Smokers and non-smokers side by side within each day:
64
+
65
+ dftk dataset tips -o | dftk box -x day -y tip -g smoker \\
66
+ --order Thur Fri Sat Sun -f tips_smoker.png
67
+
68
+ Violins of body mass by species, split by sex:
69
+
70
+ dftk dataset penguins -o | dftk box -x species -y body_mass_g -g sex \\
71
+ --kind violin -f penguins.png
72
+
73
+ A level by genotype (0, 1 or 2 copies of a loss-of-function allele), on
74
+ a log axis: a made-up level that halves with each copy (diamond prices
75
+ as the spread, genotypes drawn with randvar):
76
+
77
+ dftk dataset diamonds -o | dftk sample -n 2000 --randomseed 1 -o \\
78
+ | dftk randvar -d u --dist uniform --randomseed 2 -o \\
79
+ | dftk eval -f "dosage = (u > 0.6) * 1 + (u > 0.95) * 1" \\
80
+ -f "level = price / 2**dosage" -o \\
81
+ | dftk box -x dosage -y level --logy --points --count -f level.png
82
+ """
83
+
84
+
85
+ def _order(values: pd.Series, given: list[str] | None) -> list:
86
+ """Categories in sorted order (numbers numerically), or *given* first."""
87
+ found = list(pd.unique(values.dropna()))
88
+ try:
89
+ found = sorted(found)
90
+ except TypeError:
91
+ found = sorted(found, key=str)
92
+ if not given:
93
+ return found
94
+ by_text = {str(v): v for v in found}
95
+ missing = [g for g in given if g not in by_text]
96
+ if missing:
97
+ raise ValueError(
98
+ f"--order names values not in the data: {missing}; "
99
+ f"found {[str(v) for v in found]}."
100
+ )
101
+ listed = [by_text[g] for g in given]
102
+ return listed + [v for v in found if v not in listed]
103
+
104
+
105
+ class BoxCommand(BaseCommand):
106
+ name = "box"
107
+ help = "Box or violin plot of a value by category, points optional."
108
+
109
+ def add_arguments(self, parser: argparse.ArgumentParser) -> None:
110
+ parser.formatter_class = argparse.RawDescriptionHelpFormatter
111
+ parser.epilog = _EPILOG
112
+
113
+ self.add_read_arguments(parser)
114
+ c = parser.add_argument_group("columns")
115
+ c.add_argument(
116
+ "-y", "--ycol", required=True, metavar="COL", help="Value column."
117
+ )
118
+ c.add_argument(
119
+ "-x",
120
+ "--xcol",
121
+ metavar="COL",
122
+ help="Category column, one box each (default: one box of all rows).",
123
+ )
124
+ c.add_argument(
125
+ "-g",
126
+ "--groupcol",
127
+ metavar="COL",
128
+ help="Split each box into one per group, side by side, in colour.",
129
+ )
130
+ c.add_argument(
131
+ "--order",
132
+ nargs="+",
133
+ metavar="VAL",
134
+ help="Order of the -x categories (default: sorted); values not "
135
+ "listed follow.",
136
+ )
137
+ c.add_argument(
138
+ "--groupcolorder",
139
+ nargs="+",
140
+ metavar="VAL",
141
+ help="Order of the -g groups (default: sorted).",
142
+ )
143
+
144
+ b = parser.add_argument_group("box")
145
+ b.add_argument(
146
+ "--kind",
147
+ choices=["box", "violin"],
148
+ default="box",
149
+ help="box (quartiles and whiskers, the default) or violin (density).",
150
+ )
151
+ b.add_argument(
152
+ "--points",
153
+ action="store_true",
154
+ help="Draw every point on top, jittered sideways.",
155
+ )
156
+ b.add_argument(
157
+ "--count",
158
+ action="store_true",
159
+ help="Write the number of values under each category.",
160
+ )
161
+ b.add_argument(
162
+ "--markersize",
163
+ type=float,
164
+ default=3.0,
165
+ metavar="S",
166
+ help="Size of the --points (default: 3).",
167
+ )
168
+ b.add_argument(
169
+ "--alpha",
170
+ type=float,
171
+ default=0.5,
172
+ metavar="A",
173
+ help="Opacity of the --points, 0-1 (default: 0.5).",
174
+ )
175
+
176
+ a = parser.add_argument_group("axes")
177
+ a.add_argument("-xl", "--xlabel", metavar="TEXT", help="X-axis label.")
178
+ a.add_argument("-yl", "--ylabel", metavar="TEXT", help="Y-axis label.")
179
+ a.add_argument(
180
+ "-ym",
181
+ "--ylim",
182
+ nargs=2,
183
+ type=float,
184
+ metavar=("LO", "HI"),
185
+ help="Y-axis limits.",
186
+ )
187
+ a.add_argument("-ly", "--logy", action="store_true", help="Log y axis.")
188
+ a.add_argument(
189
+ "--legendloc",
190
+ nargs=2,
191
+ type=float,
192
+ metavar=("X", "Y"),
193
+ help="Position of the -g legend, in axes coordinates (default: best).",
194
+ )
195
+
196
+ add_figure_arguments(parser)
197
+ add_refline_arguments(parser, vertical=False)
198
+ parser.set_defaults(size="7x4.5")
199
+
200
+ def execute(self, args: argparse.Namespace) -> None:
201
+ df = io.read(args, columns=option_columns(args))
202
+ check_cols(df, [args.ycol], "-y/--ycol")
203
+ if args.xcol:
204
+ check_cols(df, [args.xcol], "-x/--xcol")
205
+ if args.groupcol:
206
+ check_cols(df, [args.groupcol], "-g/--groupcol")
207
+ if args.order and not args.xcol:
208
+ raise ValueError("--order orders the -x categories; give -x.")
209
+ if args.groupcolorder and not args.groupcol:
210
+ raise ValueError("--groupcolorder orders the -g groups; give -g.")
211
+
212
+ data = df.copy()
213
+ values = pd.to_numeric(data[args.ycol], errors="coerce")
214
+ bad = values.isna() & data[args.ycol].notna()
215
+ if bad.any():
216
+ raise ValueError(
217
+ f"-y column {args.ycol!r} isn't numeric "
218
+ f"(e.g. {data.loc[bad, args.ycol].iloc[0]!r})."
219
+ )
220
+ data[args.ycol] = values
221
+ needed = [c for c in (args.ycol, args.xcol, args.groupcol) if c]
222
+ keep = data[needed].notna().all(axis=1)
223
+ if not keep.all():
224
+ logger.info(
225
+ "Left out %d of %d rows without %s",
226
+ int((~keep).sum()),
227
+ len(data),
228
+ " / ".join(needed),
229
+ )
230
+ data = data[keep]
231
+ if data.empty:
232
+ raise ValueError("No rows with a value to plot.")
233
+ if args.logy and (data[args.ycol] <= 0).any():
234
+ raise ValueError(f"--logy needs -y values above 0 ({args.ycol!r}).")
235
+
236
+ order = _order(data[args.xcol], args.order) if args.xcol else None
237
+ hue_order = (
238
+ _order(data[args.groupcol], args.groupcolorder) if args.groupcol else None
239
+ )
240
+
241
+ if args.file:
242
+ import matplotlib
243
+
244
+ matplotlib.use("Agg")
245
+ import matplotlib.pyplot as plt
246
+
247
+ if args.usetex:
248
+ plt.rc("text", usetex=True)
249
+ apply_style(args)
250
+ fig, axes = make_figure(args)
251
+ ax = axes[0][0]
252
+ draw(ax, data, args, order, hue_order)
253
+ ax.set_title(args.title or "")
254
+ fig.tight_layout()
255
+ save_or_show(fig, args)
256
+
257
+
258
+ def draw(ax, data: pd.DataFrame, args, order, hue_order) -> None:
259
+ import seaborn as sns
260
+
261
+ # matplotlib logs "Using categorical units ..." for numeric categories
262
+ logging.getLogger("matplotlib.category").setLevel(logging.WARNING)
263
+
264
+ common = dict(data=data, x=args.xcol, y=args.ycol, order=order, ax=ax)
265
+ if args.groupcol:
266
+ common.update(
267
+ hue=args.groupcol,
268
+ hue_order=hue_order,
269
+ palette=WONG_PALETTE[: len(hue_order)],
270
+ )
271
+ else:
272
+ common["color"] = _BOX_COLOUR
273
+ if args.kind == "box":
274
+ sns.boxplot(
275
+ **common,
276
+ showfliers=not args.points,
277
+ width=0.6,
278
+ linewidth=1,
279
+ log_scale=args.logy or None,
280
+ )
281
+ else:
282
+ sns.violinplot(
283
+ **common,
284
+ inner="quart" if not args.points else None,
285
+ cut=0,
286
+ linewidth=1,
287
+ log_scale=args.logy or None,
288
+ )
289
+ if args.points:
290
+ strip = dict(common)
291
+ strip.pop("palette", None)
292
+ strip.pop("hue_order", None)
293
+ strip.pop("color", None)
294
+ if args.groupcol:
295
+ strip.update(
296
+ hue_order=hue_order,
297
+ dodge=True,
298
+ palette=[_POINT_COLOUR] * len(hue_order),
299
+ )
300
+ sns.stripplot(
301
+ **strip,
302
+ color=_POINT_COLOUR if not args.groupcol else None,
303
+ size=args.markersize,
304
+ alpha=args.alpha,
305
+ jitter=0.2,
306
+ legend=False,
307
+ zorder=3,
308
+ )
309
+
310
+ if args.count and args.xcol:
311
+ counts = data.groupby(args.xcol, sort=False).size()
312
+ ax.set_xticks(ax.get_xticks())
313
+ ax.set_xticklabels(
314
+ [
315
+ f"{t.get_text()}\n(n={counts.get(v, 0)})"
316
+ for t, v in zip(ax.get_xticklabels(), order, strict=True)
317
+ ]
318
+ )
319
+ elif args.count:
320
+ ax.set_xticks([0])
321
+ ax.set_xticklabels([f"n={len(data)}"])
322
+
323
+ if args.groupcol and ax.get_legend() is not None:
324
+ ax.legend(
325
+ title=args.groupcol,
326
+ fontsize="small",
327
+ title_fontsize="small",
328
+ loc=tuple(args.legendloc) if args.legendloc else "best",
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))
335
+ if args.ylim is not None:
336
+ ax.set_ylim(*args.ylim)
337
+ ax.spines[["top", "right"]].set_visible(False)
338
+ ax.set_xlabel(args.xlabel if args.xlabel is not None else (args.xcol or ""))
339
+ ax.set_ylabel(args.ylabel if args.ylabel is not None else args.ycol)
@@ -21,6 +21,8 @@ from dftk.common.io import check_cols, io, option_columns
21
21
  from dftk.common.plot import (
22
22
  WONG_PALETTE,
23
23
  add_figure_arguments,
24
+ add_refline_arguments,
25
+ apply_reflines,
24
26
  apply_style,
25
27
  make_figure,
26
28
  parse_figsize,
@@ -594,6 +596,7 @@ class ForestCommand(BaseCommand):
594
596
  )
595
597
 
596
598
  add_figure_arguments(parser)
599
+ add_refline_arguments(parser, horizontal=False)
597
600
  parser.set_defaults(size=None)
598
601
 
599
602
  def execute(self, args: argparse.Namespace) -> None:
@@ -652,6 +655,7 @@ class ForestCommand(BaseCommand):
652
655
  _draw(ax, df, est, ypos, args)
653
656
  if ref is not None:
654
657
  ax.axvline(ref, color=_REF_COLOUR, lw=0.8, ls="--", zorder=1)
658
+ apply_reflines(ax, args)
655
659
  if args.exp or args.logx:
656
660
  ax.set_xscale("log")
657
661
  _log_ticks(ax, est, xlim, ref)