kx-plot 0.5.0__tar.gz → 0.6.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 (98) hide show
  1. {kx_plot-0.5.0 → kx_plot-0.6.0}/CHANGELOG.md +57 -1
  2. {kx_plot-0.5.0 → kx_plot-0.6.0}/PKG-INFO +61 -7
  3. {kx_plot-0.5.0 → kx_plot-0.6.0}/README.md +57 -6
  4. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/__init__.py +28 -10
  5. kx_plot-0.6.0/kx/_cramers.py +47 -0
  6. kx_plot-0.6.0/kx/_data.py +21 -0
  7. kx_plot-0.6.0/kx/_embed.py +88 -0
  8. kx_plot-0.6.0/kx/_image.py +244 -0
  9. kx_plot-0.6.0/kx/_plot.py +347 -0
  10. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/_spec.py +9 -4
  11. kx_plot-0.6.0/kx/_stats.py +188 -0
  12. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/_util.py +18 -0
  13. kx_plot-0.6.0/kx/data/embedding.csv +601 -0
  14. kx_plot-0.6.0/kx/data/shapes.npz +0 -0
  15. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/kinds/__init__.py +1 -1
  16. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/kinds/basic.py +178 -1
  17. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/kinds/dist.py +53 -3
  18. kx_plot-0.6.0/kx/kinds/image.py +387 -0
  19. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/kinds/ml.py +56 -2
  20. kx_plot-0.6.0/kx/kinds/table.py +518 -0
  21. {kx_plot-0.5.0 → kx_plot-0.6.0}/pyproject.toml +7 -1
  22. kx_plot-0.6.0/tests/helpers.py +16 -0
  23. kx_plot-0.6.0/tests/test_api.py +213 -0
  24. kx_plot-0.6.0/tests/test_basic.py +345 -0
  25. kx_plot-0.6.0/tests/test_data.py +131 -0
  26. kx_plot-0.6.0/tests/test_dist.py +191 -0
  27. kx_plot-0.6.0/tests/test_flags.py +377 -0
  28. kx_plot-0.6.0/tests/test_image.py +499 -0
  29. kx_plot-0.6.0/tests/test_ml.py +699 -0
  30. kx_plot-0.6.0/tests/test_plot.py +320 -0
  31. kx_plot-0.6.0/tests/test_stats.py +117 -0
  32. kx_plot-0.6.0/tests/test_table.py +567 -0
  33. kx_plot-0.6.0/tests/test_theme.py +195 -0
  34. kx_plot-0.5.0/kx/_data.py +0 -16
  35. kx_plot-0.5.0/kx/_plot.py +0 -170
  36. kx_plot-0.5.0/kx/kinds/table.py +0 -132
  37. kx_plot-0.5.0/tests/test_kx.py +0 -2029
  38. {kx_plot-0.5.0 → kx_plot-0.6.0}/.gitignore +0 -0
  39. {kx_plot-0.5.0 → kx_plot-0.6.0}/LICENSE +0 -0
  40. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/_evaluate.py +0 -0
  41. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/_files.py +0 -0
  42. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/_grid.py +0 -0
  43. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/_metrics.py +0 -0
  44. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/_save.py +0 -0
  45. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/_theme.py +0 -0
  46. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/data/binary.csv +0 -0
  47. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/data/cloud.csv +0 -0
  48. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/data/curves.csv +0 -0
  49. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/data/daily.csv +0 -0
  50. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/data/dists.csv +0 -0
  51. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/data/history.csv +0 -0
  52. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/data/importance.csv +0 -0
  53. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/data/monthly.csv +0 -0
  54. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/data/multiclass.csv +0 -0
  55. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/data/passengers.csv +0 -0
  56. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/data/regression.csv +0 -0
  57. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/data/waves.csv +0 -0
  58. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/cmaps/LICENCES.md +0 -0
  59. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/cmaps/balance.txt +0 -0
  60. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/cmaps/bam.txt +0 -0
  61. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/cmaps/batlow.txt +0 -0
  62. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/cmaps/cork.txt +0 -0
  63. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/cmaps/davos.txt +0 -0
  64. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/cmaps/deep.txt +0 -0
  65. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/cmaps/haline.txt +0 -0
  66. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/cmaps/hawaii.txt +0 -0
  67. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/cmaps/lipari.txt +0 -0
  68. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/cmaps/oslo.txt +0 -0
  69. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/cmaps/roma.txt +0 -0
  70. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/cmaps/romaO.txt +0 -0
  71. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/cmaps/thermal.txt +0 -0
  72. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/cmaps/vik.txt +0 -0
  73. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/dark.mplstyle +0 -0
  74. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/light.mplstyle +0 -0
  75. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/palettes/LICENCES.md +0 -0
  76. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/palettes/dark2.txt +0 -0
  77. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/palettes/ibm.txt +0 -0
  78. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/palettes/okabe.txt +0 -0
  79. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/palettes/paired.txt +0 -0
  80. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/palettes/petroff10.txt +0 -0
  81. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/palettes/petroff6.txt +0 -0
  82. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/palettes/petroff8.txt +0 -0
  83. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/palettes/set1.txt +0 -0
  84. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/palettes/set2.txt +0 -0
  85. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/palettes/tab10.txt +0 -0
  86. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/palettes/tab20.txt +0 -0
  87. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/palettes/tableaucb.txt +0 -0
  88. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/palettes/tolbright.txt +0 -0
  89. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/palettes/tolhc.txt +0 -0
  90. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/palettes/tollight.txt +0 -0
  91. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/palettes/tolmc.txt +0 -0
  92. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/palettes/tolvibrant.txt +0 -0
  93. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/paper.mplstyle +0 -0
  94. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/poster.mplstyle +0 -0
  95. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/science.mplstyle +0 -0
  96. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/talk.mplstyle +0 -0
  97. {kx_plot-0.5.0 → kx_plot-0.6.0}/kx/styles/thesis.mplstyle +0 -0
  98. {kx_plot-0.5.0 → kx_plot-0.6.0}/tests/conftest.py +0 -0
@@ -6,6 +6,61 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.6.0] - 2026-11-04
10
+
11
+ ### Added
12
+
13
+ - `kx.plot` can draw a plot made of several panels (such as `pair`), returned as a flat array of axes in the place
14
+ of `ax=`, or a polar plot (such as `radar`), swapping a given `ax` for polar axes in the same cell.
15
+ - Statistics for the significance, association and clustering plots, in numpy without scipy and checked against
16
+ it: Kruskal-Wallis and pairwise Mann-Whitney tests, Holm-adjusted p-values, Cramér's V and hierarchical linkage.
17
+ - **Datasets** `embedding` (a 2-D embedding in 5 clusters, with the 10 features behind it) and `shapes` (210 small
18
+ images in 7 classes, some with artifacts, with masks, a model's predictions and saliency maps).
19
+ - `kx.load` reads a `.npz` dataset as a dict of arrays: `kx.load('shapes')['images']`.
20
+ - Image input for the image plots: an array of images (channels last or first), or a list of arrays, PIL images
21
+ or file paths, scaled to 0..1 whatever the dtype.
22
+ - **Plot kinds** `pie` and `donut`: shares of a whole, counting the categories of x or summing y per category.
23
+ `ann` writes the percent in each slice, `sort` puts the largest first, and past `top=` (7) slices the rest fold
24
+ into `other`. `donut` shows the total in its hole.
25
+ - **Plot kind** `radar`: one polygon per row of a table, or per group mean with `by=`, each column scaled to 0..1
26
+ with its range under its name; `raw` keeps the values.
27
+ - **Plot kind** `parallel`: parallel coordinates, one line per row, each axis scaled with its real min and max at
28
+ the ends. `by=` colours the lines by group and `mean` adds each group's mean.
29
+ - **Plot kind** `pair`: a scatter matrix of the numeric columns, coloured by `by=`, with a KDE per group on the
30
+ diagonal and shared axes. `cols=` picks the columns (at most 8).
31
+ - **Plot kind** `cluster`: `heat` with similar rows and columns side by side and dendrograms showing how they
32
+ group; `cluster-corr` groups correlated features. `method=` picks the linkage.
33
+ - **Plot kind** `mosaic`: two or three categoricals as tiles sized by their counts, `kx.plot(df, 'port', 'sex',
34
+ 'survived', spec='mosaic')`. `ann` writes the counts.
35
+ - **Plot kinds** `treemap` and `sunburst`: a hierarchy of up to three categoricals sized by count, as nested
36
+ rectangles or as rings, `kx.plot(df, 'pclass', 'sex', spec='treemap')`. `ann` labels the tiles with room.
37
+ - **Flag** `facet`: the plot once per value of `facet=`, `kx.plot(df, 'pclass', 'port', 'crosstab-facet',
38
+ facet='sex')`, with every category in each panel, shared axes and one colour scale.
39
+ - **Flag** `sig` (`box`, `violin`): the Kruskal-Wallis p over the groups and, up to 6 groups, stars over each pair
40
+ that differs (Mann-Whitney, Holm-corrected); with `ann` the p-values instead.
41
+ - **Plot kind** `imgrid`: sample images, `kx.plot(images, labels, 'imgrid')`, one row of `n=` random images per
42
+ class (`seed=` repeats them), or the images at `idx=`. Only the images shown are read.
43
+ - **Plot kind** `meanimg`: the mean image of each class, `kx.plot(images, labels, 'meanimg')`, sizes matched to
44
+ the most common one; `std` shows how much each pixel varies instead, on one colour scale.
45
+ - **Plot kind** `colorhist`: each class's average histogram per colour channel, one line per class
46
+ (`kx.plot(images, labels, 'colorhist')`); `hsv` for hue, saturation and value, `map` for heat maps.
47
+ - **Plot kind** `imhist`: images beside their channel histograms, one row each, `kx.plot(images, 'imhist',
48
+ idx=[0, 1])` or `n=` random ones; `hsv` for hue, saturation and value.
49
+ - **Plot kind** `segmask`: images with their segmentation masks, `kx.plot(images, masks, 'segmask')`: the image,
50
+ the mask and an outline over the image; predicted masks as z add a second outline and the IoU.
51
+ - **Plot kind** `saliency`: saliency maps (Grad-CAM or any, computed elsewhere) over their images,
52
+ `kx.plot(images, maps, 'saliency')`, each scaled to 0..1 and smoothed up to its image; z adds a caption.
53
+ - **Plot kind** `miscls`: the images a model got wrong, `kx.plot(images, y_true, y_pred, 'miscls')`, captioned
54
+ 'true -> predicted'; with a 2-D score as z, the most confident mistakes first.
55
+ - **Plot kind** `embed`: a 2-D embedding coloured by label, `kx.plot(xy, labels, 'embed')`, with no ticks and
56
+ equal aspect; `ann` names each group where it sits.
57
+ - `kx.embed(df, by='label')`: PCA (or `method='tsne'`, `'umap'` with the new `embed` extra) of a table or images,
58
+ then the `embed` plot; the coordinates are `ax.embedding`.
59
+ - `kx.cramers(df)`: Cramér's V between every pair of categorical columns as a heat map, `cluster=True` to group
60
+ them, `plot=False` for the matrix.
61
+ - `heat` takes `fmt=` for its `ann` numbers.
62
+ - Table kinds that group (`radar`, `parallel`, `pair`) take `by=` as a column name, left out of the columns drawn.
63
+
9
64
  ## [0.5.0] - 2026-10-24
10
65
 
11
66
  ### Added
@@ -270,7 +325,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
270
325
  - `kx.use`, `kx.show`, `kx.source`, `kx.grammar`, `kx.load` and the demo CSVs
271
326
  - a workflow that publishes the dataset to Kaggle
272
327
 
273
- [Unreleased]: https://github.com/vhrabar/kx-plot/compare/v0.5.0...HEAD
328
+ [Unreleased]: https://github.com/vhrabar/kx-plot/compare/v0.6.0...HEAD
329
+ [0.6.0]: https://github.com/vhrabar/kx-plot/compare/v0.5.0...v0.6.0
274
330
  [0.5.0]: https://github.com/vhrabar/kx-plot/compare/v0.4.0...v0.5.0
275
331
  [0.4.0]: https://github.com/vhrabar/kx-plot/compare/v0.3.0...v0.4.0
276
332
  [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.5.0
3
+ Version: 0.6.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
@@ -83,13 +89,15 @@ kx.plot(df.value, spec='box', by=df.group) # one box per group (also rid
83
89
  | Token | Values |
84
90
  |-------|-----------------------------------------------------------------------------------------------|
85
91
  | kind | `line` `step` `area` `band` `scatter` `bar` `barh` `hist` `kde` `ridge` `ecdf` `box` `violin` |
86
- | | `strip` `qq` `count` `crosstab` `hexbin` `heat` `missing` `nullmap` |
92
+ | | `strip` `qq` `count` `crosstab` `hexbin` `heat` `missing` `nullmap` `pie` `donut` `radar` |
93
+ | | `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` |
95
+ | | `lcurve` `vcurve` `elbow` `embed` |
96
+ | | Images: `imgrid` `meanimg` `colorhist` `imhist` `segmask` `saliency` `miscls` |
89
97
  | theme | `dark` `light` `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` `sort` `ann` `mean` `median` `nocb` `sym` |
92
- | | `logc` `corr` `all` `diag` `fit` `best` |
99
+ | | `si` `facet`; per kind: `stack` `norm` `cum` `date` `mk` `sort` `ann` `mean` `median` `nocb` |
100
+ | | `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,12 @@ 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
+ `facet` draws a plot once per value of a column, `kx.plot(df, 'pclass', 'port', 'crosstab-facet', facet='sex')`,
112
+ with every category in every panel, shared axes, and one colour scale and colorbar for the colour kinds.
113
+
100
114
  Unknown tokens raise an error instead of being guessed, with the closest valid tokens as a hint.
101
115
  Everything is inspectable: `kx.grammar()`, `kx.grammar('area')`, `kx.parse('leg-scatter')`, `kx.show('dark')`,
102
116
  `kx.source('scatter')`.
@@ -110,13 +124,53 @@ kx.missing(df) # share of NaNs per column, t
110
124
  kx.plot(df, 'nullmap-sort') # where the NaNs are: one pixel row per table row
111
125
  kx.plot(df, 'heat-corr-ann') # correlations of the numeric columns, -1 to 1
112
126
  kx.plot(df, 'heat') # any numeric DataFrame or 2-D array as coloured cells
127
+ kx.cramers(df, cluster=True) # Cramér's V of the categorical columns, 0 to 1
128
+ kx.plot(df, 'cluster-corr') # correlations, similar columns side by side, with trees
113
129
  kx.plot(df, 'pclass', spec='count', by='survived') # rows per category, split by a second column
114
130
  kx.plot(df, 'pclass', 'port', 'crosstab-norm-ann') # how often each pair of categories occurs
131
+ kx.plot(df, 'port', 'sex', 'survived', spec='mosaic-ann') # tiles sized by count, up to 3 categoricals
132
+ kx.plot(df, 'pclass', 'sex', spec='treemap-ann') # a hierarchy of categories; 'sunburst' as rings
115
133
  kx.plot(df, 'age', 'fare', 'hexbin-logc') # points per hexagon; with a z, its mean per hexagon
134
+ kx.plot(df, 'port', 'donut-ann') # shares of a whole, the total in the hole
135
+ kx.plot(df[['age', 'fare', 'pclass', 'survived']], 'radar', by='survived') # each group's profile
136
+ kx.plot(df[['age', 'fare', 'pclass', 'sex']], 'parallel-mean', by='sex') # every row across columns
137
+ kx.plot(df, 'pair', by='sex') # every numeric column against every other
138
+ ```
139
+
140
+ `heat`, `cluster`, `missing`, `nullmap`, `radar`, `parallel` and `pair` take the whole table and no column names
141
+ (`radar`, `parallel` and `pair` take `by=`, a column of groups); `kx.plot(df[cols], 'heat')` for some columns.
142
+ `wrap` breaks long tick labels onto several lines.
143
+
144
+ ![kinds with several panels](https://raw.githubusercontent.com/vhrabar/kx-plot/main/previews/dark-panels.png)
145
+
146
+ ### Images
147
+
148
+ Image kinds take an `(N, H, W)` or `(N, H, W, C)` array (channels first works too), or a list of arrays, PIL images
149
+ or file paths, with the labels as `y`. `kx.load('shapes')` is a small demo set.
150
+
151
+ ```python
152
+ d = kx.load('shapes')
153
+ kx.plot(d['images'], d['labels'], 'imgrid') # 6 random images per class, one row each
154
+ kx.plot(paths, labels, 'imgrid', idx=[3, 17, 42]) # chosen images, titled with their labels
155
+ kx.plot(d['images'], d['labels'], 'meanimg') # the mean image of each class; -std: where pixels vary
156
+ kx.plot(d['images'], d['labels'], 'colorhist') # pixel values per channel and class; -hsv, -map
157
+ kx.plot(d['images'], 'imhist', idx=[0, 1]) # images beside their own channel histograms
158
+ kx.plot(d['images'], d['masks'], pred, 'segmask') # image, mask, outlines; a prediction adds its IoU
159
+ kx.plot(d['images'], d['saliency'], 'saliency') # Grad-CAM or any map over its image, smoothed to fit
160
+ kx.plot(d['images'], d['labels'], d['proba'], 'miscls') # the mistakes, the most confident first
161
+ ```
162
+
163
+ ![image kinds](https://raw.githubusercontent.com/vhrabar/kx-plot/main/previews/dark-img.png)
164
+
165
+ ### Embeddings
166
+
167
+ ```python
168
+ kx.embed(df, by='label') # PCA of the numeric columns, explained variance on the axes
169
+ kx.embed(images, by=labels, method='tsne') # t-SNE or UMAP: pip install 'kx-plot[embed]'
170
+ kx.plot(xy, labels, 'embed-ann') # coordinates you already have, names at each group
116
171
  ```
117
172
 
118
- `heat`, `missing` and `nullmap` take the whole table and no column names; `kx.plot(df[cols], 'heat')` for some
119
- columns. `wrap` breaks long tick labels onto several lines.
173
+ `kx.embed` returns the axes, and the coordinates are `ax.embedding`.
120
174
 
121
175
  ### Machine learning
122
176
 
@@ -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
@@ -45,13 +48,15 @@ kx.plot(df.value, spec='box', by=df.group) # one box per group (also rid
45
48
  | Token | Values |
46
49
  |-------|-----------------------------------------------------------------------------------------------|
47
50
  | kind | `line` `step` `area` `band` `scatter` `bar` `barh` `hist` `kde` `ridge` `ecdf` `box` `violin` |
48
- | | `strip` `qq` `count` `crosstab` `hexbin` `heat` `missing` `nullmap` |
51
+ | | `strip` `qq` `count` `crosstab` `hexbin` `heat` `missing` `nullmap` `pie` `donut` `radar` |
52
+ | | `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` |
54
+ | | `lcurve` `vcurve` `elbow` `embed` |
55
+ | | Images: `imgrid` `meanimg` `colorhist` `imhist` `segmask` `saliency` `miscls` |
51
56
  | theme | `dark` `light` `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` `sort` `ann` `mean` `median` `nocb` `sym` |
54
- | | `logc` `corr` `all` `diag` `fit` `best` |
58
+ | | `si` `facet`; per kind: `stack` `norm` `cum` `date` `mk` `sort` `ann` `mean` `median` `nocb` |
59
+ | | `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,12 @@ 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
+ `facet` draws a plot once per value of a column, `kx.plot(df, 'pclass', 'port', 'crosstab-facet', facet='sex')`,
71
+ with every category in every panel, shared axes, and one colour scale and colorbar for the colour kinds.
72
+
62
73
  Unknown tokens raise an error instead of being guessed, with the closest valid tokens as a hint.
63
74
  Everything is inspectable: `kx.grammar()`, `kx.grammar('area')`, `kx.parse('leg-scatter')`, `kx.show('dark')`,
64
75
  `kx.source('scatter')`.
@@ -72,13 +83,53 @@ kx.missing(df) # share of NaNs per column, t
72
83
  kx.plot(df, 'nullmap-sort') # where the NaNs are: one pixel row per table row
73
84
  kx.plot(df, 'heat-corr-ann') # correlations of the numeric columns, -1 to 1
74
85
  kx.plot(df, 'heat') # any numeric DataFrame or 2-D array as coloured cells
86
+ kx.cramers(df, cluster=True) # Cramér's V of the categorical columns, 0 to 1
87
+ kx.plot(df, 'cluster-corr') # correlations, similar columns side by side, with trees
75
88
  kx.plot(df, 'pclass', spec='count', by='survived') # rows per category, split by a second column
76
89
  kx.plot(df, 'pclass', 'port', 'crosstab-norm-ann') # how often each pair of categories occurs
90
+ kx.plot(df, 'port', 'sex', 'survived', spec='mosaic-ann') # tiles sized by count, up to 3 categoricals
91
+ kx.plot(df, 'pclass', 'sex', spec='treemap-ann') # a hierarchy of categories; 'sunburst' as rings
77
92
  kx.plot(df, 'age', 'fare', 'hexbin-logc') # points per hexagon; with a z, its mean per hexagon
93
+ kx.plot(df, 'port', 'donut-ann') # shares of a whole, the total in the hole
94
+ kx.plot(df[['age', 'fare', 'pclass', 'survived']], 'radar', by='survived') # each group's profile
95
+ kx.plot(df[['age', 'fare', 'pclass', 'sex']], 'parallel-mean', by='sex') # every row across columns
96
+ kx.plot(df, 'pair', by='sex') # every numeric column against every other
97
+ ```
98
+
99
+ `heat`, `cluster`, `missing`, `nullmap`, `radar`, `parallel` and `pair` take the whole table and no column names
100
+ (`radar`, `parallel` and `pair` take `by=`, a column of groups); `kx.plot(df[cols], 'heat')` for some columns.
101
+ `wrap` breaks long tick labels onto several lines.
102
+
103
+ ![kinds with several panels](https://raw.githubusercontent.com/vhrabar/kx-plot/main/previews/dark-panels.png)
104
+
105
+ ### Images
106
+
107
+ Image kinds take an `(N, H, W)` or `(N, H, W, C)` array (channels first works too), or a list of arrays, PIL images
108
+ or file paths, with the labels as `y`. `kx.load('shapes')` is a small demo set.
109
+
110
+ ```python
111
+ d = kx.load('shapes')
112
+ kx.plot(d['images'], d['labels'], 'imgrid') # 6 random images per class, one row each
113
+ kx.plot(paths, labels, 'imgrid', idx=[3, 17, 42]) # chosen images, titled with their labels
114
+ kx.plot(d['images'], d['labels'], 'meanimg') # the mean image of each class; -std: where pixels vary
115
+ kx.plot(d['images'], d['labels'], 'colorhist') # pixel values per channel and class; -hsv, -map
116
+ kx.plot(d['images'], 'imhist', idx=[0, 1]) # images beside their own channel histograms
117
+ kx.plot(d['images'], d['masks'], pred, 'segmask') # image, mask, outlines; a prediction adds its IoU
118
+ kx.plot(d['images'], d['saliency'], 'saliency') # Grad-CAM or any map over its image, smoothed to fit
119
+ kx.plot(d['images'], d['labels'], d['proba'], 'miscls') # the mistakes, the most confident first
120
+ ```
121
+
122
+ ![image kinds](https://raw.githubusercontent.com/vhrabar/kx-plot/main/previews/dark-img.png)
123
+
124
+ ### Embeddings
125
+
126
+ ```python
127
+ kx.embed(df, by='label') # PCA of the numeric columns, explained variance on the axes
128
+ kx.embed(images, by=labels, method='tsne') # t-SNE or UMAP: pip install 'kx-plot[embed]'
129
+ kx.plot(xy, labels, 'embed-ann') # coordinates you already have, names at each group
78
130
  ```
79
131
 
80
- `heat`, `missing` and `nullmap` take the whole table and no column names; `kx.plot(df[cols], 'heat')` for some
81
- columns. `wrap` breaks long tick labels onto several lines.
132
+ `kx.embed` returns the axes, and the coordinates are `ax.embedding`.
82
133
 
83
134
  ### Machine learning
84
135
 
@@ -3,30 +3,42 @@ kx: tiny matplotlib helper.
3
3
 
4
4
  Token grammar for kx.plot(spec): kind-theme-flag-flag-...
5
5
  kind : line | step | area | band | scatter | bar | barh | hist | kde | ridge | ecdf | box | violin | strip
6
- | qq | heat | crosstab | count | missing | nullmap | hexbin
6
+ | qq | heat | crosstab | count | missing | nullmap | hexbin | pie | donut | radar | parallel | pair
7
+ | 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
12
+ flags : grid | leg | legout | tight | rot | wrap | logx | logy | logxy | symlogy | zero | eq | pct | si | facet
11
13
  and per kind: stack norm cum (bars, area, hist), date mk (lines), sort ann (bars, count),
12
14
  stack norm (count),
13
- mean median ann (distributions), nocb sym logc (scatter, heat, hexbin), corr ann (heat),
15
+ mean median ann (distributions), sig (box, violin),
16
+ nocb sym logc (scatter, heat, hexbin, cluster), corr ann (heat, cluster),
14
17
  norm ann nocb logc (crosstab), ann all (missing), sort (nullmap), diag (scatter, hexbin),
15
18
  fit (scatter), norm ann nocb (cm), norm (proba), best (thresh, loss, elbow),
16
- nocb sym logc (resid).
19
+ nocb sym logc (resid), ann sort (pie, donut), ann (mosaic, treemap, sunburst), raw (radar), mean (parallel),
20
+ std (meanimg), hsv map (colorhist), hsv (imhist), ann nocb sym logc (embed).
17
21
  kx.grammar(kind) lists them.
18
- by= : group labels for x, one series per group (kde, ridge, ecdf, box, violin, strip, qq, count)
19
- table : heat, missing, nullmap and loss take a whole DataFrame or 2-D array, with no column names:
22
+ by= : group labels for x, one series per group (kde, ridge, ecdf, box, violin, strip, qq, count);
23
+ for radar, parallel and pair a column of the table: kx.plot(df, 'radar', by='class')
24
+ images : image kinds take an (N, H, W[, C]) array or a list of arrays or file paths, labels as y:
25
+ kx.plot(images, labels, 'imgrid')
26
+ facet= : with the flag facet, one panel per value of a column, on shared axes and one colour scale:
27
+ kx.plot(df, 'pclass', 'port', 'crosstab-facet', facet='sex')
28
+ table : heat, cluster, missing, nullmap, loss, radar, parallel, pair take a whole DataFrame or 2-D array:
20
29
  kx.plot(df, 'heat-corr'); a dict or a Keras History works too: kx.plot(model.fit(...), 'loss')
21
30
 
22
31
  Palettes (kx.use(theme, palette="okabe")): any file name in styles/palettes/
23
32
  Colormaps (kx.use(theme, cmap="magma")): kx.cmaps()
24
33
  with kx.context(theme, ...): the same as kx.use, for one block only.
25
34
  kx.save("fig.png"): saves to /kaggle/working on Kaggle, the current folder elsewhere.
35
+ kx.load("passengers"): a demo table; kx.load("shapes"): a dict of image arrays. kx.datasets() lists them.
26
36
  kx.missing(df): the share of missing values per column, the same as kx.plot(df, 'missing-ann').
27
37
  kx.grid(5): a figure of 5 panels as a flat array of axes, for kx.plot(..., ax=).
28
38
  kx.roc_auc(y_true, score) and kx.pr_ap(y_true, score): area under the ROC curve and average precision, in numpy.
29
39
  kx.evaluate(y_true, score): a model report, the panels picked from the data (binary, multiclass or regression).
40
+ kx.embed(df, by='label'): the rows in 2-D (PCA; method='tsne' or 'umap' with pip install 'kx-plot[embed]').
41
+ kx.cramers(df): how strongly each pair of categorical columns goes together (Cramér's V), as a heat map.
30
42
  kx.grammar("area") and kx.source("area") explain one kind; kx.parse(spec) shows how a spec is read.
31
43
  """
32
44
  import glob
@@ -39,7 +51,9 @@ from typing import Any
39
51
  import pandas as pd
40
52
  from matplotlib.axes import Axes
41
53
 
54
+ from ._cramers import cramers
42
55
  from ._data import datasets, load
56
+ from ._embed import embed
43
57
  from ._evaluate import evaluate
44
58
  from ._grid import grid
45
59
  from ._metrics import pr_ap, roc_auc
@@ -48,9 +62,9 @@ from ._save import save
48
62
  from ._spec import COMMON_FLAGS, KINDS, Spec, all_flags, parse
49
63
  from ._theme import BREWER_CMAPS, BUILTIN_CMAPS, VENDORED_CMAPS, cmaps, context, palette, palettes, show, styles, use
50
64
 
51
- __all__ = ["BREWER_CMAPS", "BUILTIN_CMAPS", "VENDORED_CMAPS", "Spec", "__version__", "cmaps", "context", "datasets",
52
- "evaluate", "grammar", "grid", "load", "missing", "palette", "palettes", "parse", "plot", "pr_ap", "roc_auc",
53
- "save", "show", "source", "styles", "use"]
65
+ __all__ = ["BREWER_CMAPS", "BUILTIN_CMAPS", "VENDORED_CMAPS", "Spec", "__version__", "cmaps", "context", "cramers",
66
+ "datasets", "embed", "evaluate", "grammar", "grid", "load", "missing", "palette", "palettes", "parse",
67
+ "plot", "pr_ap", "roc_auc", "save", "show", "source", "styles", "use"]
54
68
 
55
69
 
56
70
  def _version() -> str:
@@ -88,6 +102,10 @@ def grammar(kind: str | None = None) -> None:
88
102
  print("data : takes a DataFrame or 2-D array")
89
103
  if k.takes_by:
90
104
  print("by= : group labels for x, one per group")
105
+ if k.panels:
106
+ print("axes : draws several panels; kx.plot returns them as a flat array")
107
+ if k.projection:
108
+ print(f"axes : {k.projection}; kx.plot swaps a given ax for {k.projection} axes in its place")
91
109
  return
92
110
  print("kind :", sorted(KINDS))
93
111
  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"]