kx-plot 0.5.0__tar.gz → 0.7.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.
- {kx_plot-0.5.0 → kx_plot-0.7.0}/CHANGELOG.md +71 -1
- {kx_plot-0.5.0 → kx_plot-0.7.0}/PKG-INFO +78 -9
- {kx_plot-0.5.0 → kx_plot-0.7.0}/README.md +74 -8
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/__init__.py +46 -14
- kx_plot-0.7.0/kx/_cramers.py +47 -0
- kx_plot-0.7.0/kx/_data.py +21 -0
- kx_plot-0.7.0/kx/_embed.py +88 -0
- kx_plot-0.7.0/kx/_image.py +244 -0
- kx_plot-0.7.0/kx/_plot.py +354 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/_spec.py +11 -5
- kx_plot-0.7.0/kx/_stats.py +207 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/_theme.py +60 -6
- kx_plot-0.7.0/kx/_util.py +140 -0
- kx_plot-0.7.0/kx/data/embedding.csv +601 -0
- kx_plot-0.7.0/kx/data/regression.csv +501 -0
- kx_plot-0.7.0/kx/data/shapes.npz +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/kinds/__init__.py +1 -1
- kx_plot-0.7.0/kx/kinds/basic.py +517 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/kinds/dist.py +87 -3
- kx_plot-0.7.0/kx/kinds/image.py +387 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/kinds/ml.py +56 -2
- kx_plot-0.7.0/kx/kinds/table.py +518 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/cmaps/LICENCES.md +18 -8
- kx_plot-0.7.0/kx/styles/colorblind.mplstyle +20 -0
- kx_plot-0.7.0/kx/styles/minimal.mplstyle +26 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/palettes/LICENCES.md +90 -12
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/palettes/dark2.txt +1 -1
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/palettes/ibm.txt +1 -1
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/palettes/okabe.txt +1 -1
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/palettes/paired.txt +1 -1
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/palettes/petroff10.txt +1 -1
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/palettes/petroff6.txt +1 -1
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/palettes/petroff8.txt +1 -1
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/palettes/set1.txt +1 -1
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/palettes/set2.txt +1 -1
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/palettes/tab10.txt +1 -1
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/palettes/tab20.txt +1 -1
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/palettes/tableaucb.txt +1 -1
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/palettes/tolbright.txt +1 -1
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/palettes/tolhc.txt +1 -1
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/palettes/tollight.txt +1 -1
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/palettes/tolmc.txt +1 -1
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/palettes/tolvibrant.txt +1 -1
- {kx_plot-0.5.0 → kx_plot-0.7.0}/pyproject.toml +7 -1
- kx_plot-0.7.0/tests/helpers.py +16 -0
- kx_plot-0.7.0/tests/test_api.py +213 -0
- kx_plot-0.7.0/tests/test_basic.py +413 -0
- kx_plot-0.7.0/tests/test_data.py +133 -0
- kx_plot-0.7.0/tests/test_dist.py +248 -0
- kx_plot-0.7.0/tests/test_flags.py +567 -0
- kx_plot-0.7.0/tests/test_image.py +499 -0
- kx_plot-0.7.0/tests/test_ml.py +699 -0
- kx_plot-0.7.0/tests/test_plot.py +320 -0
- kx_plot-0.7.0/tests/test_stats.py +143 -0
- kx_plot-0.7.0/tests/test_table.py +567 -0
- kx_plot-0.7.0/tests/test_theme.py +317 -0
- kx_plot-0.5.0/kx/_data.py +0 -16
- kx_plot-0.5.0/kx/_plot.py +0 -170
- kx_plot-0.5.0/kx/_util.py +0 -57
- kx_plot-0.5.0/kx/data/regression.csv +0 -501
- kx_plot-0.5.0/kx/kinds/basic.py +0 -213
- kx_plot-0.5.0/kx/kinds/table.py +0 -132
- kx_plot-0.5.0/tests/test_kx.py +0 -2029
- {kx_plot-0.5.0 → kx_plot-0.7.0}/.gitignore +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/LICENSE +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/_evaluate.py +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/_files.py +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/_grid.py +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/_metrics.py +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/_save.py +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/data/binary.csv +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/data/cloud.csv +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/data/curves.csv +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/data/daily.csv +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/data/dists.csv +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/data/history.csv +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/data/importance.csv +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/data/monthly.csv +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/data/multiclass.csv +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/data/passengers.csv +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/data/waves.csv +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/cmaps/balance.txt +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/cmaps/bam.txt +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/cmaps/batlow.txt +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/cmaps/cork.txt +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/cmaps/davos.txt +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/cmaps/deep.txt +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/cmaps/haline.txt +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/cmaps/hawaii.txt +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/cmaps/lipari.txt +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/cmaps/oslo.txt +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/cmaps/roma.txt +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/cmaps/romaO.txt +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/cmaps/thermal.txt +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/cmaps/vik.txt +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/dark.mplstyle +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/light.mplstyle +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/paper.mplstyle +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/poster.mplstyle +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/science.mplstyle +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/talk.mplstyle +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/kx/styles/thesis.mplstyle +0 -0
- {kx_plot-0.5.0 → kx_plot-0.7.0}/tests/conftest.py +0 -0
|
@@ -6,6 +6,74 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [0.7.0] - 2026-11-24
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- **Flag** `ci` (`line`, `step`): the mean at each x with a bootstrap 95% band; `n_boot=`, `seed=`.
|
|
14
|
+
- `ci` on `bar` and `barh`: the mean per category with bootstrap 95% error bars.
|
|
15
|
+
- **Plot kind** `errbar`: the mean per series or `by=` group with a bootstrap 95% interval; `sd`, `ann`, `sig`.
|
|
16
|
+
- **Flag** `endlab` (`line`, `step`, `band`, `area`): each line's name at its right end instead of a legend.
|
|
17
|
+
- **Plot kind** `lollipop`: a dot per category on a stem from 0, or a dumbbell from `y` to `z`; `sort`, `ann`.
|
|
18
|
+
- `kx.register(name, colors, cmap=False)`: a palette or colormap of your own for the session.
|
|
19
|
+
- **Theme** `minimal`: no box or tick marks, a light grid along the values only.
|
|
20
|
+
- **Theme** `colorblind`: Okabe-Ito without yellow, each colour with its own linestyle; `cividis` colormap.
|
|
21
|
+
|
|
22
|
+
## [0.6.0] - 2026-11-04
|
|
23
|
+
|
|
24
|
+
### Added
|
|
25
|
+
|
|
26
|
+
- `kx.plot` can draw a plot made of several panels (such as `pair`), returned as a flat array of axes in the place
|
|
27
|
+
of `ax=`, or a polar plot (such as `radar`), swapping a given `ax` for polar axes in the same cell.
|
|
28
|
+
- Statistics for the significance, association and clustering plots, in numpy without scipy and checked against
|
|
29
|
+
it: Kruskal-Wallis and pairwise Mann-Whitney tests, Holm-adjusted p-values, Cramér's V and hierarchical linkage.
|
|
30
|
+
- **Datasets** `embedding` (a 2-D embedding in 5 clusters, with the 10 features behind it) and `shapes` (210 small
|
|
31
|
+
images in 7 classes, some with artifacts, with masks, a model's predictions and saliency maps).
|
|
32
|
+
- `kx.load` reads a `.npz` dataset as a dict of arrays: `kx.load('shapes')['images']`.
|
|
33
|
+
- Image input for the image plots: an array of images (channels last or first), or a list of arrays, PIL images
|
|
34
|
+
or file paths, scaled to 0..1 whatever the dtype.
|
|
35
|
+
- **Plot kinds** `pie` and `donut`: shares of a whole, counting the categories of x or summing y per category.
|
|
36
|
+
`ann` writes the percent in each slice, `sort` puts the largest first, and past `top=` (7) slices the rest fold
|
|
37
|
+
into `other`. `donut` shows the total in its hole.
|
|
38
|
+
- **Plot kind** `radar`: one polygon per row of a table, or per group mean with `by=`, each column scaled to 0..1
|
|
39
|
+
with its range under its name; `raw` keeps the values.
|
|
40
|
+
- **Plot kind** `parallel`: parallel coordinates, one line per row, each axis scaled with its real min and max at
|
|
41
|
+
the ends. `by=` colours the lines by group and `mean` adds each group's mean.
|
|
42
|
+
- **Plot kind** `pair`: a scatter matrix of the numeric columns, coloured by `by=`, with a KDE per group on the
|
|
43
|
+
diagonal and shared axes. `cols=` picks the columns (at most 8).
|
|
44
|
+
- **Plot kind** `cluster`: `heat` with similar rows and columns side by side and dendrograms showing how they
|
|
45
|
+
group; `cluster-corr` groups correlated features. `method=` picks the linkage.
|
|
46
|
+
- **Plot kind** `mosaic`: two or three categoricals as tiles sized by their counts, `kx.plot(df, 'port', 'sex',
|
|
47
|
+
'survived', spec='mosaic')`. `ann` writes the counts.
|
|
48
|
+
- **Plot kinds** `treemap` and `sunburst`: a hierarchy of up to three categoricals sized by count, as nested
|
|
49
|
+
rectangles or as rings, `kx.plot(df, 'pclass', 'sex', spec='treemap')`. `ann` labels the tiles with room.
|
|
50
|
+
- **Flag** `facet`: the plot once per value of `facet=`, `kx.plot(df, 'pclass', 'port', 'crosstab-facet',
|
|
51
|
+
facet='sex')`, with every category in each panel, shared axes and one colour scale.
|
|
52
|
+
- **Flag** `sig` (`box`, `violin`): the Kruskal-Wallis p over the groups and, up to 6 groups, stars over each pair
|
|
53
|
+
that differs (Mann-Whitney, Holm-corrected); with `ann` the p-values instead.
|
|
54
|
+
- **Plot kind** `imgrid`: sample images, `kx.plot(images, labels, 'imgrid')`, one row of `n=` random images per
|
|
55
|
+
class (`seed=` repeats them), or the images at `idx=`. Only the images shown are read.
|
|
56
|
+
- **Plot kind** `meanimg`: the mean image of each class, `kx.plot(images, labels, 'meanimg')`, sizes matched to
|
|
57
|
+
the most common one; `std` shows how much each pixel varies instead, on one colour scale.
|
|
58
|
+
- **Plot kind** `colorhist`: each class's average histogram per colour channel, one line per class
|
|
59
|
+
(`kx.plot(images, labels, 'colorhist')`); `hsv` for hue, saturation and value, `map` for heat maps.
|
|
60
|
+
- **Plot kind** `imhist`: images beside their channel histograms, one row each, `kx.plot(images, 'imhist',
|
|
61
|
+
idx=[0, 1])` or `n=` random ones; `hsv` for hue, saturation and value.
|
|
62
|
+
- **Plot kind** `segmask`: images with their segmentation masks, `kx.plot(images, masks, 'segmask')`: the image,
|
|
63
|
+
the mask and an outline over the image; predicted masks as z add a second outline and the IoU.
|
|
64
|
+
- **Plot kind** `saliency`: saliency maps (Grad-CAM or any, computed elsewhere) over their images,
|
|
65
|
+
`kx.plot(images, maps, 'saliency')`, each scaled to 0..1 and smoothed up to its image; z adds a caption.
|
|
66
|
+
- **Plot kind** `miscls`: the images a model got wrong, `kx.plot(images, y_true, y_pred, 'miscls')`, captioned
|
|
67
|
+
'true -> predicted'; with a 2-D score as z, the most confident mistakes first.
|
|
68
|
+
- **Plot kind** `embed`: a 2-D embedding coloured by label, `kx.plot(xy, labels, 'embed')`, with no ticks and
|
|
69
|
+
equal aspect; `ann` names each group where it sits.
|
|
70
|
+
- `kx.embed(df, by='label')`: PCA (or `method='tsne'`, `'umap'` with the new `embed` extra) of a table or images,
|
|
71
|
+
then the `embed` plot; the coordinates are `ax.embedding`.
|
|
72
|
+
- `kx.cramers(df)`: Cramér's V between every pair of categorical columns as a heat map, `cluster=True` to group
|
|
73
|
+
them, `plot=False` for the matrix.
|
|
74
|
+
- `heat` takes `fmt=` for its `ann` numbers.
|
|
75
|
+
- Table kinds that group (`radar`, `parallel`, `pair`) take `by=` as a column name, left out of the columns drawn.
|
|
76
|
+
|
|
9
77
|
## [0.5.0] - 2026-10-24
|
|
10
78
|
|
|
11
79
|
### Added
|
|
@@ -270,7 +338,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
|
270
338
|
- `kx.use`, `kx.show`, `kx.source`, `kx.grammar`, `kx.load` and the demo CSVs
|
|
271
339
|
- a workflow that publishes the dataset to Kaggle
|
|
272
340
|
|
|
273
|
-
[Unreleased]: https://github.com/vhrabar/kx-plot/compare/v0.
|
|
341
|
+
[Unreleased]: https://github.com/vhrabar/kx-plot/compare/v0.7.0...HEAD
|
|
342
|
+
[0.7.0]: https://github.com/vhrabar/kx-plot/compare/v0.6.0...v0.7.0
|
|
343
|
+
[0.6.0]: https://github.com/vhrabar/kx-plot/compare/v0.5.0...v0.6.0
|
|
274
344
|
[0.5.0]: https://github.com/vhrabar/kx-plot/compare/v0.4.0...v0.5.0
|
|
275
345
|
[0.4.0]: https://github.com/vhrabar/kx-plot/compare/v0.3.0...v0.4.0
|
|
276
346
|
[0.3.0]: https://github.com/vhrabar/kx-plot/compare/v0.2.0...v0.3.0
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: kx-plot
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.7.0
|
|
4
4
|
Summary: One-line matplotlib plots, themes and model-evaluation charts for notebooks and scripts, Kaggle-friendly
|
|
5
5
|
Project-URL: Homepage, https://github.com/vhrabar/kx-plot
|
|
6
6
|
Project-URL: Issues, https://github.com/vhrabar/kx-plot/issues
|
|
@@ -34,6 +34,9 @@ Requires-Python: >=3.10
|
|
|
34
34
|
Requires-Dist: matplotlib>=3.7
|
|
35
35
|
Requires-Dist: numpy>=1.23
|
|
36
36
|
Requires-Dist: pandas>=1.5
|
|
37
|
+
Provides-Extra: embed
|
|
38
|
+
Requires-Dist: scikit-learn>=1.2; extra == 'embed'
|
|
39
|
+
Requires-Dist: umap-learn>=0.5; extra == 'embed'
|
|
37
40
|
Description-Content-Type: text/markdown
|
|
38
41
|
|
|
39
42
|
# kx-plot
|
|
@@ -49,6 +52,9 @@ matplotlib, numpy and pandas and works offline, so it also runs in Kaggle compet
|
|
|
49
52
|
|
|
50
53
|
```bash
|
|
51
54
|
pip install kx-plot
|
|
55
|
+
|
|
56
|
+
# adds t-SNE and UMAP to kx.embed (PCA needs neither)
|
|
57
|
+
pip install 'kx-plot[embed]'
|
|
52
58
|
```
|
|
53
59
|
|
|
54
60
|
```python
|
|
@@ -82,14 +88,16 @@ kx.plot(df.value, spec='box', by=df.group) # one box per group (also rid
|
|
|
82
88
|
|
|
83
89
|
| Token | Values |
|
|
84
90
|
|-------|-----------------------------------------------------------------------------------------------|
|
|
85
|
-
| kind | `line` `step` `area` `band` `scatter` `bar` `barh` `hist` `kde` `ridge` `ecdf`
|
|
86
|
-
| | `strip` `qq` `count` `crosstab` `hexbin` `heat` `missing` `nullmap`
|
|
91
|
+
| kind | `line` `step` `area` `band` `scatter` `bar` `barh` `lollipop` `hist` `kde` `ridge` `ecdf` |
|
|
92
|
+
| | `box` `violin` `strip` `errbar` `qq` `count` `crosstab` `hexbin` `heat` `missing` `nullmap` |
|
|
93
|
+
| | `pie` `donut` `radar` `parallel` `pair` `cluster` `mosaic` `treemap` `sunburst` |
|
|
87
94
|
| | ML: `cm` `roc` `pr` `calib` `proba` `thresh` `gain` `lift` `pva` `resid` `imp` `loss` |
|
|
88
|
-
| | `lcurve` `vcurve` `elbow`
|
|
89
|
-
|
|
|
95
|
+
| | `lcurve` `vcurve` `elbow` `embed` |
|
|
96
|
+
| | Images: `imgrid` `meanimg` `colorhist` `imhist` `segmask` `saliency` `miscls` |
|
|
97
|
+
| theme | `dark` `light` `minimal` `colorblind` `paper` `science` `talk` `poster` `thesis` |
|
|
90
98
|
| flags | `grid` `leg` `legout` `tight` `rot` `wrap` `logx` `logy` `logxy` `symlogy` `zero` `eq` `pct` |
|
|
91
|
-
| | `si`; per kind: `stack` `norm` `cum` `date` `mk` `
|
|
92
|
-
| | `logc` `corr` `all` `diag` `fit` `best`
|
|
99
|
+
| | `si` `facet`; per kind: `stack` `norm` `cum` `date` `mk` `endlab` `ci` `sort` `ann` `mean` |
|
|
100
|
+
| | `median` `sd` `nocb` `sym` `logc` `corr` `all` `diag` `fit` `best` `raw` `sig` |
|
|
93
101
|
|
|
94
102
|
`stack` works with `area`, `bar`, `barh` and `hist`. `norm` is a 100% stack for `area` and a
|
|
95
103
|
density (area 1) for `hist`. `cum` makes `hist` cumulative; `hist-norm-cum` is the CDF.
|
|
@@ -97,6 +105,26 @@ density (area 1) for `hist`. `cum` makes `hist` cumulative; `hist-norm-cum` is t
|
|
|
97
105
|
`diag` adds a dashed `y = x` line to `scatter` and `hexbin`; `fit` adds a least-squares line to `scatter`, with
|
|
98
106
|
its slope and R² in the legend (one line per group with a categorical `z`).
|
|
99
107
|
|
|
108
|
+
`sig` on `box` and `violin` writes the Kruskal-Wallis p and brackets the pairs that differ, with stars (`ann`: the
|
|
109
|
+
p-values), Holm-corrected.
|
|
110
|
+
|
|
111
|
+
### Uncertainty and labels
|
|
112
|
+
|
|
113
|
+
`ci` draws the mean of the rows at each x with a bootstrap 95% interval: a band on `line` and `step`, error bars
|
|
114
|
+
on `bar` and `barh` (`n_boot=` resamples, 1000; `seed=`, 0). `errbar` is the mean and interval per series or
|
|
115
|
+
`by=` group, `sd` for mean ± one standard deviation instead, `sig` for the tests as on `box`.
|
|
116
|
+
`endlab` writes each line's name at its right end instead of a legend, on `line`, `step`, `band` and `area`.
|
|
117
|
+
`lollipop` is a dot per category on a stem from 0, or with `z` a dumbbell from `y` to `z` (`sort` by the change).
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
kx.plot(df, 'month', 'temp', 'line-ci-endlab') # each month's mean, a 95% band, the name at the end
|
|
121
|
+
kx.plot(df, 'fare', spec='errbar-sig', by='pclass') # mean and interval per class, with the tests
|
|
122
|
+
kx.plot(df, 'city', 'before', 'after', 'lollipop-sort')
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
`facet` draws a plot once per value of a column, `kx.plot(df, 'pclass', 'port', 'crosstab-facet', facet='sex')`,
|
|
126
|
+
with every category in every panel, shared axes, and one colour scale and colorbar for the colour kinds.
|
|
127
|
+
|
|
100
128
|
Unknown tokens raise an error instead of being guessed, with the closest valid tokens as a hint.
|
|
101
129
|
Everything is inspectable: `kx.grammar()`, `kx.grammar('area')`, `kx.parse('leg-scatter')`, `kx.show('dark')`,
|
|
102
130
|
`kx.source('scatter')`.
|
|
@@ -110,13 +138,53 @@ kx.missing(df) # share of NaNs per column, t
|
|
|
110
138
|
kx.plot(df, 'nullmap-sort') # where the NaNs are: one pixel row per table row
|
|
111
139
|
kx.plot(df, 'heat-corr-ann') # correlations of the numeric columns, -1 to 1
|
|
112
140
|
kx.plot(df, 'heat') # any numeric DataFrame or 2-D array as coloured cells
|
|
141
|
+
kx.cramers(df, cluster=True) # Cramér's V of the categorical columns, 0 to 1
|
|
142
|
+
kx.plot(df, 'cluster-corr') # correlations, similar columns side by side, with trees
|
|
113
143
|
kx.plot(df, 'pclass', spec='count', by='survived') # rows per category, split by a second column
|
|
114
144
|
kx.plot(df, 'pclass', 'port', 'crosstab-norm-ann') # how often each pair of categories occurs
|
|
145
|
+
kx.plot(df, 'port', 'sex', 'survived', spec='mosaic-ann') # tiles sized by count, up to 3 categoricals
|
|
146
|
+
kx.plot(df, 'pclass', 'sex', spec='treemap-ann') # a hierarchy of categories; 'sunburst' as rings
|
|
115
147
|
kx.plot(df, 'age', 'fare', 'hexbin-logc') # points per hexagon; with a z, its mean per hexagon
|
|
148
|
+
kx.plot(df, 'port', 'donut-ann') # shares of a whole, the total in the hole
|
|
149
|
+
kx.plot(df[['age', 'fare', 'pclass', 'survived']], 'radar', by='survived') # each group's profile
|
|
150
|
+
kx.plot(df[['age', 'fare', 'pclass', 'sex']], 'parallel-mean', by='sex') # every row across columns
|
|
151
|
+
kx.plot(df, 'pair', by='sex') # every numeric column against every other
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
`heat`, `cluster`, `missing`, `nullmap`, `radar`, `parallel` and `pair` take the whole table and no column names
|
|
155
|
+
(`radar`, `parallel` and `pair` take `by=`, a column of groups); `kx.plot(df[cols], 'heat')` for some columns.
|
|
156
|
+
`wrap` breaks long tick labels onto several lines.
|
|
157
|
+
|
|
158
|
+

|
|
159
|
+
|
|
160
|
+
### Images
|
|
161
|
+
|
|
162
|
+
Image kinds take an `(N, H, W)` or `(N, H, W, C)` array (channels first works too), or a list of arrays, PIL images
|
|
163
|
+
or file paths, with the labels as `y`. `kx.load('shapes')` is a small demo set.
|
|
164
|
+
|
|
165
|
+
```python
|
|
166
|
+
d = kx.load('shapes')
|
|
167
|
+
kx.plot(d['images'], d['labels'], 'imgrid') # 6 random images per class, one row each
|
|
168
|
+
kx.plot(paths, labels, 'imgrid', idx=[3, 17, 42]) # chosen images, titled with their labels
|
|
169
|
+
kx.plot(d['images'], d['labels'], 'meanimg') # the mean image of each class; -std: where pixels vary
|
|
170
|
+
kx.plot(d['images'], d['labels'], 'colorhist') # pixel values per channel and class; -hsv, -map
|
|
171
|
+
kx.plot(d['images'], 'imhist', idx=[0, 1]) # images beside their own channel histograms
|
|
172
|
+
kx.plot(d['images'], d['masks'], pred, 'segmask') # image, mask, outlines; a prediction adds its IoU
|
|
173
|
+
kx.plot(d['images'], d['saliency'], 'saliency') # Grad-CAM or any map over its image, smoothed to fit
|
|
174
|
+
kx.plot(d['images'], d['labels'], d['proba'], 'miscls') # the mistakes, the most confident first
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+

|
|
178
|
+
|
|
179
|
+
### Embeddings
|
|
180
|
+
|
|
181
|
+
```python
|
|
182
|
+
kx.embed(df, by='label') # PCA of the numeric columns, explained variance on the axes
|
|
183
|
+
kx.embed(images, by=labels, method='tsne') # t-SNE or UMAP: pip install 'kx-plot[embed]'
|
|
184
|
+
kx.plot(xy, labels, 'embed-ann') # coordinates you already have, names at each group
|
|
116
185
|
```
|
|
117
186
|
|
|
118
|
-
`
|
|
119
|
-
columns. `wrap` breaks long tick labels onto several lines.
|
|
187
|
+
`kx.embed` returns the axes, and the coordinates are `ax.embedding`.
|
|
120
188
|
|
|
121
189
|
### Machine learning
|
|
122
190
|
|
|
@@ -174,6 +242,7 @@ other cycled properties (such as `paper`'s linestyles) stay.
|
|
|
174
242
|
| `ibm` | IBM Design Colors |
|
|
175
243
|
|
|
176
244
|
`kx.palette('okabe')` returns the hex codes. A list of colours works too: `palette=['#264653', '#e9c46a']`.
|
|
245
|
+
`kx.register('brand', colors)` adds a named palette for the session, `cmap=True` a colourmap through the colours.
|
|
177
246
|
|
|
178
247
|
## Colourmaps
|
|
179
248
|
|
|
@@ -11,6 +11,9 @@ matplotlib, numpy and pandas and works offline, so it also runs in Kaggle compet
|
|
|
11
11
|
|
|
12
12
|
```bash
|
|
13
13
|
pip install kx-plot
|
|
14
|
+
|
|
15
|
+
# adds t-SNE and UMAP to kx.embed (PCA needs neither)
|
|
16
|
+
pip install 'kx-plot[embed]'
|
|
14
17
|
```
|
|
15
18
|
|
|
16
19
|
```python
|
|
@@ -44,14 +47,16 @@ kx.plot(df.value, spec='box', by=df.group) # one box per group (also rid
|
|
|
44
47
|
|
|
45
48
|
| Token | Values |
|
|
46
49
|
|-------|-----------------------------------------------------------------------------------------------|
|
|
47
|
-
| kind | `line` `step` `area` `band` `scatter` `bar` `barh` `hist` `kde` `ridge` `ecdf`
|
|
48
|
-
| | `strip` `qq` `count` `crosstab` `hexbin` `heat` `missing` `nullmap`
|
|
50
|
+
| kind | `line` `step` `area` `band` `scatter` `bar` `barh` `lollipop` `hist` `kde` `ridge` `ecdf` |
|
|
51
|
+
| | `box` `violin` `strip` `errbar` `qq` `count` `crosstab` `hexbin` `heat` `missing` `nullmap` |
|
|
52
|
+
| | `pie` `donut` `radar` `parallel` `pair` `cluster` `mosaic` `treemap` `sunburst` |
|
|
49
53
|
| | ML: `cm` `roc` `pr` `calib` `proba` `thresh` `gain` `lift` `pva` `resid` `imp` `loss` |
|
|
50
|
-
| | `lcurve` `vcurve` `elbow`
|
|
51
|
-
|
|
|
54
|
+
| | `lcurve` `vcurve` `elbow` `embed` |
|
|
55
|
+
| | Images: `imgrid` `meanimg` `colorhist` `imhist` `segmask` `saliency` `miscls` |
|
|
56
|
+
| theme | `dark` `light` `minimal` `colorblind` `paper` `science` `talk` `poster` `thesis` |
|
|
52
57
|
| flags | `grid` `leg` `legout` `tight` `rot` `wrap` `logx` `logy` `logxy` `symlogy` `zero` `eq` `pct` |
|
|
53
|
-
| | `si`; per kind: `stack` `norm` `cum` `date` `mk` `
|
|
54
|
-
| | `logc` `corr` `all` `diag` `fit` `best`
|
|
58
|
+
| | `si` `facet`; per kind: `stack` `norm` `cum` `date` `mk` `endlab` `ci` `sort` `ann` `mean` |
|
|
59
|
+
| | `median` `sd` `nocb` `sym` `logc` `corr` `all` `diag` `fit` `best` `raw` `sig` |
|
|
55
60
|
|
|
56
61
|
`stack` works with `area`, `bar`, `barh` and `hist`. `norm` is a 100% stack for `area` and a
|
|
57
62
|
density (area 1) for `hist`. `cum` makes `hist` cumulative; `hist-norm-cum` is the CDF.
|
|
@@ -59,6 +64,26 @@ density (area 1) for `hist`. `cum` makes `hist` cumulative; `hist-norm-cum` is t
|
|
|
59
64
|
`diag` adds a dashed `y = x` line to `scatter` and `hexbin`; `fit` adds a least-squares line to `scatter`, with
|
|
60
65
|
its slope and R² in the legend (one line per group with a categorical `z`).
|
|
61
66
|
|
|
67
|
+
`sig` on `box` and `violin` writes the Kruskal-Wallis p and brackets the pairs that differ, with stars (`ann`: the
|
|
68
|
+
p-values), Holm-corrected.
|
|
69
|
+
|
|
70
|
+
### Uncertainty and labels
|
|
71
|
+
|
|
72
|
+
`ci` draws the mean of the rows at each x with a bootstrap 95% interval: a band on `line` and `step`, error bars
|
|
73
|
+
on `bar` and `barh` (`n_boot=` resamples, 1000; `seed=`, 0). `errbar` is the mean and interval per series or
|
|
74
|
+
`by=` group, `sd` for mean ± one standard deviation instead, `sig` for the tests as on `box`.
|
|
75
|
+
`endlab` writes each line's name at its right end instead of a legend, on `line`, `step`, `band` and `area`.
|
|
76
|
+
`lollipop` is a dot per category on a stem from 0, or with `z` a dumbbell from `y` to `z` (`sort` by the change).
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
kx.plot(df, 'month', 'temp', 'line-ci-endlab') # each month's mean, a 95% band, the name at the end
|
|
80
|
+
kx.plot(df, 'fare', spec='errbar-sig', by='pclass') # mean and interval per class, with the tests
|
|
81
|
+
kx.plot(df, 'city', 'before', 'after', 'lollipop-sort')
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
`facet` draws a plot once per value of a column, `kx.plot(df, 'pclass', 'port', 'crosstab-facet', facet='sex')`,
|
|
85
|
+
with every category in every panel, shared axes, and one colour scale and colorbar for the colour kinds.
|
|
86
|
+
|
|
62
87
|
Unknown tokens raise an error instead of being guessed, with the closest valid tokens as a hint.
|
|
63
88
|
Everything is inspectable: `kx.grammar()`, `kx.grammar('area')`, `kx.parse('leg-scatter')`, `kx.show('dark')`,
|
|
64
89
|
`kx.source('scatter')`.
|
|
@@ -72,13 +97,53 @@ kx.missing(df) # share of NaNs per column, t
|
|
|
72
97
|
kx.plot(df, 'nullmap-sort') # where the NaNs are: one pixel row per table row
|
|
73
98
|
kx.plot(df, 'heat-corr-ann') # correlations of the numeric columns, -1 to 1
|
|
74
99
|
kx.plot(df, 'heat') # any numeric DataFrame or 2-D array as coloured cells
|
|
100
|
+
kx.cramers(df, cluster=True) # Cramér's V of the categorical columns, 0 to 1
|
|
101
|
+
kx.plot(df, 'cluster-corr') # correlations, similar columns side by side, with trees
|
|
75
102
|
kx.plot(df, 'pclass', spec='count', by='survived') # rows per category, split by a second column
|
|
76
103
|
kx.plot(df, 'pclass', 'port', 'crosstab-norm-ann') # how often each pair of categories occurs
|
|
104
|
+
kx.plot(df, 'port', 'sex', 'survived', spec='mosaic-ann') # tiles sized by count, up to 3 categoricals
|
|
105
|
+
kx.plot(df, 'pclass', 'sex', spec='treemap-ann') # a hierarchy of categories; 'sunburst' as rings
|
|
77
106
|
kx.plot(df, 'age', 'fare', 'hexbin-logc') # points per hexagon; with a z, its mean per hexagon
|
|
107
|
+
kx.plot(df, 'port', 'donut-ann') # shares of a whole, the total in the hole
|
|
108
|
+
kx.plot(df[['age', 'fare', 'pclass', 'survived']], 'radar', by='survived') # each group's profile
|
|
109
|
+
kx.plot(df[['age', 'fare', 'pclass', 'sex']], 'parallel-mean', by='sex') # every row across columns
|
|
110
|
+
kx.plot(df, 'pair', by='sex') # every numeric column against every other
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
`heat`, `cluster`, `missing`, `nullmap`, `radar`, `parallel` and `pair` take the whole table and no column names
|
|
114
|
+
(`radar`, `parallel` and `pair` take `by=`, a column of groups); `kx.plot(df[cols], 'heat')` for some columns.
|
|
115
|
+
`wrap` breaks long tick labels onto several lines.
|
|
116
|
+
|
|
117
|
+

|
|
118
|
+
|
|
119
|
+
### Images
|
|
120
|
+
|
|
121
|
+
Image kinds take an `(N, H, W)` or `(N, H, W, C)` array (channels first works too), or a list of arrays, PIL images
|
|
122
|
+
or file paths, with the labels as `y`. `kx.load('shapes')` is a small demo set.
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
d = kx.load('shapes')
|
|
126
|
+
kx.plot(d['images'], d['labels'], 'imgrid') # 6 random images per class, one row each
|
|
127
|
+
kx.plot(paths, labels, 'imgrid', idx=[3, 17, 42]) # chosen images, titled with their labels
|
|
128
|
+
kx.plot(d['images'], d['labels'], 'meanimg') # the mean image of each class; -std: where pixels vary
|
|
129
|
+
kx.plot(d['images'], d['labels'], 'colorhist') # pixel values per channel and class; -hsv, -map
|
|
130
|
+
kx.plot(d['images'], 'imhist', idx=[0, 1]) # images beside their own channel histograms
|
|
131
|
+
kx.plot(d['images'], d['masks'], pred, 'segmask') # image, mask, outlines; a prediction adds its IoU
|
|
132
|
+
kx.plot(d['images'], d['saliency'], 'saliency') # Grad-CAM or any map over its image, smoothed to fit
|
|
133
|
+
kx.plot(d['images'], d['labels'], d['proba'], 'miscls') # the mistakes, the most confident first
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+

|
|
137
|
+
|
|
138
|
+
### Embeddings
|
|
139
|
+
|
|
140
|
+
```python
|
|
141
|
+
kx.embed(df, by='label') # PCA of the numeric columns, explained variance on the axes
|
|
142
|
+
kx.embed(images, by=labels, method='tsne') # t-SNE or UMAP: pip install 'kx-plot[embed]'
|
|
143
|
+
kx.plot(xy, labels, 'embed-ann') # coordinates you already have, names at each group
|
|
78
144
|
```
|
|
79
145
|
|
|
80
|
-
`
|
|
81
|
-
columns. `wrap` breaks long tick labels onto several lines.
|
|
146
|
+
`kx.embed` returns the axes, and the coordinates are `ax.embedding`.
|
|
82
147
|
|
|
83
148
|
### Machine learning
|
|
84
149
|
|
|
@@ -136,6 +201,7 @@ other cycled properties (such as `paper`'s linestyles) stay.
|
|
|
136
201
|
| `ibm` | IBM Design Colors |
|
|
137
202
|
|
|
138
203
|
`kx.palette('okabe')` returns the hex codes. A list of colours works too: `palette=['#264653', '#e9c46a']`.
|
|
204
|
+
`kx.register('brand', colors)` adds a named palette for the session, `cmap=True` a colourmap through the colours.
|
|
139
205
|
|
|
140
206
|
## Colourmaps
|
|
141
207
|
|
|
@@ -2,31 +2,45 @@
|
|
|
2
2
|
kx: tiny matplotlib helper.
|
|
3
3
|
|
|
4
4
|
Token grammar for kx.plot(spec): kind-theme-flag-flag-...
|
|
5
|
-
kind : line | step | area | band | scatter | bar | barh | hist | kde | ridge | ecdf | box | violin
|
|
6
|
-
| qq | heat | crosstab | count | missing | nullmap | hexbin
|
|
5
|
+
kind : line | step | area | band | scatter | bar | barh | lollipop | hist | kde | ridge | ecdf | box | violin
|
|
6
|
+
| strip | errbar | qq | heat | crosstab | count | missing | nullmap | hexbin | pie | donut | radar | parallel
|
|
7
|
+
| pair | cluster | mosaic | treemap | sunburst
|
|
7
8
|
| cm | roc | pr | calib | proba | thresh | gain | lift | pva | resid | imp | loss
|
|
8
|
-
| lcurve | vcurve | elbow
|
|
9
|
+
| lcurve | vcurve | elbow | embed
|
|
10
|
+
| imgrid | meanimg | colorhist | imhist | segmask | saliency | miscls
|
|
9
11
|
theme : any file name in styles/
|
|
10
|
-
flags : grid | leg | legout | tight | rot | wrap | logx | logy | logxy | symlogy | zero | eq | pct | si
|
|
11
|
-
and per kind: stack norm cum (bars, area, hist), date mk (lines), sort ann (bars, count),
|
|
12
|
+
flags : grid | leg | legout | tight | rot | wrap | logx | logy | logxy | symlogy | zero | eq | pct | si | facet
|
|
13
|
+
and per kind: stack norm cum (bars, area, hist), date mk endlab (lines), sort ann (bars, count, lollipop),
|
|
14
|
+
ci (line, step, bar, barh),
|
|
12
15
|
stack norm (count),
|
|
13
|
-
mean median ann (distributions),
|
|
16
|
+
mean median ann (distributions), sig (box, violin, errbar), ann sd (errbar),
|
|
17
|
+
nocb sym logc (scatter, heat, hexbin, cluster), corr ann (heat, cluster),
|
|
14
18
|
norm ann nocb logc (crosstab), ann all (missing), sort (nullmap), diag (scatter, hexbin),
|
|
15
19
|
fit (scatter), norm ann nocb (cm), norm (proba), best (thresh, loss, elbow),
|
|
16
|
-
nocb sym logc (resid)
|
|
20
|
+
nocb sym logc (resid), ann sort (pie, donut), ann (mosaic, treemap, sunburst), raw (radar), mean (parallel),
|
|
21
|
+
std (meanimg), hsv map (colorhist), hsv (imhist), ann nocb sym logc (embed).
|
|
17
22
|
kx.grammar(kind) lists them.
|
|
18
|
-
by= : group labels for x, one series per group (kde, ridge, ecdf, box, violin, strip, qq, count)
|
|
19
|
-
|
|
23
|
+
by= : group labels for x, one series per group (kde, ridge, ecdf, box, violin, strip, errbar, qq, count);
|
|
24
|
+
for radar, parallel and pair a column of the table: kx.plot(df, 'radar', by='class')
|
|
25
|
+
images : image kinds take an (N, H, W[, C]) array or a list of arrays or file paths, labels as y:
|
|
26
|
+
kx.plot(images, labels, 'imgrid')
|
|
27
|
+
facet= : with the flag facet, one panel per value of a column, on shared axes and one colour scale:
|
|
28
|
+
kx.plot(df, 'pclass', 'port', 'crosstab-facet', facet='sex')
|
|
29
|
+
table : heat, cluster, missing, nullmap, loss, radar, parallel, pair take a whole DataFrame or 2-D array:
|
|
20
30
|
kx.plot(df, 'heat-corr'); a dict or a Keras History works too: kx.plot(model.fit(...), 'loss')
|
|
21
31
|
|
|
22
32
|
Palettes (kx.use(theme, palette="okabe")): any file name in styles/palettes/
|
|
23
33
|
Colormaps (kx.use(theme, cmap="magma")): kx.cmaps()
|
|
34
|
+
kx.register("brand", colors): a palette (cmap=True: a colormap) of your own for this session, then as above.
|
|
24
35
|
with kx.context(theme, ...): the same as kx.use, for one block only.
|
|
25
36
|
kx.save("fig.png"): saves to /kaggle/working on Kaggle, the current folder elsewhere.
|
|
37
|
+
kx.load("passengers"): a demo table; kx.load("shapes"): a dict of image arrays. kx.datasets() lists them.
|
|
26
38
|
kx.missing(df): the share of missing values per column, the same as kx.plot(df, 'missing-ann').
|
|
27
39
|
kx.grid(5): a figure of 5 panels as a flat array of axes, for kx.plot(..., ax=).
|
|
28
40
|
kx.roc_auc(y_true, score) and kx.pr_ap(y_true, score): area under the ROC curve and average precision, in numpy.
|
|
29
41
|
kx.evaluate(y_true, score): a model report, the panels picked from the data (binary, multiclass or regression).
|
|
42
|
+
kx.embed(df, by='label'): the rows in 2-D (PCA; method='tsne' or 'umap' with pip install 'kx-plot[embed]').
|
|
43
|
+
kx.cramers(df): how strongly each pair of categorical columns goes together (Cramér's V), as a heat map.
|
|
30
44
|
kx.grammar("area") and kx.source("area") explain one kind; kx.parse(spec) shows how a spec is read.
|
|
31
45
|
"""
|
|
32
46
|
import glob
|
|
@@ -39,18 +53,32 @@ from typing import Any
|
|
|
39
53
|
import pandas as pd
|
|
40
54
|
from matplotlib.axes import Axes
|
|
41
55
|
|
|
56
|
+
from ._cramers import cramers
|
|
42
57
|
from ._data import datasets, load
|
|
58
|
+
from ._embed import embed
|
|
43
59
|
from ._evaluate import evaluate
|
|
44
60
|
from ._grid import grid
|
|
45
61
|
from ._metrics import pr_ap, roc_auc
|
|
46
62
|
from ._plot import plot
|
|
47
63
|
from ._save import save
|
|
48
64
|
from ._spec import COMMON_FLAGS, KINDS, Spec, all_flags, parse
|
|
49
|
-
from ._theme import
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
65
|
+
from ._theme import (
|
|
66
|
+
BREWER_CMAPS,
|
|
67
|
+
BUILTIN_CMAPS,
|
|
68
|
+
VENDORED_CMAPS,
|
|
69
|
+
cmaps,
|
|
70
|
+
context,
|
|
71
|
+
palette,
|
|
72
|
+
palettes,
|
|
73
|
+
register,
|
|
74
|
+
show,
|
|
75
|
+
styles,
|
|
76
|
+
use,
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
__all__ = ["BREWER_CMAPS", "BUILTIN_CMAPS", "VENDORED_CMAPS", "Spec", "__version__", "cmaps", "context", "cramers",
|
|
80
|
+
"datasets", "embed", "evaluate", "grammar", "grid", "load", "missing", "palette", "palettes", "parse",
|
|
81
|
+
"plot", "pr_ap", "register", "roc_auc", "save", "show", "source", "styles", "use"]
|
|
54
82
|
|
|
55
83
|
|
|
56
84
|
def _version() -> str:
|
|
@@ -88,6 +116,10 @@ def grammar(kind: str | None = None) -> None:
|
|
|
88
116
|
print("data : takes a DataFrame or 2-D array")
|
|
89
117
|
if k.takes_by:
|
|
90
118
|
print("by= : group labels for x, one per group")
|
|
119
|
+
if k.panels:
|
|
120
|
+
print("axes : draws several panels; kx.plot returns them as a flat array")
|
|
121
|
+
if k.projection:
|
|
122
|
+
print(f"axes : {k.projection}; kx.plot swaps a given ax for {k.projection} axes in its place")
|
|
91
123
|
return
|
|
92
124
|
print("kind :", sorted(KINDS))
|
|
93
125
|
print("theme:", styles())
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""kx.cramers: how strongly each pair of categorical columns goes together, as a heat map."""
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
import matplotlib as mpl
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
from matplotlib.axes import Axes
|
|
8
|
+
|
|
9
|
+
from . import _stats
|
|
10
|
+
from ._plot import plot as draw
|
|
11
|
+
|
|
12
|
+
MAX_LEVELS = 20
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def cramers(df: pd.DataFrame, cols: list[str] | None = None, spec: str = "", cluster: bool = False,
|
|
16
|
+
plot: bool = True, **kw: Any) -> Axes | pd.DataFrame:
|
|
17
|
+
"""Cramér's V (bias-corrected, 0 = independent, 1 = one fixes the other) for every pair of categorical
|
|
18
|
+
columns, drawn with heat-ann on 0..1: kx.cramers(df). The columns are cols=, else every column that is not
|
|
19
|
+
a float with at most 20 values (text, bool, small integers such as a class). cluster=True puts the columns
|
|
20
|
+
that go together side by side; the names are turned (rot, tight). plot=False returns the matrix. spec= adds
|
|
21
|
+
a theme and flags; other keywords go to kx.plot (title=, ax=)."""
|
|
22
|
+
if cols is None:
|
|
23
|
+
cols = [c for c in df.columns
|
|
24
|
+
if not pd.api.types.is_float_dtype(df[c]) and df[c].nunique(dropna=True) <= MAX_LEVELS]
|
|
25
|
+
else:
|
|
26
|
+
missing = [c for c in cols if c not in df.columns]
|
|
27
|
+
if missing:
|
|
28
|
+
raise ValueError(f"cols= names {missing}, which the table does not have. Columns: {list(df.columns)}")
|
|
29
|
+
if len(cols) < 2:
|
|
30
|
+
raise ValueError(f"Cramér's V compares pairs of categorical columns; found {list(cols)}. Pass cols=[...]")
|
|
31
|
+
v = pd.DataFrame(np.nan, index=cols, columns=cols, dtype=float)
|
|
32
|
+
for i, a in enumerate(cols):
|
|
33
|
+
for b in cols[i:]:
|
|
34
|
+
v.loc[a, b] = v.loc[b, a] = _stats.cramers_v(df[a], df[b])
|
|
35
|
+
if cluster:
|
|
36
|
+
far = (1 - v.fillna(0)).to_numpy(copy=True)
|
|
37
|
+
np.fill_diagonal(far, 0)
|
|
38
|
+
order = _stats.leaves(_stats.linkage(far, distances=True))
|
|
39
|
+
v = v.iloc[order, order]
|
|
40
|
+
if not plot:
|
|
41
|
+
return v
|
|
42
|
+
ax = draw(v, "-".join(["heat", "ann", "rot", "tight", *([spec] if spec else [])]),
|
|
43
|
+
**{"cmap": "blues", "norm": mpl.colors.Normalize(0, 1), "fmt": "{:.2f}", **kw})
|
|
44
|
+
bar = ax.images[0].colorbar
|
|
45
|
+
if bar is not None:
|
|
46
|
+
bar.set_label("Cramér's V")
|
|
47
|
+
return ax
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Demo data that ships in data/."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
import pandas as pd
|
|
4
|
+
|
|
5
|
+
from . import _files
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def datasets() -> list[str]:
|
|
9
|
+
"""List the names available to kx.load(): tables (CSV) and array sets (NPZ, such as images)."""
|
|
10
|
+
return sorted(_files.names("data", ".csv") + _files.names("data", ".npz"))
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def load(name: str) -> pd.DataFrame | dict[str, np.ndarray]:
|
|
14
|
+
"""Read data/<name>.csv as a DataFrame, or data/<name>.npz as a dict of arrays:
|
|
15
|
+
images = kx.load('shapes')['images']."""
|
|
16
|
+
if name not in datasets():
|
|
17
|
+
raise ValueError(f"unknown dataset {name!r}. Available: {datasets()}")
|
|
18
|
+
if name in _files.names("data", ".npz"):
|
|
19
|
+
with np.load(_files.path("data", f"{name}.npz"), allow_pickle=False) as arrays:
|
|
20
|
+
return dict(arrays)
|
|
21
|
+
return pd.read_csv(_files.path("data", f"{name}.csv"))
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""kx.embed: project a table or images to 2-D (PCA, t-SNE or UMAP) and plot it with the embed kind."""
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
import pandas as pd
|
|
6
|
+
from matplotlib.axes import Axes
|
|
7
|
+
from numpy.typing import ArrayLike
|
|
8
|
+
|
|
9
|
+
from ._image import images
|
|
10
|
+
from ._plot import plot
|
|
11
|
+
|
|
12
|
+
METHODS = ("pca", "tsne", "umap")
|
|
13
|
+
NEEDS = {"tsne": ("sklearn.manifold", "TSNE", "scikit-learn"), "umap": ("umap", "UMAP", "umap-learn")}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def embed(data: Any, method: str = "pca", by: ArrayLike | str | None = None, spec: str = "", seed: int = 0,
|
|
17
|
+
ax: Axes | None = None, title: str | None = None, **kw: Any) -> Axes:
|
|
18
|
+
"""kx.embed(df, by='label') or kx.embed(images, labels): the rows in 2-D, coloured by label.
|
|
19
|
+
data: a DataFrame (its numeric columns, standardised; by= may name a column, left out of them), a 2-D
|
|
20
|
+
array of features, or images (an (N, H, W[, C]) array or a list, flattened; all one size).
|
|
21
|
+
method: 'pca' (numpy, the explained variance in the axis labels), 'tsne' (scikit-learn) or 'umap'
|
|
22
|
+
(umap-learn): pip install 'kx-plot[embed]'. seed= fixes t-SNE and UMAP; other keywords go to them.
|
|
23
|
+
spec= adds a theme and flags (kx.embed(df, by='label', spec='dark-ann')). Returns the axes; the coordinates
|
|
24
|
+
are ax.embedding."""
|
|
25
|
+
if method not in METHODS:
|
|
26
|
+
raise ValueError(f"unknown method {method!r}; use one of {list(METHODS)}")
|
|
27
|
+
if kw and method == "pca":
|
|
28
|
+
raise TypeError(f"method='pca' takes no options, got {sorted(kw)}")
|
|
29
|
+
features, by = _features(data, by)
|
|
30
|
+
coords, names = _project(features, method, seed, kw)
|
|
31
|
+
axes = plot(pd.Series(coords[:, 0], name=names[0]), pd.Series(coords[:, 1], name=names[1]),
|
|
32
|
+
spec="-".join(["embed", *([spec] if spec else [])]), by=by, ax=ax, title=title)
|
|
33
|
+
axes.embedding = coords
|
|
34
|
+
return axes
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _features(data: Any, by: ArrayLike | str | None) -> tuple[np.ndarray, ArrayLike | None]:
|
|
38
|
+
"""The rows as a float matrix to project, and by= as labels (a column name taken out of a table)."""
|
|
39
|
+
if isinstance(data, pd.DataFrame):
|
|
40
|
+
if isinstance(by, str):
|
|
41
|
+
if by not in data.columns:
|
|
42
|
+
raise ValueError(f"no column {by!r} in the DataFrame. Columns: {list(data.columns)}")
|
|
43
|
+
data, by = data.drop(columns=by), data[by]
|
|
44
|
+
cols = [c for c in data.columns
|
|
45
|
+
if pd.api.types.is_numeric_dtype(data[c]) and not pd.api.types.is_bool_dtype(data[c])]
|
|
46
|
+
if not cols:
|
|
47
|
+
raise ValueError("kx.embed needs numeric columns to project; this table has none")
|
|
48
|
+
values = data[cols].to_numpy(dtype=float)
|
|
49
|
+
spread = values.std(axis=0)
|
|
50
|
+
values = (values - values.mean(axis=0)) / np.where(spread > 0, spread, 1) # one unit per column
|
|
51
|
+
elif isinstance(by, str):
|
|
52
|
+
raise TypeError(f"by={by!r} names a column, which needs a DataFrame: kx.embed(df, by={by!r})")
|
|
53
|
+
elif isinstance(data, np.ndarray) and data.dtype != object and data.ndim == 2:
|
|
54
|
+
values = data.astype(float)
|
|
55
|
+
else:
|
|
56
|
+
found = images(data)
|
|
57
|
+
if len({im.shape for im in found}) > 1:
|
|
58
|
+
raise ValueError("kx.embed compares images pixel by pixel; they need one size and one channel count")
|
|
59
|
+
values = np.stack([im.ravel() for im in found])
|
|
60
|
+
if not np.isfinite(values).all():
|
|
61
|
+
raise ValueError("kx.embed needs every value; fill or drop the NaNs first (df.dropna())")
|
|
62
|
+
if len(values) < 3:
|
|
63
|
+
raise ValueError(f"kx.embed needs at least 3 rows, got {len(values)}")
|
|
64
|
+
if by is not None and np.size(by) != len(values):
|
|
65
|
+
raise ValueError(f"there are {len(values)} rows but {np.size(by)} labels")
|
|
66
|
+
return values, by
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _project(values: np.ndarray, method: str, seed: int, kw: dict[str, Any]) -> tuple[np.ndarray, list[str]]:
|
|
70
|
+
"""2-D coordinates and the axis names."""
|
|
71
|
+
if method == "pca":
|
|
72
|
+
if values.shape[1] < 2:
|
|
73
|
+
raise ValueError("PCA to 2-D needs at least 2 features")
|
|
74
|
+
centred = values - values.mean(axis=0)
|
|
75
|
+
u, s, vt = np.linalg.svd(centred, full_matrices=False)
|
|
76
|
+
big = np.argmax(np.abs(vt[:2]), axis=1)
|
|
77
|
+
signs = np.sign(vt[[0, 1], big])
|
|
78
|
+
coords = u[:, :2] * s[:2] * signs
|
|
79
|
+
share = s ** 2 / (s ** 2).sum()
|
|
80
|
+
return coords, [f"PC{k + 1} ({share[k]:.0%})" for k in range(2)]
|
|
81
|
+
module, cls, package = NEEDS[method]
|
|
82
|
+
try:
|
|
83
|
+
model = getattr(__import__(module, fromlist=[cls]), cls)
|
|
84
|
+
except ImportError as err:
|
|
85
|
+
raise ImportError(f"method={method!r} needs {package}: pip install 'kx-plot[embed]'") from err
|
|
86
|
+
found = model(n_components=2, random_state=seed, **kw).fit_transform(values)
|
|
87
|
+
name = "t-SNE" if method == "tsne" else "UMAP"
|
|
88
|
+
return np.asarray(found, dtype=float), [f"{name} 1", f"{name} 2"]
|