kx-plot 0.1.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 (43) hide show
  1. kx_plot-0.1.0/.gitignore +14 -0
  2. kx_plot-0.1.0/CHANGELOG.md +84 -0
  3. kx_plot-0.1.0/LICENSE +21 -0
  4. kx_plot-0.1.0/PKG-INFO +114 -0
  5. kx_plot-0.1.0/README.md +87 -0
  6. kx_plot-0.1.0/kx/__init__.py +76 -0
  7. kx_plot-0.1.0/kx/_data.py +16 -0
  8. kx_plot-0.1.0/kx/_files.py +16 -0
  9. kx_plot-0.1.0/kx/_plot.py +42 -0
  10. kx_plot-0.1.0/kx/_spec.py +57 -0
  11. kx_plot-0.1.0/kx/_theme.py +72 -0
  12. kx_plot-0.1.0/kx/_util.py +22 -0
  13. kx_plot-0.1.0/kx/data/cloud.csv +201 -0
  14. kx_plot-0.1.0/kx/data/dists.csv +501 -0
  15. kx_plot-0.1.0/kx/data/monthly.csv +13 -0
  16. kx_plot-0.1.0/kx/data/waves.csv +61 -0
  17. kx_plot-0.1.0/kx/kinds/__init__.py +2 -0
  18. kx_plot-0.1.0/kx/kinds/basic.py +92 -0
  19. kx_plot-0.1.0/kx/kinds/dist.py +14 -0
  20. kx_plot-0.1.0/kx/styles/dark.mplstyle +21 -0
  21. kx_plot-0.1.0/kx/styles/light.mplstyle +16 -0
  22. kx_plot-0.1.0/kx/styles/palettes/LICENCES.md +583 -0
  23. kx_plot-0.1.0/kx/styles/palettes/dark2.txt +10 -0
  24. kx_plot-0.1.0/kx/styles/palettes/ibm.txt +7 -0
  25. kx_plot-0.1.0/kx/styles/palettes/okabe.txt +10 -0
  26. kx_plot-0.1.0/kx/styles/palettes/petroff10.txt +12 -0
  27. kx_plot-0.1.0/kx/styles/palettes/petroff6.txt +8 -0
  28. kx_plot-0.1.0/kx/styles/palettes/petroff8.txt +10 -0
  29. kx_plot-0.1.0/kx/styles/palettes/set2.txt +10 -0
  30. kx_plot-0.1.0/kx/styles/palettes/tab10.txt +12 -0
  31. kx_plot-0.1.0/kx/styles/palettes/tableaucb.txt +12 -0
  32. kx_plot-0.1.0/kx/styles/palettes/tolbright.txt +9 -0
  33. kx_plot-0.1.0/kx/styles/palettes/tolhc.txt +6 -0
  34. kx_plot-0.1.0/kx/styles/palettes/tolmc.txt +9 -0
  35. kx_plot-0.1.0/kx/styles/palettes/tolvibrant.txt +9 -0
  36. kx_plot-0.1.0/kx/styles/paper.mplstyle +29 -0
  37. kx_plot-0.1.0/kx/styles/poster.mplstyle +36 -0
  38. kx_plot-0.1.0/kx/styles/science.mplstyle +44 -0
  39. kx_plot-0.1.0/kx/styles/talk.mplstyle +34 -0
  40. kx_plot-0.1.0/kx/styles/thesis.mplstyle +35 -0
  41. kx_plot-0.1.0/pyproject.toml +74 -0
  42. kx_plot-0.1.0/tests/conftest.py +17 -0
  43. kx_plot-0.1.0/tests/test_kx.py +356 -0
@@ -0,0 +1,14 @@
1
+ # Python
2
+ .venv/
3
+ __pycache__/
4
+ *.pyc
5
+ .pytest_cache/
6
+
7
+
8
+ # IDE
9
+ .vscode/
10
+ .idea/
11
+
12
+ # Build
13
+ dist/
14
+ build/
@@ -0,0 +1,84 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.1.0] - 2026-10-08
10
+
11
+ ### Added
12
+
13
+ - **PyPI package:** `pip install kx-plot`, then `import kx`. The wheel ships the themes, palettes and demo CSVs.
14
+ - **Palettes:** Paul Tol (`tolbright`, `tolvibrant`, `tolhc`, `tolmc`), Petroff (`petroff6`, `petroff8`, `petroff10`),
15
+ Tableau (`tab10`, `tableaucb`), ColorBrewer (`set2`, `dark2`) and `ibm`. Their licences are in
16
+ `kx/styles/palettes/LICENCES.md`.
17
+
18
+ ### Changed
19
+
20
+ - **`kx.py` is now the `kx/` package**, with the themes in `kx/styles/` and the demo CSVs in `kx/data/`.
21
+ `kx.source()` prints every file in the package.
22
+
23
+ ## [0.0.2] - 2026-10-08
24
+
25
+ ### Added
26
+
27
+ - **Plot kinds**
28
+ - `step`: like `line`, drawn as steps centred on each x.
29
+ - `area`: filled areas, overlapping and semi-transparent by default.
30
+ - `area-stack` stacks `z` on top of `y`, so the top edge is the total.
31
+ - `area-norm` draws a 100% stack with a percent y axis. With `leg`, the legend goes outside on the right.
32
+ - `band`: a `y` line with a shaded `y ± z` band in the same colour. `z` is required.
33
+ - `scatter` with a text, bool or pandas categorical `z` draws one colour per category with a legend titled after `z`. A numeric `z` still gets a colorbar.
34
+ - **Flags**
35
+ - `stack` and `norm`. Both work with `area` only for now.
36
+ - **Themes**
37
+ - `science`: one journal column (3.5 in), 8 pt serif, inward ticks on all four sides, minor ticks, Paul Tol bright colours, saves at 600 dpi.
38
+ - `talk`: slides (16:9), 18 pt sans, thick lines, Okabe-Ito colours.
39
+ - `poster`: 12 × 9 in, 26 pt sans, very thick lines, saves at 300 dpi.
40
+ - `thesis`: A4 text width (160 mm), Computer Modern 10/9 pt without needing LaTeX, saves as PDF when the file name has no extension.
41
+ - **Palettes**
42
+ - Named palettes live in `styles/palettes/<name>.txt`, one hex colour per line. Any file added there is found automatically.
43
+ - `okabe`: the Okabe-Ito palette, 8 colours that stay distinguishable for every common type of colour blindness.
44
+ - `kx.palettes()` lists the palettes and `kx.palette(name)` returns a palette's colours.
45
+ - `kx.use(theme, palette="okabe")` accepts a palette name as well as a list of colours.
46
+ - **Colormaps**
47
+ - `kx.use(theme, cmap=...)` sets the colormap for continuous colour.
48
+ - The supported matplotlib colormaps are `viridis`, `magma`, `plasma`, `inferno`, `cividis`, `turbo`, `twilight`, `coolwarm`, `berlin`, `managua` and `vanimo`.
49
+ - `kx.cmaps()` lists only the ones the installed matplotlib has. `berlin`, `managua` and `vanimo` need matplotlib 3.10 or newer.
50
+ - **Docs**
51
+ - `Example Usage.ipynb`: a detailed walkthrough for the public Kaggle notebook. It loads `kx` from the attached dataset.
52
+ - `kx.grammar()` lists the palettes and colormaps as well as the kinds, themes and flags.
53
+
54
+ ### Changed
55
+
56
+ - **`paper` theme, reworked for greyscale print:**
57
+ - black, dark grey and mid grey colours, each paired with a linestyle (solid, dashed, dotted, dash-dot)
58
+ - greyscale colormap
59
+ - 300 dpi export with a white background
60
+ - serif font for maths text as well
61
+ - 110 dpi in notebooks instead of 150
62
+ - **Palettes keep the theme's other cycled properties:** they replace only the colours, so `paper` + `okabe` keeps `paper`'s linestyles.
63
+ - **`scatter` point size follows the theme's `lines.markersize`.** Points are bigger on `poster` and smaller on `science`. `dark` and `light` look the same as before.
64
+ - **Preview images:** each theme's preview is drawn at twice that theme's own figure size instead of a fixed 12×6 in, so `talk` and `poster` previews no longer overlap.
65
+ - **`previews/demo.ipynb`:** cut down to a short demo of each kind and theme. The full walkthrough is now `Example Usage.ipynb`.
66
+ - **Strict errors** also cover:
67
+ - `stack` or `norm` on a kind that doesn't support them
68
+ - `band` without `z`
69
+ - `area-norm` with only one series
70
+
71
+ ## [0.0.1] - 2026-10-07
72
+
73
+ ### Added
74
+
75
+ - `kx.plot` with the kinds `line`, `scatter`, `bar` and `hist`
76
+ - the flags `grid`, `leg`, `logx`, `logy` and `tight`
77
+ - the themes `dark`, `light` and `paper`
78
+ - `kx.use`, `kx.show`, `kx.source`, `kx.grammar`, `kx.load` and the demo CSVs
79
+ - a workflow that publishes the dataset to Kaggle
80
+
81
+ [Unreleased]: https://github.com/vhrabar/kx-plot/compare/v0.1.0...HEAD
82
+ [0.1.0]: https://github.com/vhrabar/kx-plot/compare/v0.0.2...v0.1.0
83
+ [0.0.2]: https://github.com/vhrabar/kx-plot/compare/v0.0.1...v0.0.2
84
+ [0.0.1]: https://github.com/vhrabar/kx-plot/releases/tag/v0.0.1
kx_plot-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Vedran Hrabar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
kx_plot-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,114 @@
1
+ Metadata-Version: 2.5
2
+ Name: kx-plot
3
+ Version: 0.1.0
4
+ Summary: One-line matplotlib plots and themes for notebook and scripts, Kaggle-friendly
5
+ Project-URL: Homepage, https://github.com/vhrabar/kx-plot
6
+ Project-URL: Issues, https://github.com/vhrabar/kx-plot/issues
7
+ Project-URL: Changelog, https://github.com/vhrabar/kx-plot/blob/main/CHANGELOG.md
8
+ Project-URL: Kaggle, https://www.kaggle.com/datasets/vhrabar/kx-plot
9
+ Author-email: Vedran Hrabar <vedran.hrabar@outlook.com>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ License-File: kx/styles/palettes/LICENCES.md
13
+ Keywords: jupyter,kaggle,matplotlib,plotting,themes,visualization
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Framework :: Jupyter
16
+ Classifier: Framework :: Matplotlib
17
+ Classifier: Intended Audience :: Science/Research
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Topic :: Scientific/Engineering :: Visualization
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: matplotlib>=3.7
24
+ Requires-Dist: numpy>=1.23
25
+ Requires-Dist: pandas>=1.5
26
+ Description-Content-Type: text/markdown
27
+
28
+ # kx-plot
29
+
30
+ One-line matplotlib plots and themes for notebooks and scripts.
31
+
32
+ `kx` is a small, plain-Python package with `.mplstyle` themes, palettes and colourmaps. It needs nothing beyond
33
+ matplotlib, numpy and pandas and works offline, so it also runs in Kaggle competition notebooks.
34
+
35
+ ![dark theme](https://raw.githubusercontent.com/vhrabar/kx-plot/main/previews/dark.png)
36
+
37
+ ## Install
38
+
39
+ ```bash
40
+ pip install kx-plot
41
+ ```
42
+
43
+ ```python
44
+ import kx; kx.use('dark')
45
+ ```
46
+
47
+ ### Kaggle
48
+
49
+ With internet off (competition notebooks), attach the dataset instead (**Add Input → Datasets → `vhrabar/kx-plot`**), then:
50
+
51
+ ```python
52
+ import sys; sys.path.append('/kaggle/input/datasets/vhrabar/kx-plot')
53
+ import kx; kx.use('dark')
54
+ ```
55
+
56
+ ## Usage
57
+
58
+ ```python
59
+ kx.use('light', palette='okabe', cmap='cividis') # notebook default: theme, palette, colormap
60
+ kx.plot(x, y, z, 'scatter-grid-leg') # spec: kind-theme-flag-...
61
+ kx.plot(x, y, 'bar-paper') # a theme in the spec applies to this plot only
62
+ ```
63
+
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` |
69
+
70
+ Unknown tokens raise an error instead of being guessed. Everything is inspectable:
71
+ `kx.grammar()`, `kx.grammar('area')`, `kx.show('dark')`, `kx.source('scatter')`.
72
+
73
+ rcParams can be overridden in `kx.use` with `__` for dots: `kx.use('dark', figure__figsize=(8, 4))`.
74
+
75
+ ## Palettes
76
+
77
+ Palettes for `kx.use(theme, palette=...)`, they swap only the colours; a theme's
78
+ other cycled properties (such as `paper`'s linestyles) stay.
79
+
80
+ | Name | Source |
81
+ |------------------------------------------|--------------------|
82
+ | `okabe` | Okabe & Ito (2008) |
83
+ | `tolbright` `tolvibrant` `tolhc` `tolmc` | Paul Tol |
84
+ | `petroff6` `petroff8` `petroff10` | Petroff (2021) |
85
+ | `tab10` `tableaucb` | Tableau |
86
+ | `set2` `dark2` | ColorBrewer |
87
+ | `ibm` | IBM Design Colors |
88
+
89
+ `kx.palette('okabe')` returns the hex codes. A list of colours works too: `palette=['#264653', '#e9c46a']`.
90
+
91
+ ## Colourmaps
92
+
93
+ Colourmaps for `kx.use(theme, cmap=...)` colour continuous values, such as a numeric `z` in `scatter`.
94
+ Without `cmap`, the theme's own default applies.
95
+
96
+ | Name | Type |
97
+ |------------------------------------------------|----------------------------------|
98
+ | `viridis` `magma` `plasma` `inferno` `cividis` | Sequential, perceptually uniform |
99
+ | `turbo` | Sequential, rainbow |
100
+ | `coolwarm` | Diverging |
101
+ | `berlin` `managua` `vanimo` | Diverging, dark centre |
102
+ | `twilight` | Cyclic, for angles and phases |
103
+
104
+ `kx.cmaps()` lists the ones that are available in the installed matplotlib as those implemented in matplotlib 3.10 or newer
105
+ are not vendored.
106
+
107
+
108
+ ## License
109
+
110
+ Released under the MIT License. See [`LICENSE`](https://github.com/vhrabar/kx-plot/blob/main/LICENSE).
111
+
112
+ Copyright © 2026 Vedran Hrabar
113
+
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).
@@ -0,0 +1,87 @@
1
+ # kx-plot
2
+
3
+ One-line matplotlib plots and themes for notebooks and scripts.
4
+
5
+ `kx` is a small, plain-Python package with `.mplstyle` themes, palettes and colourmaps. It needs nothing beyond
6
+ matplotlib, numpy and pandas and works offline, so it also runs in Kaggle competition notebooks.
7
+
8
+ ![dark theme](https://raw.githubusercontent.com/vhrabar/kx-plot/main/previews/dark.png)
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ pip install kx-plot
14
+ ```
15
+
16
+ ```python
17
+ import kx; kx.use('dark')
18
+ ```
19
+
20
+ ### Kaggle
21
+
22
+ With internet off (competition notebooks), attach the dataset instead (**Add Input → Datasets → `vhrabar/kx-plot`**), then:
23
+
24
+ ```python
25
+ import sys; sys.path.append('/kaggle/input/datasets/vhrabar/kx-plot')
26
+ import kx; kx.use('dark')
27
+ ```
28
+
29
+ ## Usage
30
+
31
+ ```python
32
+ kx.use('light', palette='okabe', cmap='cividis') # notebook default: theme, palette, colormap
33
+ kx.plot(x, y, z, 'scatter-grid-leg') # spec: kind-theme-flag-...
34
+ kx.plot(x, y, 'bar-paper') # a theme in the spec applies to this plot only
35
+ ```
36
+
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` |
42
+
43
+ Unknown tokens raise an error instead of being guessed. Everything is inspectable:
44
+ `kx.grammar()`, `kx.grammar('area')`, `kx.show('dark')`, `kx.source('scatter')`.
45
+
46
+ rcParams can be overridden in `kx.use` with `__` for dots: `kx.use('dark', figure__figsize=(8, 4))`.
47
+
48
+ ## Palettes
49
+
50
+ Palettes for `kx.use(theme, palette=...)`, they swap only the colours; a theme's
51
+ other cycled properties (such as `paper`'s linestyles) stay.
52
+
53
+ | Name | Source |
54
+ |------------------------------------------|--------------------|
55
+ | `okabe` | Okabe & Ito (2008) |
56
+ | `tolbright` `tolvibrant` `tolhc` `tolmc` | Paul Tol |
57
+ | `petroff6` `petroff8` `petroff10` | Petroff (2021) |
58
+ | `tab10` `tableaucb` | Tableau |
59
+ | `set2` `dark2` | ColorBrewer |
60
+ | `ibm` | IBM Design Colors |
61
+
62
+ `kx.palette('okabe')` returns the hex codes. A list of colours works too: `palette=['#264653', '#e9c46a']`.
63
+
64
+ ## Colourmaps
65
+
66
+ Colourmaps for `kx.use(theme, cmap=...)` colour continuous values, such as a numeric `z` in `scatter`.
67
+ Without `cmap`, the theme's own default applies.
68
+
69
+ | Name | Type |
70
+ |------------------------------------------------|----------------------------------|
71
+ | `viridis` `magma` `plasma` `inferno` `cividis` | Sequential, perceptually uniform |
72
+ | `turbo` | Sequential, rainbow |
73
+ | `coolwarm` | Diverging |
74
+ | `berlin` `managua` `vanimo` | Diverging, dark centre |
75
+ | `twilight` | Cyclic, for angles and phases |
76
+
77
+ `kx.cmaps()` lists the ones that are available in the installed matplotlib as those implemented in matplotlib 3.10 or newer
78
+ are not vendored.
79
+
80
+
81
+ ## License
82
+
83
+ Released under the MIT License. See [`LICENSE`](https://github.com/vhrabar/kx-plot/blob/main/LICENSE).
84
+
85
+ Copyright © 2026 Vedran Hrabar
86
+
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).
@@ -0,0 +1,76 @@
1
+ """
2
+ kx: tiny matplotlib helper.
3
+
4
+ Token grammar for kx.plot(spec): kind-theme-flag-flag-...
5
+ kind : line | step | area | band | scatter | bar | hist
6
+ theme : any file name in styles/
7
+ flags : grid | leg | logx | logy | tight | stack | norm (stack and norm: area only)
8
+
9
+ Palettes (kx.use(theme, palette="okabe")): any file name in styles/palettes/
10
+ Colormaps (kx.use(theme, cmap="magma")): kx.cmaps()
11
+ kx.grammar("area") and kx.source("area") explain one kind.
12
+ """
13
+ import glob
14
+ import importlib.metadata
15
+ import inspect
16
+ import os
17
+ import re
18
+
19
+ from ._data import datasets, load
20
+ from ._plot import plot
21
+ from ._spec import COMMON_FLAGS, KINDS, all_flags
22
+ from ._spec import parse as _parse # noqa: F401 (tests)
23
+ from ._theme import BUILTIN_CMAPS, cmaps, palette, palettes, show, styles, use
24
+
25
+ __all__ = ["BUILTIN_CMAPS", "__version__", "cmaps", "datasets", "grammar", "load", "palette", "palettes", "plot",
26
+ "show", "source", "styles", "use"]
27
+
28
+
29
+ def _version() -> str:
30
+ """project.version from pyproject.toml, the only place it is written.
31
+
32
+ """
33
+ toml = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "pyproject.toml")
34
+ if os.path.isfile(toml):
35
+ with open(toml) as f:
36
+ m = re.search(r'^version\s*=\s*"([^"]+)"', f.read(), re.MULTILINE)
37
+ if m:
38
+ return m.group(1)
39
+ try:
40
+ return importlib.metadata.version("kx-plot")
41
+ except importlib.metadata.PackageNotFoundError:
42
+ return "unknown"
43
+
44
+
45
+ __version__ = _version()
46
+
47
+
48
+ def _kind(name: str): # noqa: ANN202
49
+ if name not in KINDS:
50
+ raise ValueError(f"unknown kind {name!r}. Available: {sorted(KINDS)}")
51
+ return KINDS[name]
52
+
53
+
54
+ def grammar(kind: str | None = None) -> None:
55
+ """Print the valid tokens for kx.plot specs, or what one kind does and which flags it takes."""
56
+ if kind:
57
+ k = _kind(kind)
58
+ print(f"{k.name}: {inspect.getdoc(k.draw)}")
59
+ print("flags:", sorted(COMMON_FLAGS), "+", sorted(k.flags) or "none of its own")
60
+ return
61
+ print("kind :", sorted(KINDS))
62
+ print("theme:", styles())
63
+ print("flags:", sorted(all_flags()))
64
+ print("palettes (kx.use):", palettes())
65
+ print("cmaps (kx.use):", cmaps())
66
+
67
+
68
+ def source(kind: str | None = None) -> None:
69
+ """Print the code that draws one kind, or every file in this package."""
70
+ if kind:
71
+ print(inspect.getsource(_kind(kind).draw))
72
+ return
73
+ here = os.path.dirname(os.path.abspath(__file__))
74
+ for p in sorted(glob.glob(os.path.join(here, "**", "*.py"), recursive=True)):
75
+ with open(p) as f:
76
+ print(f"# ---------- kx/{os.path.relpath(p, here)} ----------\n{f.read()}")
@@ -0,0 +1,16 @@
1
+ """Demo data that ships in data/."""
2
+ import pandas as pd
3
+
4
+ from . import _files
5
+
6
+
7
+ def datasets() -> list[str]:
8
+ """List CSV names available to kx.load()."""
9
+ return _files.names("data", ".csv")
10
+
11
+
12
+ def load(name: str) -> pd.DataFrame:
13
+ """Read data/<name>.csv that ships with the package."""
14
+ if name not in datasets():
15
+ raise ValueError(f"unknown dataset {name!r}. Available: {datasets()}")
16
+ return pd.read_csv(_files.path("data", f"{name}.csv"))
@@ -0,0 +1,16 @@
1
+ """Files that ship inside the package: styles/, styles/palettes/, data/."""
2
+ import glob
3
+ import os
4
+
5
+ # the kx/ package folder; read as _files.root at call time so tests can point it elsewhere
6
+ root = os.path.dirname(os.path.abspath(__file__))
7
+
8
+
9
+ def path(*parts: str) -> str:
10
+ """Path under the root."""
11
+ return os.path.join(root, *parts)
12
+
13
+
14
+ def names(folder: str, ext: str) -> list[str]:
15
+ """Sorted base names of the <folder>/*<ext> files under the root."""
16
+ return sorted(os.path.basename(p)[:-len(ext)] for p in glob.glob(path(folder, f"*{ext}")))
@@ -0,0 +1,42 @@
1
+ """kx.plot: the one-liner. Kinds live in kx/kinds/; this file checks input and applies common flags."""
2
+ import contextlib
3
+
4
+ import matplotlib.pyplot as plt
5
+ from matplotlib.axes import Axes
6
+ from numpy.typing import ArrayLike
7
+
8
+ from . import kinds # noqa: F401 (registers every kind)
9
+ from ._spec import KINDS, parse
10
+ from ._theme import style_path
11
+
12
+
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:
15
+ """kx.plot(x, y, z, 'scatter-dark-grid-leg') or kx.plot(x, y, 'bar-light')
16
+
17
+ A theme in the spec applies to this plot only; kx.use() sets the notebook default.
18
+ """
19
+ if isinstance(z, str): # kx.plot(x, y, "spec"): spec given as 3rd arg
20
+ if spec is not None:
21
+ raise TypeError("spec given twice (as z and as spec=)")
22
+ z, spec = None, z
23
+ name, theme, flags = parse(spec or "line")
24
+ kind = KINDS[name]
25
+ if kind.needs_y and y is None:
26
+ raise ValueError(f"kind {name!r} needs both x and y")
27
+ if kind.check:
28
+ kind.check(y, z, flags)
29
+
30
+ style = plt.style.context(["default", style_path(theme)]) if theme else contextlib.nullcontext()
31
+ with style:
32
+ ax = ax or plt.subplots()[1]
33
+ kind.draw(ax, x, y, z, flags)
34
+
35
+ if "grid" in flags: ax.grid(True)
36
+ 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 {}))
38
+ if "logx" in flags: ax.set_xscale("log")
39
+ if "logy" in flags: ax.set_yscale("log")
40
+ if title: ax.set_title(title)
41
+ if "tight" in flags: ax.figure.tight_layout()
42
+ return ax
@@ -0,0 +1,57 @@
1
+ """Spec grammar (kind-theme-flag-flag-...) and the registry of kinds."""
2
+ from collections.abc import Callable
3
+ from dataclasses import dataclass
4
+ from typing import Any
5
+
6
+ from ._theme import styles
7
+
8
+ COMMON_FLAGS = {"grid", "leg", "logx", "logy", "tight"} # handled by kx.plot for every kind
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class Kind:
13
+ """A plot kind: draw(ax, x, y, z, flags) plus what kx.plot checks before drawing."""
14
+ name: str
15
+ draw: Callable[..., None]
16
+ flags: frozenset[str] # kind-specific flags, on top of COMMON_FLAGS
17
+ needs_y: bool
18
+ check: Callable[[Any, Any, set[str]], None] | None # check(y, z, flags) raises on bad input
19
+
20
+
21
+ KINDS: dict[str, Kind] = {}
22
+
23
+
24
+ def kind(name: str, flags: tuple[str, ...] = (), needs_y: bool = True,
25
+ check: Callable[[Any, Any, set[str]], None] | None = None) -> Callable:
26
+ """Decorator that registers a draw function as kind `name`."""
27
+ def register(draw: Callable[..., None]) -> Callable[..., None]:
28
+ if name in KINDS or name in COMMON_FLAGS or "-" in name:
29
+ raise ValueError(f"kind name {name!r} is taken or has a '-'")
30
+ KINDS[name] = Kind(name, draw, frozenset(flags), needs_y, check)
31
+ return draw
32
+ return register
33
+
34
+
35
+ def all_flags() -> set[str]:
36
+ """Common flags and every kind-specific flag."""
37
+ return COMMON_FLAGS.union(*(k.flags for k in KINDS.values()))
38
+
39
+
40
+ def parse(spec: str) -> tuple[str, str | None, set[str]]:
41
+ """Split 'kind-theme-flag-...' into (kind, theme, flags). Strict: no guessing."""
42
+ toks = spec.split("-")
43
+ themes, flags = set(styles()), all_flags()
44
+ unknown = [t for t in toks if t not in KINDS.keys() | flags | themes]
45
+ if unknown:
46
+ raise ValueError(f"unknown tokens: {unknown}. Run kx.grammar() to see valid ones.")
47
+ kinds = [t for t in toks if t in KINDS]
48
+ picked = [t for t in toks if t in themes]
49
+ if len(kinds) > 1:
50
+ raise ValueError(f"spec {spec!r} has more than one kind: {kinds}")
51
+ if len(picked) > 1:
52
+ raise ValueError(f"spec {spec!r} has more than one theme: {picked}")
53
+ kind = (kinds or ["line"])[0]
54
+ for flag in sorted(set(toks) & (flags - COMMON_FLAGS - KINDS[kind].flags)):
55
+ owners = sorted(k.name for k in KINDS.values() if flag in k.flags)
56
+ raise ValueError(f"flag {flag!r} only works with kind {owners}, not {kind!r}")
57
+ return kind, (picked or [None])[0], set(toks) & flags
@@ -0,0 +1,72 @@
1
+ """Themes, palettes and colormaps: discovery and kx.use."""
2
+ from typing import Any
3
+
4
+ import matplotlib as mpl
5
+ import matplotlib.pyplot as plt
6
+
7
+ from . import _files
8
+
9
+ BUILTIN_CMAPS = ("viridis", "magma", "plasma", "inferno", "cividis", "turbo",
10
+ "twilight", "coolwarm", "berlin", "managua", "vanimo")
11
+
12
+
13
+ def styles() -> list[str]:
14
+ """List available theme names."""
15
+ return _files.names("styles", ".mplstyle")
16
+
17
+
18
+ def style_path(name: str) -> str:
19
+ """Path to styles/<name>.mplstyle; unknown names raise ValueError."""
20
+ if name not in styles():
21
+ raise ValueError(f"unknown theme {name!r}. Available: {styles()}")
22
+ return _files.path("styles", f"{name}.mplstyle")
23
+
24
+
25
+ def palettes() -> list[str]:
26
+ """List available palette names."""
27
+ return _files.names("styles/palettes", ".txt")
28
+
29
+
30
+ def palette(name: str) -> list[str]:
31
+ """Colors of styles/palettes/<name>.txt as '#RRGGBB' strings (one hex per line, '#' lines are comments)."""
32
+ return _read_palette(name)
33
+
34
+
35
+ def _read_palette(name: str) -> list[str]:
36
+ """palette() under a name that kx.use's `palette` argument does not shadow."""
37
+ if name not in palettes():
38
+ raise ValueError(f"unknown palette {name!r}. Available: {palettes()}")
39
+ with open(_files.path("styles", "palettes", f"{name}.txt")) as f:
40
+ lines = (line.strip() for line in f)
41
+ return [f"#{line}" for line in lines if line and not line.startswith("#")]
42
+
43
+
44
+ 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)
47
+
48
+
49
+ def show(name: str) -> None:
50
+ """Print the contents of a style file."""
51
+ with open(style_path(name)) as f:
52
+ print(f.read())
53
+
54
+
55
+ def use(name: str = "dark", palette: str | list[str] | None = None, cmap: str | None = None,
56
+ **rc: Any) -> None:
57
+ """Apply a theme, optional palette (name from styles/palettes/ or list of colors),
58
+ colormap (one of kx.cmaps()), and rcParam overrides.
59
+ Use double underscore for dots: figure__figsize=(8, 4) -> figure.figsize
60
+ """
61
+ if cmap is not None and cmap not in cmaps():
62
+ raise ValueError(f"unknown cmap {cmap!r}. Available: {cmaps()}")
63
+ plt.style.use(["default", style_path(name)]) # reset first so themes never mix
64
+ if cmap:
65
+ plt.rcParams["image.cmap"] = cmap
66
+ if palette:
67
+ colors = _read_palette(palette) if isinstance(palette, str) else list(palette)
68
+ # swap only the colors; other cycled props (paper's linestyles) repeat to the new length
69
+ rest = {k: v for k, v in plt.rcParams["axes.prop_cycle"].by_key().items() if k != "color"}
70
+ plt.rcParams["axes.prop_cycle"] = plt.cycler(
71
+ color=colors, **{k: [v[i % len(v)] for i in range(len(colors))] for k, v in rest.items()})
72
+ plt.rcParams.update({k.replace("__", "."): v for k, v in rc.items()})
@@ -0,0 +1,22 @@
1
+ """Small helpers shared by the kinds."""
2
+ from typing import Any
3
+
4
+ import numpy as np
5
+ import pandas as pd
6
+ from numpy.typing import ArrayLike
7
+
8
+
9
+ def label(arr: ArrayLike, default: str) -> str:
10
+ """Use a pandas Series name as legend label when there is one."""
11
+ name = getattr(arr, "name", None)
12
+ return str(name) if name is not None else default
13
+
14
+
15
+ def categories(z: ArrayLike) -> list[Any] | None:
16
+ """Category values of z if it is text, bool or categorical; None if z is numeric."""
17
+ s = z if isinstance(z, pd.Series) else pd.Series(np.asarray(z))
18
+ if isinstance(s.dtype, pd.CategoricalDtype):
19
+ return list(s.cat.categories)
20
+ if pd.api.types.is_numeric_dtype(s) and not pd.api.types.is_bool_dtype(s):
21
+ return None
22
+ return sorted(s.dropna().unique(), key=str)