dataframe-toolkit 0.23.0__tar.gz → 0.24.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.24.0}/PKG-INFO +12 -2
  2. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/README.md +11 -1
  3. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/pyproject.toml +1 -1
  4. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/pyproject.toml.orig +1 -1
  5. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/__init__.py +2 -0
  6. dataframe_toolkit-0.24.0/src/dftk/commands/box_cmd.py +326 -0
  7. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/forest_cmd.py +4 -0
  8. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/hist_cmd.py +8 -0
  9. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/line_cmd.py +13 -0
  10. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/manhattan_cmd.py +1 -0
  11. dataframe_toolkit-0.24.0/src/dftk/commands/phewas_cmd.py +421 -0
  12. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/scat_cmd.py +139 -15
  13. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/common/plot.py +76 -0
  14. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/skills/dftk/SKILL.md +9 -3
  15. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/__init__.py +0 -0
  16. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/cli.py +0 -0
  17. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/annotate_cmd.py +0 -0
  18. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/append_cmd.py +0 -0
  19. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/base.py +0 -0
  20. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/binx_cmd.py +0 -0
  21. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/chi_cmd.py +0 -0
  22. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/clean_cmd.py +0 -0
  23. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/cleannames_cmd.py +0 -0
  24. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/concat_cmd.py +0 -0
  25. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/corr_cmd.py +0 -0
  26. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/dataset_cmd.py +0 -0
  27. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/describe_cmd.py +0 -0
  28. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/eval_cmd.py +0 -0
  29. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/explode_cmd.py +0 -0
  30. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/fit_cmd.py +0 -0
  31. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/func_cmd.py +0 -0
  32. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/heatmap_cmd.py +0 -0
  33. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/help.py +0 -0
  34. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/implode_cmd.py +0 -0
  35. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/info_cmd.py +0 -0
  36. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/interp_cmd.py +0 -0
  37. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/locus_cmd.py +0 -0
  38. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/melt_cmd.py +0 -0
  39. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/merge_cmd.py +0 -0
  40. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/pairs_cmd.py +0 -0
  41. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/pivot_cmd.py +0 -0
  42. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/print_cmd.py +0 -0
  43. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/qq_cmd.py +0 -0
  44. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/query_cmd.py +0 -0
  45. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/randvar_cmd.py +0 -0
  46. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/sample_cmd.py +0 -0
  47. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/scale_cmd.py +0 -0
  48. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/segid_cmd.py +0 -0
  49. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/skill_cmd.py +0 -0
  50. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/split_cmd.py +0 -0
  51. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/stat_cmd.py +0 -0
  52. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/test_cmd.py +0 -0
  53. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/transpose_cmd.py +0 -0
  54. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/commands/wstat_cmd.py +0 -0
  55. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/common/__init__.py +0 -0
  56. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/common/copula.py +0 -0
  57. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/common/docformats.py +0 -0
  58. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/common/evalfuncs.py +0 -0
  59. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/common/gwas.py +0 -0
  60. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/common/io.py +0 -0
  61. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/common/seed.py +0 -0
  62. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/common/seq.py +0 -0
  63. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/common/stats.py +0 -0
  64. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.0}/src/dftk/io.py +0 -0
  65. {dataframe_toolkit-0.23.0 → dataframe_toolkit-0.24.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.24.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
169
  | `heatmap` | Coloured grid of values from a long (`-x -y -v`) or wide (`-y`) table; correlograms from `corr --all`, `--annot`, `--lower` |
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`.
178
+
175
179
  ### Utilities
176
180
 
177
181
  | Command | Description |
@@ -518,6 +522,12 @@ dftk dataset gwas -o | dftk query -q "Chr == '6' and pos > 31.6e6 and pos < 33.6
518
522
  | dftk locus --ldcol r2 -f locus.png
519
523
  ```
520
524
 
525
+ `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.
526
+
527
+ ```bash
528
+ dftk dataset phewas -o | dftk query -q "genotype == 'het'" -o | dftk phewas --betacol beta -f phewas.png
529
+ ```
530
+
521
531
  `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
532
 
523
533
  `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
139
  | `heatmap` | Coloured grid of values from a long (`-x -y -v`) or wide (`-y`) table; correlograms from `corr --all`, `--annot`, `--lower` |
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`.
148
+
145
149
  ### Utilities
146
150
 
147
151
  | Command | Description |
@@ -488,6 +492,12 @@ dftk dataset gwas -o | dftk query -q "Chr == '6' and pos > 31.6e6 and pos < 33.6
488
492
  | dftk locus --ldcol r2 -f locus.png
489
493
  ```
490
494
 
495
+ `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.
496
+
497
+ ```bash
498
+ dftk dataset phewas -o | dftk query -q "genotype == 'het'" -o | dftk phewas --betacol beta -f phewas.png
499
+ ```
500
+
491
501
  `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
502
 
493
503
  `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.24.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.24.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,326 @@
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
+ apply_style,
23
+ make_figure,
24
+ save_or_show,
25
+ )
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ _BOX_COLOUR = WONG_PALETTE[1] # sky blue, without -g
30
+ _POINT_COLOUR = "0.15"
31
+
32
+ _EPILOG = """\
33
+ Input: one row per observation. -y is the value, -x the category (one
34
+ box each, in sorted order unless --order gives one; numbers such as a
35
+ genotype 0/1/2 are categories too). Without -x, a single box of all
36
+ rows. Rows without a value or category are left out.
37
+
38
+ The box spans the quartiles with a line at the median, and the whiskers
39
+ reach the furthest point within 1.5 times the box's height (Tukey);
40
+ points beyond them are drawn on their own, unless --points draws every
41
+ point anyway. --kind violin draws the distribution's density instead.
42
+
43
+ -g splits every box into one per group, side by side and in colour.
44
+
45
+ EXAMPLES
46
+ --------
47
+ Basic box plot of a value by category:
48
+
49
+ dftk box data.tsv -x genotype -y protein -f box.png
50
+
51
+ Tips by day, with every bill drawn on top, and how many there are:
52
+
53
+ dftk dataset tips -o | dftk box -x day -y tip --points --count \\
54
+ --order Thur Fri Sat Sun -f tips.png
55
+
56
+ Smokers and non-smokers side by side within each day:
57
+
58
+ dftk dataset tips -o | dftk box -x day -y tip -g smoker \\
59
+ --order Thur Fri Sat Sun -f tips_smoker.png
60
+
61
+ Violins of body mass by species, split by sex:
62
+
63
+ dftk dataset penguins -o | dftk box -x species -y body_mass_g -g sex \\
64
+ --kind violin -f penguins.png
65
+
66
+ A level by genotype (0, 1 or 2 copies of a loss-of-function allele), on
67
+ a log axis: a made-up level that halves with each copy (diamond prices
68
+ as the spread, genotypes drawn with randvar):
69
+
70
+ dftk dataset diamonds -o | dftk sample -n 2000 --randomseed 1 -o \\
71
+ | dftk randvar -d u --dist uniform --randomseed 2 -o \\
72
+ | dftk eval -f "dosage = (u > 0.6) * 1 + (u > 0.95) * 1" \\
73
+ -f "level = price / 2**dosage" -o \\
74
+ | dftk box -x dosage -y level --logy --points --count -f level.png
75
+ """
76
+
77
+
78
+ def _order(values: pd.Series, given: list[str] | None) -> list:
79
+ """Categories in sorted order (numbers numerically), or *given* first."""
80
+ found = list(pd.unique(values.dropna()))
81
+ try:
82
+ found = sorted(found)
83
+ except TypeError:
84
+ found = sorted(found, key=str)
85
+ if not given:
86
+ return found
87
+ by_text = {str(v): v for v in found}
88
+ missing = [g for g in given if g not in by_text]
89
+ if missing:
90
+ raise ValueError(
91
+ f"--order names values not in the data: {missing}; "
92
+ f"found {[str(v) for v in found]}."
93
+ )
94
+ listed = [by_text[g] for g in given]
95
+ return listed + [v for v in found if v not in listed]
96
+
97
+
98
+ class BoxCommand(BaseCommand):
99
+ name = "box"
100
+ help = "Box or violin plot of a value by category, points optional."
101
+
102
+ def add_arguments(self, parser: argparse.ArgumentParser) -> None:
103
+ parser.formatter_class = argparse.RawDescriptionHelpFormatter
104
+ parser.epilog = _EPILOG
105
+
106
+ self.add_read_arguments(parser)
107
+ c = parser.add_argument_group("columns")
108
+ c.add_argument(
109
+ "-y", "--ycol", required=True, metavar="COL", help="Value column."
110
+ )
111
+ c.add_argument(
112
+ "-x",
113
+ "--xcol",
114
+ metavar="COL",
115
+ help="Category column, one box each (default: one box of all rows).",
116
+ )
117
+ c.add_argument(
118
+ "-g",
119
+ "--groupcol",
120
+ metavar="COL",
121
+ help="Split each box into one per group, side by side, in colour.",
122
+ )
123
+ c.add_argument(
124
+ "--order",
125
+ nargs="+",
126
+ metavar="VAL",
127
+ help="Order of the -x categories (default: sorted); values not "
128
+ "listed follow.",
129
+ )
130
+ c.add_argument(
131
+ "--groupcolorder",
132
+ nargs="+",
133
+ metavar="VAL",
134
+ help="Order of the -g groups (default: sorted).",
135
+ )
136
+
137
+ b = parser.add_argument_group("box")
138
+ b.add_argument(
139
+ "--kind",
140
+ choices=["box", "violin"],
141
+ default="box",
142
+ help="box (quartiles and whiskers, the default) or violin (density).",
143
+ )
144
+ b.add_argument(
145
+ "--points",
146
+ action="store_true",
147
+ help="Draw every point on top, jittered sideways.",
148
+ )
149
+ b.add_argument(
150
+ "--count",
151
+ action="store_true",
152
+ help="Write the number of values under each category.",
153
+ )
154
+ b.add_argument(
155
+ "--markersize",
156
+ type=float,
157
+ default=3.0,
158
+ metavar="S",
159
+ help="Size of the --points (default: 3).",
160
+ )
161
+ b.add_argument(
162
+ "--alpha",
163
+ type=float,
164
+ default=0.5,
165
+ metavar="A",
166
+ help="Opacity of the --points, 0-1 (default: 0.5).",
167
+ )
168
+
169
+ a = parser.add_argument_group("axes")
170
+ a.add_argument("-xl", "--xlabel", metavar="TEXT", help="X-axis label.")
171
+ a.add_argument("-yl", "--ylabel", metavar="TEXT", help="Y-axis label.")
172
+ a.add_argument(
173
+ "-ym",
174
+ "--ylim",
175
+ nargs=2,
176
+ type=float,
177
+ metavar=("LO", "HI"),
178
+ help="Y-axis limits.",
179
+ )
180
+ a.add_argument("-ly", "--logy", action="store_true", help="Log y axis.")
181
+ a.add_argument(
182
+ "--legendloc",
183
+ nargs=2,
184
+ type=float,
185
+ metavar=("X", "Y"),
186
+ help="Position of the -g legend, in axes coordinates (default: best).",
187
+ )
188
+
189
+ add_figure_arguments(parser)
190
+ parser.set_defaults(size="7x4.5")
191
+
192
+ def execute(self, args: argparse.Namespace) -> None:
193
+ df = io.read(args, columns=option_columns(args))
194
+ check_cols(df, [args.ycol], "-y/--ycol")
195
+ if args.xcol:
196
+ check_cols(df, [args.xcol], "-x/--xcol")
197
+ if args.groupcol:
198
+ check_cols(df, [args.groupcol], "-g/--groupcol")
199
+ if args.order and not args.xcol:
200
+ raise ValueError("--order orders the -x categories; give -x.")
201
+ if args.groupcolorder and not args.groupcol:
202
+ raise ValueError("--groupcolorder orders the -g groups; give -g.")
203
+
204
+ data = df.copy()
205
+ values = pd.to_numeric(data[args.ycol], errors="coerce")
206
+ bad = values.isna() & data[args.ycol].notna()
207
+ if bad.any():
208
+ raise ValueError(
209
+ f"-y column {args.ycol!r} isn't numeric "
210
+ f"(e.g. {data.loc[bad, args.ycol].iloc[0]!r})."
211
+ )
212
+ data[args.ycol] = values
213
+ needed = [c for c in (args.ycol, args.xcol, args.groupcol) if c]
214
+ keep = data[needed].notna().all(axis=1)
215
+ if not keep.all():
216
+ logger.info(
217
+ "Left out %d of %d rows without %s",
218
+ int((~keep).sum()),
219
+ len(data),
220
+ " / ".join(needed),
221
+ )
222
+ data = data[keep]
223
+ if data.empty:
224
+ raise ValueError("No rows with a value to plot.")
225
+ if args.logy and (data[args.ycol] <= 0).any():
226
+ raise ValueError(f"--logy needs -y values above 0 ({args.ycol!r}).")
227
+
228
+ order = _order(data[args.xcol], args.order) if args.xcol else None
229
+ hue_order = (
230
+ _order(data[args.groupcol], args.groupcolorder) if args.groupcol else None
231
+ )
232
+
233
+ if args.file:
234
+ import matplotlib
235
+
236
+ matplotlib.use("Agg")
237
+ import matplotlib.pyplot as plt
238
+
239
+ if args.usetex:
240
+ plt.rc("text", usetex=True)
241
+ apply_style(args)
242
+ fig, axes = make_figure(args)
243
+ ax = axes[0][0]
244
+ draw(ax, data, args, order, hue_order)
245
+ ax.set_title(args.title or "")
246
+ fig.tight_layout()
247
+ save_or_show(fig, args)
248
+
249
+
250
+ def draw(ax, data: pd.DataFrame, args, order, hue_order) -> None:
251
+ import seaborn as sns
252
+
253
+ # matplotlib logs "Using categorical units ..." for numeric categories
254
+ logging.getLogger("matplotlib.category").setLevel(logging.WARNING)
255
+
256
+ common = dict(data=data, x=args.xcol, y=args.ycol, order=order, ax=ax)
257
+ if args.groupcol:
258
+ common.update(
259
+ hue=args.groupcol,
260
+ hue_order=hue_order,
261
+ palette=WONG_PALETTE[: len(hue_order)],
262
+ )
263
+ else:
264
+ common["color"] = _BOX_COLOUR
265
+ if args.kind == "box":
266
+ sns.boxplot(
267
+ **common,
268
+ showfliers=not args.points,
269
+ width=0.6,
270
+ linewidth=1,
271
+ log_scale=args.logy or None,
272
+ )
273
+ else:
274
+ sns.violinplot(
275
+ **common,
276
+ inner="quart" if not args.points else None,
277
+ cut=0,
278
+ linewidth=1,
279
+ log_scale=args.logy or None,
280
+ )
281
+ if args.points:
282
+ strip = dict(common)
283
+ strip.pop("palette", None)
284
+ strip.pop("hue_order", None)
285
+ strip.pop("color", None)
286
+ if args.groupcol:
287
+ strip.update(
288
+ hue_order=hue_order,
289
+ dodge=True,
290
+ palette=[_POINT_COLOUR] * len(hue_order),
291
+ )
292
+ sns.stripplot(
293
+ **strip,
294
+ color=_POINT_COLOUR if not args.groupcol else None,
295
+ size=args.markersize,
296
+ alpha=args.alpha,
297
+ jitter=0.2,
298
+ legend=False,
299
+ zorder=3,
300
+ )
301
+
302
+ if args.count and args.xcol:
303
+ counts = data.groupby(args.xcol, sort=False).size()
304
+ ax.set_xticks(ax.get_xticks())
305
+ ax.set_xticklabels(
306
+ [
307
+ f"{t.get_text()}\n(n={counts.get(v, 0)})"
308
+ for t, v in zip(ax.get_xticklabels(), order, strict=True)
309
+ ]
310
+ )
311
+ elif args.count:
312
+ ax.set_xticks([0])
313
+ ax.set_xticklabels([f"n={len(data)}"])
314
+
315
+ if args.groupcol and ax.get_legend() is not None:
316
+ ax.legend(
317
+ title=args.groupcol,
318
+ fontsize="small",
319
+ title_fontsize="small",
320
+ loc=tuple(args.legendloc) if args.legendloc else "best",
321
+ )
322
+ if args.ylim is not None:
323
+ ax.set_ylim(*args.ylim)
324
+ ax.spines[["top", "right"]].set_visible(False)
325
+ ax.set_xlabel(args.xlabel if args.xlabel is not None else (args.xcol or ""))
326
+ 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)
@@ -23,8 +23,10 @@ from dftk.common.plot import (
23
23
  add_figure_arguments,
24
24
  add_group_arguments,
25
25
  add_legend_arguments,
26
+ add_refline_arguments,
26
27
  apply_labels,
27
28
  apply_limits,
29
+ apply_reflines,
28
30
  apply_style,
29
31
  make_figure,
30
32
  make_grouplabel,
@@ -111,6 +113,7 @@ def _hist_ax(ax, df, args, title_suffix: str = ""):
111
113
  if label:
112
114
  ax.legend(loc=legendloc, title=args.legendtitle)
113
115
 
116
+ apply_reflines(ax, args)
114
117
  apply_limits(ax, args)
115
118
  apply_labels(
116
119
  ax,
@@ -171,6 +174,10 @@ Weighted histogram (weight by party size):
171
174
 
172
175
  dftk dataset tips -o | dftk hist -x total_bill -y size
173
176
 
177
+ Reference lines, labelled (NUMBER:LABEL, or just NUMBER):
178
+
179
+ dftk dataset tips -o | dftk hist -x total_bill --vline 20:typical 40:large
180
+
174
181
  Publication figure (Nature single column, PDF):
175
182
 
176
183
  dftk dataset tips -o | dftk hist -x total_bill \\
@@ -188,6 +195,7 @@ class HistCommand(BaseCommand):
188
195
 
189
196
  self.add_read_arguments(parser)
190
197
  add_figure_arguments(parser)
198
+ add_refline_arguments(parser)
191
199
  add_group_arguments(parser)
192
200
  add_legend_arguments(parser)
193
201
 
@@ -25,9 +25,11 @@ from dftk.common.plot import (
25
25
  add_figure_arguments,
26
26
  add_group_arguments,
27
27
  add_legend_arguments,
28
+ add_refline_arguments,
28
29
  add_xy_arguments,
29
30
  apply_labels,
30
31
  apply_limits,
32
+ apply_reflines,
31
33
  apply_style,
32
34
  apply_ticks,
33
35
  make_figure,
@@ -162,6 +164,7 @@ def _line_ax(ax, df, args, title_suffix: str = ""):
162
164
  if getattr(args, "fit", False) and args.groupcol is None:
163
165
  _fit_overlay(ax, df[xcol], df[ycol], args)
164
166
 
167
+ apply_reflines(ax, args)
165
168
  apply_limits(ax, args)
166
169
  apply_ticks(ax, args)
167
170
  apply_labels(ax, args, default_xlabel=xcol or "", default_ylabel=ycol or "")
@@ -223,6 +226,15 @@ Fit and overlay regression line:
223
226
  --sql "SELECT * FROM data WHERE month = 'Jan'" -o \\
224
227
  | dftk line -x year -y passengers --fit
225
228
 
229
+ Smallest odds ratio detectable with 80 % power against the number of
230
+ carriers (disease prevalence 5 %, p < 5e-4), with the cohort's carrier
231
+ count marked by a labelled vertical line:
232
+
233
+ dftk query --sql "SELECT n::DOUBLE AS carriers,
234
+ exp((3.48 + 0.84) / sqrt(n * 0.05 * 0.95)) AS or_min
235
+ FROM range(10, 5001, 10) t(n)" -o \\
236
+ | dftk line -x carriers -y or_min --logy --vline 412:cohort --hline 2
237
+
226
238
  Publication figure (Nature double column, PDF):
227
239
 
228
240
  dftk dataset flights -o | dftk query \\
@@ -243,6 +255,7 @@ class LineCommand(BaseCommand):
243
255
  self.add_read_arguments(parser)
244
256
  add_xy_arguments(parser)
245
257
  add_figure_arguments(parser)
258
+ add_refline_arguments(parser)
246
259
  add_group_arguments(parser)
247
260
  add_legend_arguments(parser)
248
261
 
@@ -245,6 +245,7 @@ def scatter_capped(ax, x, y, hi, args, colours=None, capmarker="^", **kw):
245
245
  ) # fmt: skip
246
246
  if over.any():
247
247
  common.pop("label", None)
248
+ common.pop("marker", None) # the cap has its own: capmarker
248
249
  ax.scatter(
249
250
  x[over], np.full(over.sum(), hi), s=size * 4, marker=capmarker,
250
251
  clip_on=False, c=None if colours is None else colours[over], **common,