kx-plot 0.1.0__tar.gz → 0.2.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 (63) hide show
  1. {kx_plot-0.1.0 → kx_plot-0.2.0}/CHANGELOG.md +26 -1
  2. {kx_plot-0.1.0 → kx_plot-0.2.0}/PKG-INFO +29 -11
  3. {kx_plot-0.1.0 → kx_plot-0.2.0}/README.md +27 -10
  4. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/__init__.py +9 -5
  5. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/_plot.py +11 -3
  6. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/_spec.py +3 -2
  7. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/_theme.py +28 -6
  8. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/kinds/basic.py +19 -7
  9. kx_plot-0.2.0/kx/kinds/dist.py +151 -0
  10. kx_plot-0.2.0/kx/styles/cmaps/LICENCES.md +57 -0
  11. kx_plot-0.2.0/kx/styles/cmaps/balance.txt +257 -0
  12. kx_plot-0.2.0/kx/styles/cmaps/bam.txt +257 -0
  13. kx_plot-0.2.0/kx/styles/cmaps/batlow.txt +257 -0
  14. kx_plot-0.2.0/kx/styles/cmaps/cork.txt +257 -0
  15. kx_plot-0.2.0/kx/styles/cmaps/davos.txt +257 -0
  16. kx_plot-0.2.0/kx/styles/cmaps/deep.txt +257 -0
  17. kx_plot-0.2.0/kx/styles/cmaps/haline.txt +257 -0
  18. kx_plot-0.2.0/kx/styles/cmaps/hawaii.txt +257 -0
  19. kx_plot-0.2.0/kx/styles/cmaps/lipari.txt +257 -0
  20. kx_plot-0.2.0/kx/styles/cmaps/oslo.txt +257 -0
  21. kx_plot-0.2.0/kx/styles/cmaps/roma.txt +257 -0
  22. kx_plot-0.2.0/kx/styles/cmaps/romaO.txt +257 -0
  23. kx_plot-0.2.0/kx/styles/cmaps/thermal.txt +257 -0
  24. kx_plot-0.2.0/kx/styles/cmaps/vik.txt +257 -0
  25. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/styles/palettes/LICENCES.md +1 -1
  26. kx_plot-0.2.0/kx/styles/palettes/paired.txt +14 -0
  27. kx_plot-0.2.0/kx/styles/palettes/set1.txt +11 -0
  28. kx_plot-0.2.0/kx/styles/palettes/tab20.txt +22 -0
  29. kx_plot-0.2.0/kx/styles/palettes/tollight.txt +11 -0
  30. {kx_plot-0.1.0 → kx_plot-0.2.0}/pyproject.toml +2 -2
  31. {kx_plot-0.1.0 → kx_plot-0.2.0}/tests/test_kx.py +174 -2
  32. kx_plot-0.1.0/kx/kinds/dist.py +0 -14
  33. {kx_plot-0.1.0 → kx_plot-0.2.0}/.gitignore +0 -0
  34. {kx_plot-0.1.0 → kx_plot-0.2.0}/LICENSE +0 -0
  35. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/_data.py +0 -0
  36. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/_files.py +0 -0
  37. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/_util.py +0 -0
  38. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/data/cloud.csv +0 -0
  39. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/data/dists.csv +0 -0
  40. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/data/monthly.csv +0 -0
  41. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/data/waves.csv +0 -0
  42. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/kinds/__init__.py +0 -0
  43. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/styles/dark.mplstyle +0 -0
  44. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/styles/light.mplstyle +0 -0
  45. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/styles/palettes/dark2.txt +0 -0
  46. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/styles/palettes/ibm.txt +0 -0
  47. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/styles/palettes/okabe.txt +0 -0
  48. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/styles/palettes/petroff10.txt +0 -0
  49. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/styles/palettes/petroff6.txt +0 -0
  50. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/styles/palettes/petroff8.txt +0 -0
  51. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/styles/palettes/set2.txt +0 -0
  52. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/styles/palettes/tab10.txt +0 -0
  53. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/styles/palettes/tableaucb.txt +0 -0
  54. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/styles/palettes/tolbright.txt +0 -0
  55. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/styles/palettes/tolhc.txt +0 -0
  56. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/styles/palettes/tolmc.txt +0 -0
  57. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/styles/palettes/tolvibrant.txt +0 -0
  58. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/styles/paper.mplstyle +0 -0
  59. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/styles/poster.mplstyle +0 -0
  60. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/styles/science.mplstyle +0 -0
  61. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/styles/talk.mplstyle +0 -0
  62. {kx_plot-0.1.0 → kx_plot-0.2.0}/kx/styles/thesis.mplstyle +0 -0
  63. {kx_plot-0.1.0 → kx_plot-0.2.0}/tests/conftest.py +0 -0
@@ -6,6 +6,30 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.2.0] - 2026-10-09
10
+
11
+ ### Added
12
+
13
+ - **Plot kinds**
14
+ - `barh`: horizontal bars, first category on top. `y` and `z` are grouped like `bar`.
15
+ - `kde`: smooth density curves (Gaussian KDE in numpy, no scipy needed), one per array.
16
+ - `ecdf`: empirical CDF, the share of values at or below each x, one step curve per array.
17
+ - `box`: box plots side by side (median, quartiles, 1.5 IQR whiskers, outliers), one per array.
18
+ - `violin`: violin plots side by side with the median and quartiles marked, one per array.
19
+ - **Flags**
20
+ - `stack` now works with `bar` and `barh`: `z` is drawn on top of `y`, so the bar's end is the total.
21
+ - `stack`, `norm` (density) and the new `cum` (cumulative) work with `hist`.
22
+ - `kx.plot(..., by=groups)` splits `x` into one curve, box or violin per group (for `kde`, `ecdf`, `box`, `violin`).
23
+ - cmocean colourmaps `thermal`, `haline`, `deep` and `balance` for `kx.use(cmap=...)`.
24
+ - Crameri colourmaps (Scientific colour maps 8) `batlow`, `lipari`, `hawaii`, `oslo`, `davos`, `vik`, `roma`,
25
+ `bam`, `cork` and cyclic `romaO`, vendored the same way.
26
+ - `kx.use(cmap="<name>_r")` reverses any colourmap in `kx.cmaps()`.
27
+ - Palettes `tollight` (Paul Tol), `set1` and `paired` (ColorBrewer) and `tab20` (Tableau, 20 categories).
28
+
29
+ ### Changed
30
+
31
+ - `hist` puts every series on the same bins, so overlaid bars line up.
32
+
9
33
  ## [0.1.0] - 2026-10-08
10
34
 
11
35
  ### Added
@@ -78,7 +102,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
78
102
  - `kx.use`, `kx.show`, `kx.source`, `kx.grammar`, `kx.load` and the demo CSVs
79
103
  - a workflow that publishes the dataset to Kaggle
80
104
 
81
- [Unreleased]: https://github.com/vhrabar/kx-plot/compare/v0.1.0...HEAD
105
+ [Unreleased]: https://github.com/vhrabar/kx-plot/compare/v0.2.0...HEAD
106
+ [0.2.0]: https://github.com/vhrabar/kx-plot/compare/v0.1.0...v0.2.0
82
107
  [0.1.0]: https://github.com/vhrabar/kx-plot/compare/v0.0.2...v0.1.0
83
108
  [0.0.2]: https://github.com/vhrabar/kx-plot/compare/v0.0.1...v0.0.2
84
109
  [0.0.1]: https://github.com/vhrabar/kx-plot/releases/tag/v0.0.1
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: kx-plot
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: One-line matplotlib plots and themes for notebook 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
@@ -9,6 +9,7 @@ Project-URL: Kaggle, https://www.kaggle.com/datasets/vhrabar/kx-plot
9
9
  Author-email: Vedran Hrabar <vedran.hrabar@outlook.com>
10
10
  License-Expression: MIT
11
11
  License-File: LICENSE
12
+ License-File: kx/styles/cmaps/LICENCES.md
12
13
  License-File: kx/styles/palettes/LICENCES.md
13
14
  Keywords: jupyter,kaggle,matplotlib,plotting,themes,visualization
14
15
  Classifier: Development Status :: 3 - Alpha
@@ -46,7 +47,7 @@ import kx; kx.use('dark')
46
47
 
47
48
  ### Kaggle
48
49
 
49
- With internet off (competition notebooks), attach the dataset instead (**Add Input → Datasets → `vhrabar/kx-plot`**), then:
50
+ Attach the dataset instead (**Add Input → Datasets → `vhrabar/kx-plot`**), then:
50
51
 
51
52
  ```python
52
53
  import sys; sys.path.append('/kaggle/input/datasets/vhrabar/kx-plot')
@@ -59,19 +60,28 @@ import kx; kx.use('dark')
59
60
  kx.use('light', palette='okabe', cmap='cividis') # notebook default: theme, palette, colormap
60
61
  kx.plot(x, y, z, 'scatter-grid-leg') # spec: kind-theme-flag-...
61
62
  kx.plot(x, y, 'bar-paper') # a theme in the spec applies to this plot only
63
+ kx.plot(df.value, spec='kde', by=df.group) # one density curve per group
64
+ kx.plot(df.value, spec='box', by=df.group) # one box per group (also ecdf, violin)
62
65
  ```
63
66
 
64
- | Token | Values |
65
- |-------|--------------------------------------------------------------------|
66
- | kind | `line` `step` `area` `band` `scatter` `bar` `hist` |
67
- | theme | `dark` `light` `paper` `science` `talk` `poster` `thesis` |
68
- | flags | `grid` `leg` `logx` `logy` `tight`, plus `stack` `norm` for `area` |
67
+ | Token | Values |
68
+ |-------|---------------------------------------------------------------------------------------|
69
+ | kind | `line` `step` `area` `band` `scatter` `bar` `barh` `hist` `kde` `ecdf` `box` `violin` |
70
+ | theme | `dark` `light` `paper` `science` `talk` `poster` `thesis` |
71
+ | flags | `grid` `leg` `logx` `logy` `tight`, plus `stack` `norm` `cum` (below) |
72
+
73
+ `stack` works with `area`, `bar`, `barh` and `hist`. `norm` is a 100% stack for `area` and a
74
+ density (area 1) for `hist`. `cum` makes `hist` cumulative; `hist-norm-cum` is the CDF.
75
+ `hist` puts every series on the same bins, so the bars line up.
69
76
 
70
77
  Unknown tokens raise an error instead of being guessed. Everything is inspectable:
71
78
  `kx.grammar()`, `kx.grammar('area')`, `kx.show('dark')`, `kx.source('scatter')`.
72
79
 
73
80
  rcParams can be overridden in `kx.use` with `__` for dots: `kx.use('dark', figure__figsize=(8, 4))`.
74
81
 
82
+ Every kind, option, flag and config, with its output, is in the
83
+ [Example Usage notebook](https://github.com/vhrabar/kx-plot/blob/main/Example%20Usage.ipynb).
84
+
75
85
  ## Palettes
76
86
 
77
87
  Palettes for `kx.use(theme, palette=...)`, they swap only the colours; a theme's
@@ -80,10 +90,11 @@ other cycled properties (such as `paper`'s linestyles) stay.
80
90
  | Name | Source |
81
91
  |------------------------------------------|--------------------|
82
92
  | `okabe` | Okabe & Ito (2008) |
83
- | `tolbright` `tolvibrant` `tolhc` `tolmc` | Paul Tol |
93
+ | `tolbright` `tolvibrant` `tollight` | Paul Tol |
94
+ | `tolhc` `tolmc` | Paul Tol |
84
95
  | `petroff6` `petroff8` `petroff10` | Petroff (2021) |
85
- | `tab10` `tableaucb` | Tableau |
86
- | `set2` `dark2` | ColorBrewer |
96
+ | `tab10` `tab20` `tableaucb` | Tableau |
97
+ | `set1` `set2` `dark2` `paired` | ColorBrewer |
87
98
  | `ibm` | IBM Design Colors |
88
99
 
89
100
  `kx.palette('okabe')` returns the hex codes. A list of colours works too: `palette=['#264653', '#e9c46a']`.
@@ -92,6 +103,7 @@ other cycled properties (such as `paper`'s linestyles) stay.
92
103
 
93
104
  Colourmaps for `kx.use(theme, cmap=...)` colour continuous values, such as a numeric `z` in `scatter`.
94
105
  Without `cmap`, the theme's own default applies.
106
+ Add `_r` to any name to reverse it, e.g. `cmap="thermal_r"`.
95
107
 
96
108
  | Name | Type |
97
109
  |------------------------------------------------|----------------------------------|
@@ -100,6 +112,11 @@ Without `cmap`, the theme's own default applies.
100
112
  | `coolwarm` | Diverging |
101
113
  | `berlin` `managua` `vanimo` | Diverging, dark centre |
102
114
  | `twilight` | Cyclic, for angles and phases |
115
+ | `thermal` `haline` `deep` | Sequential, cmocean (vendored) |
116
+ | `balance` | Diverging, cmocean (vendored) |
117
+ | `batlow` `lipari` `hawaii` `oslo` `davos` | Sequential, Crameri (vendored) |
118
+ | `vik` `roma` `bam` `cork` | Diverging, Crameri (vendored) |
119
+ | `romaO` | Cyclic, Crameri (vendored) |
103
120
 
104
121
  `kx.cmaps()` lists the ones that are available in the installed matplotlib as those implemented in matplotlib 3.10 or newer
105
122
  are not vendored.
@@ -111,4 +128,5 @@ Released under the MIT License. See [`LICENSE`](https://github.com/vhrabar/kx-pl
111
128
 
112
129
  Copyright © 2026 Vedran Hrabar
113
130
 
114
- Vendored palettes keep their own licences; see [`kx/styles/palettes/LICENCES.md`](https://github.com/vhrabar/kx-plot/blob/main/kx/styles/palettes/LICENCES.md).
131
+ Vendored palettes and colourmaps keep their own licences; see [`kx/styles/palettes/LICENCES.md`](https://github.com/vhrabar/kx-plot/blob/main/kx/styles/palettes/LICENCES.md)
132
+ and [`kx/styles/cmaps/LICENCES.md`](https://github.com/vhrabar/kx-plot/blob/main/kx/styles/cmaps/LICENCES.md).
@@ -19,7 +19,7 @@ import kx; kx.use('dark')
19
19
 
20
20
  ### Kaggle
21
21
 
22
- With internet off (competition notebooks), attach the dataset instead (**Add Input → Datasets → `vhrabar/kx-plot`**), then:
22
+ Attach the dataset instead (**Add Input → Datasets → `vhrabar/kx-plot`**), then:
23
23
 
24
24
  ```python
25
25
  import sys; sys.path.append('/kaggle/input/datasets/vhrabar/kx-plot')
@@ -32,19 +32,28 @@ import kx; kx.use('dark')
32
32
  kx.use('light', palette='okabe', cmap='cividis') # notebook default: theme, palette, colormap
33
33
  kx.plot(x, y, z, 'scatter-grid-leg') # spec: kind-theme-flag-...
34
34
  kx.plot(x, y, 'bar-paper') # a theme in the spec applies to this plot only
35
+ kx.plot(df.value, spec='kde', by=df.group) # one density curve per group
36
+ kx.plot(df.value, spec='box', by=df.group) # one box per group (also ecdf, violin)
35
37
  ```
36
38
 
37
- | Token | Values |
38
- |-------|--------------------------------------------------------------------|
39
- | kind | `line` `step` `area` `band` `scatter` `bar` `hist` |
40
- | theme | `dark` `light` `paper` `science` `talk` `poster` `thesis` |
41
- | flags | `grid` `leg` `logx` `logy` `tight`, plus `stack` `norm` for `area` |
39
+ | Token | Values |
40
+ |-------|---------------------------------------------------------------------------------------|
41
+ | kind | `line` `step` `area` `band` `scatter` `bar` `barh` `hist` `kde` `ecdf` `box` `violin` |
42
+ | theme | `dark` `light` `paper` `science` `talk` `poster` `thesis` |
43
+ | flags | `grid` `leg` `logx` `logy` `tight`, plus `stack` `norm` `cum` (below) |
44
+
45
+ `stack` works with `area`, `bar`, `barh` and `hist`. `norm` is a 100% stack for `area` and a
46
+ density (area 1) for `hist`. `cum` makes `hist` cumulative; `hist-norm-cum` is the CDF.
47
+ `hist` puts every series on the same bins, so the bars line up.
42
48
 
43
49
  Unknown tokens raise an error instead of being guessed. Everything is inspectable:
44
50
  `kx.grammar()`, `kx.grammar('area')`, `kx.show('dark')`, `kx.source('scatter')`.
45
51
 
46
52
  rcParams can be overridden in `kx.use` with `__` for dots: `kx.use('dark', figure__figsize=(8, 4))`.
47
53
 
54
+ Every kind, option, flag and config, with its output, is in the
55
+ [Example Usage notebook](https://github.com/vhrabar/kx-plot/blob/main/Example%20Usage.ipynb).
56
+
48
57
  ## Palettes
49
58
 
50
59
  Palettes for `kx.use(theme, palette=...)`, they swap only the colours; a theme's
@@ -53,10 +62,11 @@ other cycled properties (such as `paper`'s linestyles) stay.
53
62
  | Name | Source |
54
63
  |------------------------------------------|--------------------|
55
64
  | `okabe` | Okabe & Ito (2008) |
56
- | `tolbright` `tolvibrant` `tolhc` `tolmc` | Paul Tol |
65
+ | `tolbright` `tolvibrant` `tollight` | Paul Tol |
66
+ | `tolhc` `tolmc` | Paul Tol |
57
67
  | `petroff6` `petroff8` `petroff10` | Petroff (2021) |
58
- | `tab10` `tableaucb` | Tableau |
59
- | `set2` `dark2` | ColorBrewer |
68
+ | `tab10` `tab20` `tableaucb` | Tableau |
69
+ | `set1` `set2` `dark2` `paired` | ColorBrewer |
60
70
  | `ibm` | IBM Design Colors |
61
71
 
62
72
  `kx.palette('okabe')` returns the hex codes. A list of colours works too: `palette=['#264653', '#e9c46a']`.
@@ -65,6 +75,7 @@ other cycled properties (such as `paper`'s linestyles) stay.
65
75
 
66
76
  Colourmaps for `kx.use(theme, cmap=...)` colour continuous values, such as a numeric `z` in `scatter`.
67
77
  Without `cmap`, the theme's own default applies.
78
+ Add `_r` to any name to reverse it, e.g. `cmap="thermal_r"`.
68
79
 
69
80
  | Name | Type |
70
81
  |------------------------------------------------|----------------------------------|
@@ -73,6 +84,11 @@ Without `cmap`, the theme's own default applies.
73
84
  | `coolwarm` | Diverging |
74
85
  | `berlin` `managua` `vanimo` | Diverging, dark centre |
75
86
  | `twilight` | Cyclic, for angles and phases |
87
+ | `thermal` `haline` `deep` | Sequential, cmocean (vendored) |
88
+ | `balance` | Diverging, cmocean (vendored) |
89
+ | `batlow` `lipari` `hawaii` `oslo` `davos` | Sequential, Crameri (vendored) |
90
+ | `vik` `roma` `bam` `cork` | Diverging, Crameri (vendored) |
91
+ | `romaO` | Cyclic, Crameri (vendored) |
76
92
 
77
93
  `kx.cmaps()` lists the ones that are available in the installed matplotlib as those implemented in matplotlib 3.10 or newer
78
94
  are not vendored.
@@ -84,4 +100,5 @@ Released under the MIT License. See [`LICENSE`](https://github.com/vhrabar/kx-pl
84
100
 
85
101
  Copyright © 2026 Vedran Hrabar
86
102
 
87
- Vendored palettes keep their own licences; see [`kx/styles/palettes/LICENCES.md`](https://github.com/vhrabar/kx-plot/blob/main/kx/styles/palettes/LICENCES.md).
103
+ Vendored palettes and colourmaps keep their own licences; see [`kx/styles/palettes/LICENCES.md`](https://github.com/vhrabar/kx-plot/blob/main/kx/styles/palettes/LICENCES.md)
104
+ and [`kx/styles/cmaps/LICENCES.md`](https://github.com/vhrabar/kx-plot/blob/main/kx/styles/cmaps/LICENCES.md).
@@ -2,9 +2,11 @@
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 | hist
5
+ kind : line | step | area | band | scatter | bar | barh | hist | kde | ecdf | box | violin
6
6
  theme : any file name in styles/
7
- flags : grid | leg | logx | logy | tight | stack | norm (stack and norm: area only)
7
+ flags : grid | leg | logx | logy | tight | stack | norm | cum
8
+ (stack: area, bar, barh, hist; norm: area, hist; cum: hist)
9
+ by= : group labels for x, one curve/box/violin per group (kde, ecdf, box, violin)
8
10
 
9
11
  Palettes (kx.use(theme, palette="okabe")): any file name in styles/palettes/
10
12
  Colormaps (kx.use(theme, cmap="magma")): kx.cmaps()
@@ -20,10 +22,10 @@ from ._data import datasets, load
20
22
  from ._plot import plot
21
23
  from ._spec import COMMON_FLAGS, KINDS, all_flags
22
24
  from ._spec import parse as _parse # noqa: F401 (tests)
23
- from ._theme import BUILTIN_CMAPS, cmaps, palette, palettes, show, styles, use
25
+ from ._theme import BUILTIN_CMAPS, VENDORED_CMAPS, cmaps, palette, palettes, show, styles, use
24
26
 
25
- __all__ = ["BUILTIN_CMAPS", "__version__", "cmaps", "datasets", "grammar", "load", "palette", "palettes", "plot",
26
- "show", "source", "styles", "use"]
27
+ __all__ = ["BUILTIN_CMAPS", "VENDORED_CMAPS", "__version__", "cmaps", "datasets", "grammar", "load", "palette",
28
+ "palettes", "plot", "show", "source", "styles", "use"]
27
29
 
28
30
 
29
31
  def _version() -> str:
@@ -57,6 +59,8 @@ def grammar(kind: str | None = None) -> None:
57
59
  k = _kind(kind)
58
60
  print(f"{k.name}: {inspect.getdoc(k.draw)}")
59
61
  print("flags:", sorted(COMMON_FLAGS), "+", sorted(k.flags) or "none of its own")
62
+ if k.takes_by:
63
+ print("by= : group labels for x, one per group")
60
64
  return
61
65
  print("kind :", sorted(KINDS))
62
66
  print("theme:", styles())
@@ -11,9 +11,13 @@ from ._theme import style_path
11
11
 
12
12
 
13
13
  def plot(x: ArrayLike, y: ArrayLike | None = None, z: ArrayLike | str | None = None,
14
- spec: str | None = None, title: str | None = None, ax: Axes | None = None) -> Axes:
14
+ spec: str | None = None, title: str | None = None, ax: Axes | None = None,
15
+ by: ArrayLike | None = None) -> Axes:
15
16
  """kx.plot(x, y, z, 'scatter-dark-grid-leg') or kx.plot(x, y, 'bar-light')
16
17
 
18
+ by= gives a group label per x value, one curve, box or violin per group:
19
+ kx.plot(df.value, spec='kde', by=df.group).
20
+
17
21
  A theme in the spec applies to this plot only; kx.use() sets the notebook default.
18
22
  """
19
23
  if isinstance(z, str): # kx.plot(x, y, "spec"): spec given as 3rd arg
@@ -24,17 +28,21 @@ def plot(x: ArrayLike, y: ArrayLike | None = None, z: ArrayLike | str | None = N
24
28
  kind = KINDS[name]
25
29
  if kind.needs_y and y is None:
26
30
  raise ValueError(f"kind {name!r} needs both x and y")
31
+ if by is not None and not kind.takes_by:
32
+ raise ValueError(f"by= only works with kind {sorted(k.name for k in KINDS.values() if k.takes_by)}, "
33
+ f"not {name!r}")
27
34
  if kind.check:
28
35
  kind.check(y, z, flags)
29
36
 
30
37
  style = plt.style.context(["default", style_path(theme)]) if theme else contextlib.nullcontext()
31
38
  with style:
32
39
  ax = ax or plt.subplots()[1]
33
- kind.draw(ax, x, y, z, flags)
40
+ kind.draw(ax, x, y, z, flags, **({"by": by} if by is not None else {}))
34
41
 
35
42
  if "grid" in flags: ax.grid(True)
36
43
  if "leg" in flags and ax.get_legend() is None: # a 100% stack has no free corner: legend goes right
37
- ax.legend(**({"loc": "center left", "bbox_to_anchor": (1, 0.5)} if "norm" in flags else {}))
44
+ outside = name == "area" and "norm" in flags
45
+ ax.legend(**({"loc": "center left", "bbox_to_anchor": (1, 0.5)} if outside else {}))
38
46
  if "logx" in flags: ax.set_xscale("log")
39
47
  if "logy" in flags: ax.set_yscale("log")
40
48
  if title: ax.set_title(title)
@@ -16,18 +16,19 @@ class Kind:
16
16
  flags: frozenset[str] # kind-specific flags, on top of COMMON_FLAGS
17
17
  needs_y: bool
18
18
  check: Callable[[Any, Any, set[str]], None] | None # check(y, z, flags) raises on bad input
19
+ takes_by: bool = False # draw also gets by= (group labels for x)
19
20
 
20
21
 
21
22
  KINDS: dict[str, Kind] = {}
22
23
 
23
24
 
24
25
  def kind(name: str, flags: tuple[str, ...] = (), needs_y: bool = True,
25
- check: Callable[[Any, Any, set[str]], None] | None = None) -> Callable:
26
+ check: Callable[[Any, Any, set[str]], None] | None = None, takes_by: bool = False) -> Callable:
26
27
  """Decorator that registers a draw function as kind `name`."""
27
28
  def register(draw: Callable[..., None]) -> Callable[..., None]:
28
29
  if name in KINDS or name in COMMON_FLAGS or "-" in name:
29
30
  raise ValueError(f"kind name {name!r} is taken or has a '-'")
30
- KINDS[name] = Kind(name, draw, frozenset(flags), needs_y, check)
31
+ KINDS[name] = Kind(name, draw, frozenset(flags), needs_y, check, takes_by)
31
32
  return draw
32
33
  return register
33
34
 
@@ -3,11 +3,15 @@ from typing import Any
3
3
 
4
4
  import matplotlib as mpl
5
5
  import matplotlib.pyplot as plt
6
+ from matplotlib.colors import ListedColormap
6
7
 
7
8
  from . import _files
8
9
 
9
10
  BUILTIN_CMAPS = ("viridis", "magma", "plasma", "inferno", "cividis", "turbo",
10
11
  "twilight", "coolwarm", "berlin", "managua", "vanimo")
12
+ # styles/cmaps/<name>.txt: cmocean, then Crameri's Scientific colour maps 8
13
+ VENDORED_CMAPS = ("thermal", "haline", "deep", "balance",
14
+ "batlow", "lipari", "hawaii", "oslo", "davos", "vik", "roma", "bam", "cork", "romaO")
11
15
 
12
16
 
13
17
  def styles() -> list[str]:
@@ -36,14 +40,30 @@ def _read_palette(name: str) -> list[str]:
36
40
  """palette() under a name that kx.use's `palette` argument does not shadow."""
37
41
  if name not in palettes():
38
42
  raise ValueError(f"unknown palette {name!r}. Available: {palettes()}")
39
- with open(_files.path("styles", "palettes", f"{name}.txt")) as f:
43
+ return _read_hex(_files.path("styles", "palettes", f"{name}.txt"))
44
+
45
+
46
+ def _read_hex(path: str) -> list[str]:
47
+ """One hex per line as '#RRGGBB'; '#' lines are comments."""
48
+ with open(path) as f:
40
49
  lines = (line.strip() for line in f)
41
50
  return [f"#{line}" for line in lines if line and not line.startswith("#")]
42
51
 
43
52
 
53
+ def _register_cmaps() -> None:
54
+ """Add the vendored colormaps to matplotlib, once."""
55
+ for name in VENDORED_CMAPS:
56
+ if name not in mpl.colormaps:
57
+ cmap = ListedColormap(_read_hex(_files.path("styles", "cmaps", f"{name}.txt")), name=name)
58
+ mpl.colormaps.register(cmap)
59
+
60
+
61
+ _register_cmaps()
62
+
63
+
44
64
  def cmaps() -> list[str]:
45
- """List supported colormap names that this matplotlib version has."""
46
- return sorted(n for n in BUILTIN_CMAPS if n in mpl.colormaps)
65
+ """List supported colormap names that this matplotlib version has, plus the vendored ones."""
66
+ return sorted(n for n in BUILTIN_CMAPS + VENDORED_CMAPS if n in mpl.colormaps)
47
67
 
48
68
 
49
69
  def show(name: str) -> None:
@@ -55,13 +75,15 @@ def show(name: str) -> None:
55
75
  def use(name: str = "dark", palette: str | list[str] | None = None, cmap: str | None = None,
56
76
  **rc: Any) -> None:
57
77
  """Apply a theme, optional palette (name from styles/palettes/ or list of colors),
58
- colormap (one of kx.cmaps()), and rcParam overrides.
78
+ colormap (one of kx.cmaps(), '_r' reverses it), and rcParam overrides.
59
79
  Use double underscore for dots: figure__figsize=(8, 4) -> figure.figsize
60
80
  """
61
- if cmap is not None and cmap not in cmaps():
62
- raise ValueError(f"unknown cmap {cmap!r}. Available: {cmaps()}")
81
+ if cmap is not None and cmap.removesuffix("_r") not in cmaps():
82
+ raise ValueError(f"unknown cmap {cmap!r}. Available: {cmaps()} (add '_r' to reverse)")
63
83
  plt.style.use(["default", style_path(name)]) # reset first so themes never mix
64
84
  if cmap:
85
+ if cmap not in mpl.colormaps: # '<name>_r' that matplotlib does not ship
86
+ mpl.colormaps.register(mpl.colormaps[cmap.removesuffix("_r")].reversed(), name=cmap)
65
87
  plt.rcParams["image.cmap"] = cmap
66
88
  if palette:
67
89
  colors = _read_palette(palette) if isinstance(palette, str) else list(palette)
@@ -79,14 +79,26 @@ def scatter(ax: Axes, x: ArrayLike, y: ArrayLike, z: ArrayLike | None, flags: se
79
79
  ax.legend(title=label(z, "z"))
80
80
 
81
81
 
82
- @kind("bar")
83
- def bar(ax: Axes, x: ArrayLike, y: ArrayLike, z: ArrayLike | None, flags: set[str]) -> None:
84
- """y and z grouped, x = category labels."""
82
+ @kind("bar", flags=("stack",))
83
+ def bar(ax: Axes, x: ArrayLike, y: ArrayLike, z: ArrayLike | None, flags: set[str],
84
+ horizontal: bool = False) -> None:
85
+ """y and z grouped per category, x = category labels; stack = z on top of y."""
85
86
  w = 0.4
86
87
  idx = np.arange(len(x))
88
+ draw = ax.barh if horizontal else ax.bar
87
89
  if z is None:
88
- ax.bar(idx, y, 2 * w, label=label(y, "y"))
90
+ draw(idx, y, 2 * w, label=label(y, "y"))
91
+ elif "stack" in flags: # z starts where y ends, so the bar's end is the total
92
+ draw(idx, y, 2 * w, label=label(y, "y"))
93
+ draw(idx, z, 2 * w, np.asarray(y, dtype=float), label=label(z, "z"))
89
94
  else:
90
- ax.bar(idx - w / 2, y, w, label=label(y, "y"))
91
- ax.bar(idx + w / 2, z, w, label=label(z, "z"))
92
- ax.set_xticks(idx, [str(v) for v in x])
95
+ draw(idx - w / 2, y, w, label=label(y, "y"))
96
+ draw(idx + w / 2, z, w, label=label(z, "z"))
97
+ (ax.set_yticks if horizontal else ax.set_xticks)(idx, [str(v) for v in x])
98
+
99
+
100
+ @kind("barh", flags=("stack",))
101
+ def barh(ax: Axes, x: ArrayLike, y: ArrayLike, z: ArrayLike | None, flags: set[str]) -> None:
102
+ """Like bar, lying down: categories (x) top to bottom, bar lengths along the x axis."""
103
+ bar(ax, x, y, z, flags, horizontal=True)
104
+ ax.invert_yaxis() # first category on top, read like a table
@@ -0,0 +1,151 @@
1
+ """Distribution kinds."""
2
+ import matplotlib as mpl
3
+ import matplotlib.pyplot as plt
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 .._spec import kind
10
+ from .._util import categories, label
11
+
12
+
13
+ def _finite(arr: ArrayLike) -> np.ndarray:
14
+ """Values as floats, NaN and inf dropped: a gap in the data is not a value."""
15
+ v = np.asarray(arr, dtype=float).ravel()
16
+ return v[np.isfinite(v)]
17
+
18
+
19
+ def _series(x: ArrayLike, y: ArrayLike | None, z: ArrayLike | None) -> list[tuple[np.ndarray, str]]:
20
+ return [(_finite(a), label(a, n)) for a, n in ((x, "x"), (y, "y"), (z, "z")) if a is not None]
21
+
22
+
23
+ def _split(x: ArrayLike, y: ArrayLike | None, z: ArrayLike | None,
24
+ by: ArrayLike | None) -> list[tuple[np.ndarray, str]]:
25
+ """x, y, z as separate series, or with by= x split into one series per group (categories in order)."""
26
+ if by is None:
27
+ return _series(x, y, z)
28
+ if y is not None or z is not None:
29
+ raise ValueError("by= splits x into groups; pass only x, not y or z")
30
+ xs, groups = np.asarray(x, dtype=float).ravel(), np.asarray(by, dtype=object).ravel()
31
+ if len(xs) != len(groups):
32
+ raise ValueError(f"by= has {len(groups)} values but x has {len(xs)}")
33
+ cats = categories(by)
34
+ if cats is None:
35
+ cats = sorted(pd.unique(groups[pd.notna(groups)]))
36
+ return [(_finite(xs[groups == c]), str(c)) for c in cats]
37
+
38
+
39
+ def _need(series: list[tuple[np.ndarray, str]], kind: str, distinct: int) -> None:
40
+ for v, n in series:
41
+ if len(np.unique(v)) < distinct:
42
+ what = "a finite value" if distinct == 1 else f"at least {distinct} distinct finite values"
43
+ raise ValueError(f"{kind} of {n!r} needs {what}")
44
+
45
+
46
+ @kind("hist", flags=("stack", "norm", "cum"), needs_y=False)
47
+ def hist(ax: Axes, x: ArrayLike, y: ArrayLike | None, z: ArrayLike | None, flags: set[str]) -> None:
48
+ """Up to three distributions x, y, z on the same 30 bins, overlaid.
49
+ stack = on top of each other, norm = density (area 1), cum = cumulative outlines (with norm: the CDF)."""
50
+ series = _series(x, y, z)
51
+ edges = np.histogram_bin_edges(np.concatenate([v for v, _ in series]), bins=30)
52
+ values, names = [v for v, _ in series], [n for _, n in series]
53
+ if "stack" in flags:
54
+ ax.hist(values, edges, histtype="barstacked", label=names,
55
+ density="norm" in flags, cumulative="cum" in flags)
56
+ else: # overlaid cumulative fills hide each other: outlines instead
57
+ look = {"histtype": "step", "linewidth": 1.5} if "cum" in flags else {"alpha": 0.6}
58
+ for v, n in zip(values, names, strict=True):
59
+ ax.hist(v, edges, label=n, density="norm" in flags, cumulative="cum" in flags, **look)
60
+
61
+
62
+ def density(v: np.ndarray, grid: np.ndarray, bw: float) -> np.ndarray:
63
+ """Gaussian KDE of v on grid with bandwidth bw, in chunks so big v does not need a len(v) x len(grid) array."""
64
+ out = np.zeros_like(grid)
65
+ for i in range(0, len(v), 4096):
66
+ out += np.exp(-0.5 * ((grid[:, None] - v[None, i:i + 4096]) / bw) ** 2).sum(axis=1)
67
+ return out / (len(v) * bw * np.sqrt(2 * np.pi))
68
+
69
+
70
+ def bandwidth(v: np.ndarray) -> float:
71
+ """Silverman's rule of thumb, the IQR form: one outlier does not flatten the curve."""
72
+ iqr = np.subtract(*np.percentile(v, [75, 25]))
73
+ spread = min(v.std(ddof=1), iqr / 1.349) if iqr > 0 else v.std(ddof=1)
74
+ return 0.9 * spread * len(v) ** -0.2
75
+
76
+
77
+ @kind("kde", needs_y=False, takes_by=True)
78
+ def kde(ax: Axes, x: ArrayLike, y: ArrayLike | None, z: ArrayLike | None, flags: set[str],
79
+ by: ArrayLike | None = None) -> None:
80
+ """Smooth density curves of x, y, z (Gaussian KDE, Silverman bandwidth).
81
+ by= splits x into one curve per group: kx.plot(df.value, spec='kde', by=df.group)."""
82
+ series = _split(x, y, z, by)
83
+ _need(series, "kde", 2)
84
+ bws = [bandwidth(v) for v, _ in series]
85
+ lo = min(v.min() - 3 * bw for (v, _), bw in zip(series, bws, strict=True))
86
+ hi = max(v.max() + 3 * bw for (v, _), bw in zip(series, bws, strict=True))
87
+ grid = np.linspace(lo, hi, 256)
88
+ for (v, n), bw in zip(series, bws, strict=True):
89
+ d = density(v, grid, bw)
90
+ ln, = ax.plot(grid, d, label=n)
91
+ ax.fill_between(grid, d, color=ln.get_color(), alpha=0.15, linewidth=0)
92
+ ax.set_ylim(bottom=0)
93
+ if by is not None:
94
+ ax.legend(title=label(by, "by"))
95
+
96
+
97
+ @kind("ecdf", needs_y=False, takes_by=True)
98
+ def ecdf(ax: Axes, x: ArrayLike, y: ArrayLike | None, z: ArrayLike | None, flags: set[str],
99
+ by: ArrayLike | None = None) -> None:
100
+ """Empirical CDF of x, y, z: the share of values <= each x, a step up of 1/n at every value.
101
+ by= splits x into one curve per group."""
102
+ series = _split(x, y, z, by)
103
+ _need(series, "ecdf", 1)
104
+ for v, n in series:
105
+ v = np.sort(v)
106
+ ax.step(np.r_[v[0], v], np.arange(len(v) + 1) / len(v), where="post", label=n)
107
+ ax.set_ylim(0, 1.02)
108
+ if by is not None:
109
+ ax.legend(title=label(by, "by"))
110
+
111
+
112
+ def _per_group(ax: Axes, names: list[str], by: ArrayLike | None) -> None:
113
+ """One tick per series, named; with by= the axis is named after the groups."""
114
+ ax.set_xticks(range(1, len(names) + 1), names)
115
+ if by is not None:
116
+ ax.set_xlabel(label(by, "by"))
117
+
118
+
119
+ @kind("box", needs_y=False, takes_by=True)
120
+ def box(ax: Axes, x: ArrayLike, y: ArrayLike | None, z: ArrayLike | None, flags: set[str],
121
+ by: ArrayLike | None = None) -> None:
122
+ """Box plots of x, y, z side by side: median, quartile box, whiskers to 1.5 IQR, outliers as points.
123
+ by= splits x into one box per group."""
124
+ series = _split(x, y, z, by)
125
+ _need(series, "box", 1)
126
+ ink = plt.rcParams["text.color"] # whiskers and medians in the theme's ink, not black on dark
127
+ line = {"color": ink}
128
+ parts = ax.boxplot([v for v, _ in series], patch_artist=True, boxprops={"edgecolor": ink}, medianprops=line,
129
+ whiskerprops=line, capprops=line, flierprops={"markeredgecolor": ink})
130
+ for i, patch in enumerate(parts["boxes"]):
131
+ patch.set_facecolor((*mpl.colors.to_rgb(f"C{i}"), 0.7)) # alpha on the fill only, edge stays solid
132
+ _per_group(ax, [n for _, n in series], by)
133
+
134
+
135
+ @kind("violin", needs_y=False, takes_by=True)
136
+ def violin(ax: Axes, x: ArrayLike, y: ArrayLike | None, z: ArrayLike | None, flags: set[str],
137
+ by: ArrayLike | None = None) -> None:
138
+ """Violin plots of x, y, z side by side: a mirrored KDE with the median and quartiles marked.
139
+ by= splits x into one violin per group."""
140
+ series = _split(x, y, z, by)
141
+ _need(series, "violin", 2)
142
+ values = [v for v, _ in series]
143
+ parts = ax.violinplot(values, showextrema=False)
144
+ for i, body in enumerate(parts["bodies"]):
145
+ body.set(facecolor=f"C{i}", edgecolor=f"C{i}", alpha=0.6)
146
+ pos = np.arange(1, len(values) + 1)
147
+ q1, med, q3 = np.array([np.percentile(v, [25, 50, 75]) for v in values]).T
148
+ ink = plt.rcParams["text.color"]
149
+ ax.vlines(pos, q1, q3, color=ink, linewidth=3)
150
+ ax.scatter(pos, med, color=plt.rcParams["axes.facecolor"], edgecolor=ink, zorder=3)
151
+ _per_group(ax, [n for _, n in series], by)
@@ -0,0 +1,57 @@
1
+ # Vendored colourmaps
2
+
3
+ ```
4
+ cmocean colourmaps: thermal, haline, deep, balance
5
+ https://github.com/matplotlib/cmocean
6
+
7
+ The MIT License (MIT)
8
+
9
+ Copyright (c) 2015 Kristen M. Thyng
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.```
28
+
29
+ ```
30
+ Crameri colourmaps: batlow, lipari, hawaii, oslo, davos, vik, roma, bam, cork, romaO
31
+ Scientific colour maps 8.0, https://doi.org/10.5281/zenodo.8035877
32
+ Tables taken from cmcrameri 1.10, https://github.com/callumrollo/cmcrameri
33
+
34
+ MIT License
35
+
36
+ Colormaps in cmcrameri/cm/cmaps:
37
+ Copyright (c) 2020 Fabio Crameri
38
+
39
+
40
+ Permission is hereby granted, free of charge, to any person obtaining a copy
41
+ of this software and associated documentation files (the "Software"), to deal
42
+ in the Software without restriction, including without limitation the rights
43
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
44
+ copies of the Software, and to permit persons to whom the Software is
45
+ furnished to do so, subject to the following conditions:
46
+
47
+ The above copyright notice and this permission notice shall be included in all
48
+ copies or substantial portions of the Software.
49
+
50
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
51
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
52
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
53
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
54
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
55
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
56
+ SOFTWARE.
57
+ ```