kx-plot 0.1.0__tar.gz → 0.3.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- kx_plot-0.3.0/CHANGELOG.md +166 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/PKG-INFO +40 -13
- kx_plot-0.3.0/README.md +113 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/__init__.py +18 -8
- kx_plot-0.3.0/kx/_grid.py +25 -0
- kx_plot-0.3.0/kx/_plot.py +121 -0
- kx_plot-0.3.0/kx/_save.py +26 -0
- kx_plot-0.3.0/kx/_spec.py +90 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/_theme.py +41 -7
- kx_plot-0.3.0/kx/data/daily.csv +731 -0
- kx_plot-0.3.0/kx/kinds/basic.py +150 -0
- kx_plot-0.3.0/kx/kinds/dist.py +274 -0
- kx_plot-0.3.0/kx/styles/cmaps/LICENCES.md +57 -0
- kx_plot-0.3.0/kx/styles/cmaps/balance.txt +257 -0
- kx_plot-0.3.0/kx/styles/cmaps/bam.txt +257 -0
- kx_plot-0.3.0/kx/styles/cmaps/batlow.txt +257 -0
- kx_plot-0.3.0/kx/styles/cmaps/cork.txt +257 -0
- kx_plot-0.3.0/kx/styles/cmaps/davos.txt +257 -0
- kx_plot-0.3.0/kx/styles/cmaps/deep.txt +257 -0
- kx_plot-0.3.0/kx/styles/cmaps/haline.txt +257 -0
- kx_plot-0.3.0/kx/styles/cmaps/hawaii.txt +257 -0
- kx_plot-0.3.0/kx/styles/cmaps/lipari.txt +257 -0
- kx_plot-0.3.0/kx/styles/cmaps/oslo.txt +257 -0
- kx_plot-0.3.0/kx/styles/cmaps/roma.txt +257 -0
- kx_plot-0.3.0/kx/styles/cmaps/romaO.txt +257 -0
- kx_plot-0.3.0/kx/styles/cmaps/thermal.txt +257 -0
- kx_plot-0.3.0/kx/styles/cmaps/vik.txt +257 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/styles/palettes/LICENCES.md +1 -1
- kx_plot-0.3.0/kx/styles/palettes/paired.txt +14 -0
- kx_plot-0.3.0/kx/styles/palettes/set1.txt +11 -0
- kx_plot-0.3.0/kx/styles/palettes/tab20.txt +22 -0
- kx_plot-0.3.0/kx/styles/palettes/tollight.txt +11 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/pyproject.toml +2 -2
- kx_plot-0.3.0/tests/test_kx.py +918 -0
- kx_plot-0.1.0/CHANGELOG.md +0 -84
- kx_plot-0.1.0/README.md +0 -87
- kx_plot-0.1.0/kx/_plot.py +0 -42
- kx_plot-0.1.0/kx/_spec.py +0 -57
- kx_plot-0.1.0/kx/kinds/basic.py +0 -92
- kx_plot-0.1.0/kx/kinds/dist.py +0 -14
- kx_plot-0.1.0/tests/test_kx.py +0 -356
- {kx_plot-0.1.0 → kx_plot-0.3.0}/.gitignore +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/LICENSE +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/_data.py +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/_files.py +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/_util.py +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/data/cloud.csv +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/data/dists.csv +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/data/monthly.csv +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/data/waves.csv +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/kinds/__init__.py +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/styles/dark.mplstyle +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/styles/light.mplstyle +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/styles/palettes/dark2.txt +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/styles/palettes/ibm.txt +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/styles/palettes/okabe.txt +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/styles/palettes/petroff10.txt +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/styles/palettes/petroff6.txt +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/styles/palettes/petroff8.txt +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/styles/palettes/set2.txt +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/styles/palettes/tab10.txt +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/styles/palettes/tableaucb.txt +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/styles/palettes/tolbright.txt +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/styles/palettes/tolhc.txt +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/styles/palettes/tolmc.txt +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/styles/palettes/tolvibrant.txt +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/styles/paper.mplstyle +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/styles/poster.mplstyle +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/styles/science.mplstyle +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/styles/talk.mplstyle +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/kx/styles/thesis.mplstyle +0 -0
- {kx_plot-0.1.0 → kx_plot-0.3.0}/tests/conftest.py +0 -0
|
@@ -0,0 +1,166 @@
|
|
|
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.3.0] - 2026-10-12
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- **Plot kind** `qq`: sorted values against normal quantiles, one series per array or `by=` group, with a dashed
|
|
14
|
+
line through each one's quartiles. The quantiles come from Python's `statistics`, so no scipy is needed.
|
|
15
|
+
- **Plot kind** `ridge`: density curves stacked top to bottom, one per array or `by=` group, on one shared height
|
|
16
|
+
scale; `overlap=` sets the tallest ridge's height in rows. `mean` and `median` mark each ridge.
|
|
17
|
+
- **Plot kind** `strip`: every value as a point, one column per array or `by=` group, jittered sideways so ties
|
|
18
|
+
stay visible (the same way every run; `jitter=` sets the spread). Takes `mean` and `ann` like `box`.
|
|
19
|
+
- `kx.grid(n, cols=3)` makes a figure of `n` panels and returns them as a flat array of axes. Each panel gets
|
|
20
|
+
the theme's figure size, empty cells are removed, and constrained layout leaves room for colorbars and outside
|
|
21
|
+
legends. Other keywords go to `plt.subplots`.
|
|
22
|
+
- `kx.save('fig.png')` saves the current figure (or the one of a given `ax` or figure) and returns the path.
|
|
23
|
+
A relative name goes to `/kaggle/working` on Kaggle and to the current folder elsewhere; missing folders are
|
|
24
|
+
created. Without an extension the theme's format is used, so `thesis` saves a PDF.
|
|
25
|
+
- `with kx.context(theme, palette=..., cmap=..., **rc):` takes the same arguments as `kx.use` and puts the
|
|
26
|
+
previous settings back when the block ends, also after an error.
|
|
27
|
+
- `kx.parse(spec)` returns a `Spec` with `kind`, `theme` and `flags`. Printed, it is the canonical spec string
|
|
28
|
+
(kind, theme, then flags A–Z), and `kx.plot` takes a `Spec` wherever it takes a spec string. Mistyped tokens get
|
|
29
|
+
the closest valid ones as a hint.
|
|
30
|
+
- `kx.plot(df, 'x', 'y', 'z', spec)` names DataFrame columns, and `by=` can name a column. A mistyped column
|
|
31
|
+
gets the closest names as a hint.
|
|
32
|
+
- `kx.plot(..., **kwargs)` passes other keywords to the matplotlib call that draws the kind, over kx's defaults:
|
|
33
|
+
`kx.plot(x, y, 'line', linewidth=3)`. `bins=` sets the shared `hist` bins and `width=` (`height=` for
|
|
34
|
+
`barh`) the space each category's bars fill.
|
|
35
|
+
- **Flags for every kind**
|
|
36
|
+
- Layout: `legout` puts the legend outside on the right, keeping a kind's legend title. `rot` rotates the x tick
|
|
37
|
+
labels 45°.
|
|
38
|
+
- Axes: `logxy` (log on both), `symlogy` (symmetric log y, so negatives work), `zero` (the value axis includes 0)
|
|
39
|
+
and `eq` (equal aspect).
|
|
40
|
+
- Number format: `pct` (0.25 → 25%) and `si` (1500 → 1.5k) on the value axis, which is x for `barh` and y
|
|
41
|
+
otherwise.
|
|
42
|
+
- **Flags for some kinds**
|
|
43
|
+
- `date` for `line`, `step`, `area`, `band` and `scatter`: `x` is read as dates (text works too) and gets compact
|
|
44
|
+
date ticks.
|
|
45
|
+
- `mk` for `line`, `step`, `area` and `band`: a marker on every point.
|
|
46
|
+
- `sort` for `bar` and `barh`: largest first, by `y`, or by the total with `stack`.
|
|
47
|
+
- `ann` for `bar` and `barh`: the value on each bar, inside each segment with `stack`.
|
|
48
|
+
- `mean` and `median` for `hist`, `kde` and `ecdf`: a dashed / dotted line at each series' mean / median.
|
|
49
|
+
`mean` for `box` and `violin`: a diamond at each mean. `ann` writes the values.
|
|
50
|
+
- `nocb`, `sym` and `logc` for `scatter` with a numeric `z`: no colorbar, colour limits symmetric around 0,
|
|
51
|
+
log colour scale.
|
|
52
|
+
- Flags that ask for opposite things (`pct` and `si`, `logy` and `logxy`, `zero` and a log y, `sym` and `logc`)
|
|
53
|
+
raise an error.
|
|
54
|
+
|
|
55
|
+
### Changed
|
|
56
|
+
|
|
57
|
+
- The `tight` flag leaves a figure with constrained layout (such as `kx.grid`'s) alone instead of failing
|
|
58
|
+
when it has a colorbar.
|
|
59
|
+
|
|
60
|
+
### Fixed
|
|
61
|
+
|
|
62
|
+
- `leg` and `legout` on a plot with nothing to label, such as `scatter` with a numeric `z`, no longer warn
|
|
63
|
+
"No artists with labels found"; the plot just has no legend.
|
|
64
|
+
|
|
65
|
+
## [0.2.0] - 2026-10-09
|
|
66
|
+
|
|
67
|
+
### Added
|
|
68
|
+
|
|
69
|
+
- **Plot kinds**
|
|
70
|
+
- `barh`: horizontal bars, first category on top. `y` and `z` are grouped like `bar`.
|
|
71
|
+
- `kde`: smooth density curves (Gaussian KDE in numpy, no scipy needed), one per array.
|
|
72
|
+
- `ecdf`: empirical CDF, the share of values at or below each x, one step curve per array.
|
|
73
|
+
- `box`: box plots side by side (median, quartiles, 1.5 IQR whiskers, outliers), one per array.
|
|
74
|
+
- `violin`: violin plots side by side with the median and quartiles marked, one per array.
|
|
75
|
+
- **Flags**
|
|
76
|
+
- `stack` now works with `bar` and `barh`: `z` is drawn on top of `y`, so the bar's end is the total.
|
|
77
|
+
- `stack`, `norm` (density) and the new `cum` (cumulative) work with `hist`.
|
|
78
|
+
- `kx.plot(..., by=groups)` splits `x` into one curve, box or violin per group (for `kde`, `ecdf`, `box`, `violin`).
|
|
79
|
+
- cmocean colourmaps `thermal`, `haline`, `deep` and `balance` for `kx.use(cmap=...)`.
|
|
80
|
+
- Crameri colourmaps (Scientific colour maps 8) `batlow`, `lipari`, `hawaii`, `oslo`, `davos`, `vik`, `roma`,
|
|
81
|
+
`bam`, `cork` and cyclic `romaO`, vendored the same way.
|
|
82
|
+
- `kx.use(cmap="<name>_r")` reverses any colourmap in `kx.cmaps()`.
|
|
83
|
+
- Palettes `tollight` (Paul Tol), `set1` and `paired` (ColorBrewer) and `tab20` (Tableau, 20 categories).
|
|
84
|
+
|
|
85
|
+
### Changed
|
|
86
|
+
|
|
87
|
+
- `hist` puts every series on the same bins, so overlaid bars line up.
|
|
88
|
+
|
|
89
|
+
## [0.1.0] - 2026-10-08
|
|
90
|
+
|
|
91
|
+
### Added
|
|
92
|
+
|
|
93
|
+
- **PyPI package:** `pip install kx-plot`, then `import kx`. The wheel ships the themes, palettes and demo CSVs.
|
|
94
|
+
- **Palettes:** Paul Tol (`tolbright`, `tolvibrant`, `tolhc`, `tolmc`), Petroff (`petroff6`, `petroff8`, `petroff10`),
|
|
95
|
+
Tableau (`tab10`, `tableaucb`), ColorBrewer (`set2`, `dark2`) and `ibm`. Their licences are in
|
|
96
|
+
`kx/styles/palettes/LICENCES.md`.
|
|
97
|
+
|
|
98
|
+
### Changed
|
|
99
|
+
|
|
100
|
+
- **`kx.py` is now the `kx/` package**, with the themes in `kx/styles/` and the demo CSVs in `kx/data/`.
|
|
101
|
+
`kx.source()` prints every file in the package.
|
|
102
|
+
|
|
103
|
+
## [0.0.2] - 2026-10-08
|
|
104
|
+
|
|
105
|
+
### Added
|
|
106
|
+
|
|
107
|
+
- **Plot kinds**
|
|
108
|
+
- `step`: like `line`, drawn as steps centred on each x.
|
|
109
|
+
- `area`: filled areas, overlapping and semi-transparent by default.
|
|
110
|
+
- `area-stack` stacks `z` on top of `y`, so the top edge is the total.
|
|
111
|
+
- `area-norm` draws a 100% stack with a percent y axis. With `leg`, the legend goes outside on the right.
|
|
112
|
+
- `band`: a `y` line with a shaded `y ± z` band in the same colour. `z` is required.
|
|
113
|
+
- `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.
|
|
114
|
+
- **Flags**
|
|
115
|
+
- `stack` and `norm`. Both work with `area` only for now.
|
|
116
|
+
- **Themes**
|
|
117
|
+
- `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.
|
|
118
|
+
- `talk`: slides (16:9), 18 pt sans, thick lines, Okabe-Ito colours.
|
|
119
|
+
- `poster`: 12 × 9 in, 26 pt sans, very thick lines, saves at 300 dpi.
|
|
120
|
+
- `thesis`: A4 text width (160 mm), Computer Modern 10/9 pt without needing LaTeX, saves as PDF when the file name has no extension.
|
|
121
|
+
- **Palettes**
|
|
122
|
+
- Named palettes live in `styles/palettes/<name>.txt`, one hex colour per line. Any file added there is found automatically.
|
|
123
|
+
- `okabe`: the Okabe-Ito palette, 8 colours that stay distinguishable for every common type of colour blindness.
|
|
124
|
+
- `kx.palettes()` lists the palettes and `kx.palette(name)` returns a palette's colours.
|
|
125
|
+
- `kx.use(theme, palette="okabe")` accepts a palette name as well as a list of colours.
|
|
126
|
+
- **Colormaps**
|
|
127
|
+
- `kx.use(theme, cmap=...)` sets the colormap for continuous colour.
|
|
128
|
+
- The supported matplotlib colormaps are `viridis`, `magma`, `plasma`, `inferno`, `cividis`, `turbo`, `twilight`, `coolwarm`, `berlin`, `managua` and `vanimo`.
|
|
129
|
+
- `kx.cmaps()` lists only the ones the installed matplotlib has. `berlin`, `managua` and `vanimo` need matplotlib 3.10 or newer.
|
|
130
|
+
- **Docs**
|
|
131
|
+
- `Example Usage.ipynb`: a detailed walkthrough for the public Kaggle notebook. It loads `kx` from the attached dataset.
|
|
132
|
+
- `kx.grammar()` lists the palettes and colormaps as well as the kinds, themes and flags.
|
|
133
|
+
|
|
134
|
+
### Changed
|
|
135
|
+
|
|
136
|
+
- **`paper` theme, reworked for greyscale print:**
|
|
137
|
+
- black, dark grey and mid grey colours, each paired with a linestyle (solid, dashed, dotted, dash-dot)
|
|
138
|
+
- greyscale colormap
|
|
139
|
+
- 300 dpi export with a white background
|
|
140
|
+
- serif font for maths text as well
|
|
141
|
+
- 110 dpi in notebooks instead of 150
|
|
142
|
+
- **Palettes keep the theme's other cycled properties:** they replace only the colours, so `paper` + `okabe` keeps `paper`'s linestyles.
|
|
143
|
+
- **`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.
|
|
144
|
+
- **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.
|
|
145
|
+
- **`previews/demo.ipynb`:** cut down to a short demo of each kind and theme. The full walkthrough is now `Example Usage.ipynb`.
|
|
146
|
+
- **Strict errors** also cover:
|
|
147
|
+
- `stack` or `norm` on a kind that doesn't support them
|
|
148
|
+
- `band` without `z`
|
|
149
|
+
- `area-norm` with only one series
|
|
150
|
+
|
|
151
|
+
## [0.0.1] - 2026-10-07
|
|
152
|
+
|
|
153
|
+
### Added
|
|
154
|
+
|
|
155
|
+
- `kx.plot` with the kinds `line`, `scatter`, `bar` and `hist`
|
|
156
|
+
- the flags `grid`, `leg`, `logx`, `logy` and `tight`
|
|
157
|
+
- the themes `dark`, `light` and `paper`
|
|
158
|
+
- `kx.use`, `kx.show`, `kx.source`, `kx.grammar`, `kx.load` and the demo CSVs
|
|
159
|
+
- a workflow that publishes the dataset to Kaggle
|
|
160
|
+
|
|
161
|
+
[Unreleased]: https://github.com/vhrabar/kx-plot/compare/v0.3.0...HEAD
|
|
162
|
+
[0.3.0]: https://github.com/vhrabar/kx-plot/compare/v0.2.0...v0.3.0
|
|
163
|
+
[0.2.0]: https://github.com/vhrabar/kx-plot/compare/v0.1.0...v0.2.0
|
|
164
|
+
[0.1.0]: https://github.com/vhrabar/kx-plot/compare/v0.0.2...v0.1.0
|
|
165
|
+
[0.0.2]: https://github.com/vhrabar/kx-plot/compare/v0.0.1...v0.0.2
|
|
166
|
+
[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.
|
|
3
|
+
Version: 0.3.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
|
-
|
|
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,37 @@ 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
|
+
with kx.context('paper'): ... # or to every plot in the block
|
|
64
|
+
kx.save('fig.png') # to /kaggle/working on Kaggle, else the current folder
|
|
65
|
+
for ax, col in zip(kx.grid(3), df.columns): # a figure of 3 panels, a flat array of axes
|
|
66
|
+
kx.plot(df, col, spec='hist', ax=ax)
|
|
67
|
+
kx.plot(df, 'month', 'y2025', 'bar') # DataFrame columns by name
|
|
68
|
+
kx.plot(x, y, 'line', linewidth=3) # other keywords go to matplotlib
|
|
69
|
+
kx.plot(df, 'value', spec='kde', by='group') # one density curve per group
|
|
70
|
+
kx.plot(df.value, spec='box', by=df.group) # one box per group (also ridge, violin, qq)
|
|
62
71
|
```
|
|
63
72
|
|
|
64
|
-
| Token | Values
|
|
65
|
-
|
|
66
|
-
| kind | `line` `step` `area` `band` `scatter` `bar` `hist`
|
|
67
|
-
|
|
|
68
|
-
|
|
|
73
|
+
| Token | Values |
|
|
74
|
+
|-------|-----------------------------------------------------------------------------------------------|
|
|
75
|
+
| kind | `line` `step` `area` `band` `scatter` `bar` `barh` `hist` `kde` `ridge` `ecdf` `box` `violin` |
|
|
76
|
+
| | `strip` `qq` |
|
|
77
|
+
| theme | `dark` `light` `paper` `science` `talk` `poster` `thesis` |
|
|
78
|
+
| flags | `grid` `leg` `legout` `tight` `rot` `logx` `logy` `logxy` `symlogy` `zero` `eq` `pct` `si` |
|
|
79
|
+
| | per kind: `stack` `norm` `cum` `date` `mk` `sort` `ann` `mean` `median` `nocb` `sym` `logc` |
|
|
69
80
|
|
|
70
|
-
|
|
71
|
-
|
|
81
|
+
`stack` works with `area`, `bar`, `barh` and `hist`. `norm` is a 100% stack for `area` and a
|
|
82
|
+
density (area 1) for `hist`. `cum` makes `hist` cumulative; `hist-norm-cum` is the CDF.
|
|
83
|
+
`hist` puts every series on the same bins, so the bars line up.
|
|
84
|
+
|
|
85
|
+
Unknown tokens raise an error instead of being guessed, with the closest valid tokens as a hint.
|
|
86
|
+
Everything is inspectable: `kx.grammar()`, `kx.grammar('area')`, `kx.parse('leg-scatter')`, `kx.show('dark')`,
|
|
87
|
+
`kx.source('scatter')`.
|
|
72
88
|
|
|
73
89
|
rcParams can be overridden in `kx.use` with `__` for dots: `kx.use('dark', figure__figsize=(8, 4))`.
|
|
74
90
|
|
|
91
|
+
Every kind, option, flag and config, with its output, is in the
|
|
92
|
+
[Example Usage notebook](https://github.com/vhrabar/kx-plot/blob/main/Example%20Usage.ipynb).
|
|
93
|
+
|
|
75
94
|
## Palettes
|
|
76
95
|
|
|
77
96
|
Palettes for `kx.use(theme, palette=...)`, they swap only the colours; a theme's
|
|
@@ -80,10 +99,11 @@ other cycled properties (such as `paper`'s linestyles) stay.
|
|
|
80
99
|
| Name | Source |
|
|
81
100
|
|------------------------------------------|--------------------|
|
|
82
101
|
| `okabe` | Okabe & Ito (2008) |
|
|
83
|
-
| `tolbright` `tolvibrant` `
|
|
102
|
+
| `tolbright` `tolvibrant` `tollight` | Paul Tol |
|
|
103
|
+
| `tolhc` `tolmc` | Paul Tol |
|
|
84
104
|
| `petroff6` `petroff8` `petroff10` | Petroff (2021) |
|
|
85
|
-
| `tab10` `tableaucb`
|
|
86
|
-
| `set2` `dark2`
|
|
105
|
+
| `tab10` `tab20` `tableaucb` | Tableau |
|
|
106
|
+
| `set1` `set2` `dark2` `paired` | ColorBrewer |
|
|
87
107
|
| `ibm` | IBM Design Colors |
|
|
88
108
|
|
|
89
109
|
`kx.palette('okabe')` returns the hex codes. A list of colours works too: `palette=['#264653', '#e9c46a']`.
|
|
@@ -92,6 +112,7 @@ other cycled properties (such as `paper`'s linestyles) stay.
|
|
|
92
112
|
|
|
93
113
|
Colourmaps for `kx.use(theme, cmap=...)` colour continuous values, such as a numeric `z` in `scatter`.
|
|
94
114
|
Without `cmap`, the theme's own default applies.
|
|
115
|
+
Add `_r` to any name to reverse it, e.g. `cmap="thermal_r"`.
|
|
95
116
|
|
|
96
117
|
| Name | Type |
|
|
97
118
|
|------------------------------------------------|----------------------------------|
|
|
@@ -100,6 +121,11 @@ Without `cmap`, the theme's own default applies.
|
|
|
100
121
|
| `coolwarm` | Diverging |
|
|
101
122
|
| `berlin` `managua` `vanimo` | Diverging, dark centre |
|
|
102
123
|
| `twilight` | Cyclic, for angles and phases |
|
|
124
|
+
| `thermal` `haline` `deep` | Sequential, cmocean (vendored) |
|
|
125
|
+
| `balance` | Diverging, cmocean (vendored) |
|
|
126
|
+
| `batlow` `lipari` `hawaii` `oslo` `davos` | Sequential, Crameri (vendored) |
|
|
127
|
+
| `vik` `roma` `bam` `cork` | Diverging, Crameri (vendored) |
|
|
128
|
+
| `romaO` | Cyclic, Crameri (vendored) |
|
|
103
129
|
|
|
104
130
|
`kx.cmaps()` lists the ones that are available in the installed matplotlib as those implemented in matplotlib 3.10 or newer
|
|
105
131
|
are not vendored.
|
|
@@ -111,4 +137,5 @@ Released under the MIT License. See [`LICENSE`](https://github.com/vhrabar/kx-pl
|
|
|
111
137
|
|
|
112
138
|
Copyright © 2026 Vedran Hrabar
|
|
113
139
|
|
|
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)
|
|
140
|
+
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)
|
|
141
|
+
and [`kx/styles/cmaps/LICENCES.md`](https://github.com/vhrabar/kx-plot/blob/main/kx/styles/cmaps/LICENCES.md).
|
kx_plot-0.3.0/README.md
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
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
|
+

|
|
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
|
+
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
|
+
with kx.context('paper'): ... # or to every plot in the block
|
|
36
|
+
kx.save('fig.png') # to /kaggle/working on Kaggle, else the current folder
|
|
37
|
+
for ax, col in zip(kx.grid(3), df.columns): # a figure of 3 panels, a flat array of axes
|
|
38
|
+
kx.plot(df, col, spec='hist', ax=ax)
|
|
39
|
+
kx.plot(df, 'month', 'y2025', 'bar') # DataFrame columns by name
|
|
40
|
+
kx.plot(x, y, 'line', linewidth=3) # other keywords go to matplotlib
|
|
41
|
+
kx.plot(df, 'value', spec='kde', by='group') # one density curve per group
|
|
42
|
+
kx.plot(df.value, spec='box', by=df.group) # one box per group (also ridge, violin, qq)
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
| Token | Values |
|
|
46
|
+
|-------|-----------------------------------------------------------------------------------------------|
|
|
47
|
+
| kind | `line` `step` `area` `band` `scatter` `bar` `barh` `hist` `kde` `ridge` `ecdf` `box` `violin` |
|
|
48
|
+
| | `strip` `qq` |
|
|
49
|
+
| theme | `dark` `light` `paper` `science` `talk` `poster` `thesis` |
|
|
50
|
+
| flags | `grid` `leg` `legout` `tight` `rot` `logx` `logy` `logxy` `symlogy` `zero` `eq` `pct` `si` |
|
|
51
|
+
| | per kind: `stack` `norm` `cum` `date` `mk` `sort` `ann` `mean` `median` `nocb` `sym` `logc` |
|
|
52
|
+
|
|
53
|
+
`stack` works with `area`, `bar`, `barh` and `hist`. `norm` is a 100% stack for `area` and a
|
|
54
|
+
density (area 1) for `hist`. `cum` makes `hist` cumulative; `hist-norm-cum` is the CDF.
|
|
55
|
+
`hist` puts every series on the same bins, so the bars line up.
|
|
56
|
+
|
|
57
|
+
Unknown tokens raise an error instead of being guessed, with the closest valid tokens as a hint.
|
|
58
|
+
Everything is inspectable: `kx.grammar()`, `kx.grammar('area')`, `kx.parse('leg-scatter')`, `kx.show('dark')`,
|
|
59
|
+
`kx.source('scatter')`.
|
|
60
|
+
|
|
61
|
+
rcParams can be overridden in `kx.use` with `__` for dots: `kx.use('dark', figure__figsize=(8, 4))`.
|
|
62
|
+
|
|
63
|
+
Every kind, option, flag and config, with its output, is in the
|
|
64
|
+
[Example Usage notebook](https://github.com/vhrabar/kx-plot/blob/main/Example%20Usage.ipynb).
|
|
65
|
+
|
|
66
|
+
## Palettes
|
|
67
|
+
|
|
68
|
+
Palettes for `kx.use(theme, palette=...)`, they swap only the colours; a theme's
|
|
69
|
+
other cycled properties (such as `paper`'s linestyles) stay.
|
|
70
|
+
|
|
71
|
+
| Name | Source |
|
|
72
|
+
|------------------------------------------|--------------------|
|
|
73
|
+
| `okabe` | Okabe & Ito (2008) |
|
|
74
|
+
| `tolbright` `tolvibrant` `tollight` | Paul Tol |
|
|
75
|
+
| `tolhc` `tolmc` | Paul Tol |
|
|
76
|
+
| `petroff6` `petroff8` `petroff10` | Petroff (2021) |
|
|
77
|
+
| `tab10` `tab20` `tableaucb` | Tableau |
|
|
78
|
+
| `set1` `set2` `dark2` `paired` | ColorBrewer |
|
|
79
|
+
| `ibm` | IBM Design Colors |
|
|
80
|
+
|
|
81
|
+
`kx.palette('okabe')` returns the hex codes. A list of colours works too: `palette=['#264653', '#e9c46a']`.
|
|
82
|
+
|
|
83
|
+
## Colourmaps
|
|
84
|
+
|
|
85
|
+
Colourmaps for `kx.use(theme, cmap=...)` colour continuous values, such as a numeric `z` in `scatter`.
|
|
86
|
+
Without `cmap`, the theme's own default applies.
|
|
87
|
+
Add `_r` to any name to reverse it, e.g. `cmap="thermal_r"`.
|
|
88
|
+
|
|
89
|
+
| Name | Type |
|
|
90
|
+
|------------------------------------------------|----------------------------------|
|
|
91
|
+
| `viridis` `magma` `plasma` `inferno` `cividis` | Sequential, perceptually uniform |
|
|
92
|
+
| `turbo` | Sequential, rainbow |
|
|
93
|
+
| `coolwarm` | Diverging |
|
|
94
|
+
| `berlin` `managua` `vanimo` | Diverging, dark centre |
|
|
95
|
+
| `twilight` | Cyclic, for angles and phases |
|
|
96
|
+
| `thermal` `haline` `deep` | Sequential, cmocean (vendored) |
|
|
97
|
+
| `balance` | Diverging, cmocean (vendored) |
|
|
98
|
+
| `batlow` `lipari` `hawaii` `oslo` `davos` | Sequential, Crameri (vendored) |
|
|
99
|
+
| `vik` `roma` `bam` `cork` | Diverging, Crameri (vendored) |
|
|
100
|
+
| `romaO` | Cyclic, Crameri (vendored) |
|
|
101
|
+
|
|
102
|
+
`kx.cmaps()` lists the ones that are available in the installed matplotlib as those implemented in matplotlib 3.10 or newer
|
|
103
|
+
are not vendored.
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
## License
|
|
107
|
+
|
|
108
|
+
Released under the MIT License. See [`LICENSE`](https://github.com/vhrabar/kx-plot/blob/main/LICENSE).
|
|
109
|
+
|
|
110
|
+
Copyright © 2026 Vedran Hrabar
|
|
111
|
+
|
|
112
|
+
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)
|
|
113
|
+
and [`kx/styles/cmaps/LICENCES.md`](https://github.com/vhrabar/kx-plot/blob/main/kx/styles/cmaps/LICENCES.md).
|
|
@@ -2,13 +2,20 @@
|
|
|
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 | ridge | ecdf | box | violin | strip
|
|
6
|
+
| qq
|
|
6
7
|
theme : any file name in styles/
|
|
7
|
-
flags : grid | leg | logx | logy |
|
|
8
|
+
flags : grid | leg | legout | tight | rot | logx | logy | logxy | symlogy | zero | eq | pct | si
|
|
9
|
+
and per kind: stack norm cum (bars, area, hist), date mk (lines), sort ann (bars),
|
|
10
|
+
mean median ann (distributions), nocb sym logc (scatter). kx.grammar(kind) lists them.
|
|
11
|
+
by= : group labels for x, one series per group (kde, ridge, ecdf, box, violin, strip, qq)
|
|
8
12
|
|
|
9
13
|
Palettes (kx.use(theme, palette="okabe")): any file name in styles/palettes/
|
|
10
14
|
Colormaps (kx.use(theme, cmap="magma")): kx.cmaps()
|
|
11
|
-
kx.
|
|
15
|
+
with kx.context(theme, ...): the same as kx.use, for one block only.
|
|
16
|
+
kx.save("fig.png"): saves to /kaggle/working on Kaggle, the current folder elsewhere.
|
|
17
|
+
kx.grid(5): a figure of 5 panels as a flat array of axes, for kx.plot(..., ax=).
|
|
18
|
+
kx.grammar("area") and kx.source("area") explain one kind; kx.parse(spec) shows how a spec is read.
|
|
12
19
|
"""
|
|
13
20
|
import glob
|
|
14
21
|
import importlib.metadata
|
|
@@ -17,13 +24,14 @@ import os
|
|
|
17
24
|
import re
|
|
18
25
|
|
|
19
26
|
from ._data import datasets, load
|
|
27
|
+
from ._grid import grid
|
|
20
28
|
from ._plot import plot
|
|
21
|
-
from .
|
|
22
|
-
from ._spec import
|
|
23
|
-
from ._theme import BUILTIN_CMAPS, cmaps, palette, palettes, show, styles, use
|
|
29
|
+
from ._save import save
|
|
30
|
+
from ._spec import COMMON_FLAGS, KINDS, Spec, all_flags, parse
|
|
31
|
+
from ._theme import BUILTIN_CMAPS, VENDORED_CMAPS, cmaps, context, palette, palettes, show, styles, use
|
|
24
32
|
|
|
25
|
-
__all__ = ["BUILTIN_CMAPS", "
|
|
26
|
-
"show", "source", "styles", "use"]
|
|
33
|
+
__all__ = ["BUILTIN_CMAPS", "VENDORED_CMAPS", "Spec", "__version__", "cmaps", "context", "datasets", "grammar",
|
|
34
|
+
"grid", "load", "palette", "palettes", "parse", "plot", "save", "show", "source", "styles", "use"]
|
|
27
35
|
|
|
28
36
|
|
|
29
37
|
def _version() -> str:
|
|
@@ -57,6 +65,8 @@ def grammar(kind: str | None = None) -> None:
|
|
|
57
65
|
k = _kind(kind)
|
|
58
66
|
print(f"{k.name}: {inspect.getdoc(k.draw)}")
|
|
59
67
|
print("flags:", sorted(COMMON_FLAGS), "+", sorted(k.flags) or "none of its own")
|
|
68
|
+
if k.takes_by:
|
|
69
|
+
print("by= : group labels for x, one per group")
|
|
60
70
|
return
|
|
61
71
|
print("kind :", sorted(KINDS))
|
|
62
72
|
print("theme:", styles())
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""kx.grid: a figure of panels as one flat array of axes."""
|
|
2
|
+
import math
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
import matplotlib.pyplot as plt
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def grid(n: int, cols: int = 3, **kw: Any) -> np.ndarray:
|
|
10
|
+
"""A figure with n panels, `cols` per row, as a flat array of n axes: for ax in kx.grid(5): ...
|
|
11
|
+
|
|
12
|
+
Each panel gets the theme's figure.figsize, so panels look like single plots. Cells past n in the
|
|
13
|
+
last row are removed. Other keywords go to plt.subplots (sharex=True, figsize=..., layout=...).
|
|
14
|
+
The figure is axs[0].figure.
|
|
15
|
+
"""
|
|
16
|
+
if n < 1 or cols < 1:
|
|
17
|
+
raise ValueError(f"kx.grid needs n >= 1 and cols >= 1, got n={n}, cols={cols}")
|
|
18
|
+
cols = min(cols, n)
|
|
19
|
+
rows = math.ceil(n / cols)
|
|
20
|
+
w, h = plt.rcParams["figure.figsize"]
|
|
21
|
+
kw = {"figsize": (cols * w, rows * h), "layout": "constrained", **kw} # constrained: room for colorbars
|
|
22
|
+
fig, axs = plt.subplots(rows, cols, squeeze=False, **kw)
|
|
23
|
+
for ax in axs.flat[n:]:
|
|
24
|
+
fig.delaxes(ax)
|
|
25
|
+
return axs.flat[:n]
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""kx.plot: the one-liner. Kinds live in kx/kinds/; this file checks input and applies common flags."""
|
|
2
|
+
import contextlib
|
|
3
|
+
import difflib
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
import matplotlib as mpl
|
|
7
|
+
import matplotlib.dates as mdates
|
|
8
|
+
import matplotlib.pyplot as plt
|
|
9
|
+
import pandas as pd
|
|
10
|
+
from matplotlib.axes import Axes
|
|
11
|
+
from matplotlib.layout_engine import ConstrainedLayoutEngine
|
|
12
|
+
from numpy.typing import ArrayLike
|
|
13
|
+
|
|
14
|
+
from . import kinds # noqa: F401 (registers every kind)
|
|
15
|
+
from ._spec import KINDS, Spec, parse
|
|
16
|
+
from ._theme import style_path
|
|
17
|
+
|
|
18
|
+
OUTSIDE = {"loc": "center left", "bbox_to_anchor": (1, 0.5)} # legend right of the axes
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def plot(*data: ArrayLike | pd.DataFrame | str, spec: str | Spec | None = None, title: str | None = None,
|
|
22
|
+
ax: Axes | None = None, by: ArrayLike | str | None = None, **kwargs: Any) -> Axes:
|
|
23
|
+
"""kx.plot(x, y, z, 'scatter-dark-grid-leg') or kx.plot(x, y, 'bar-light')
|
|
24
|
+
kx.plot(df, 'month', 'y2025', 'y2026', 'bar') names columns of a DataFrame.
|
|
25
|
+
|
|
26
|
+
Up to three arrays x, y, z, then the spec (or spec=). by= gives a group label per x value,
|
|
27
|
+
one curve, box or violin per group: kx.plot(df, 'value', spec='kde', by='group').
|
|
28
|
+
Other keywords go to the kind's matplotlib call and win over kx's defaults:
|
|
29
|
+
kx.plot(x, y, 'line', linewidth=3), kx.plot(x, spec='hist', bins=50). kx.grammar(kind) says which call.
|
|
30
|
+
|
|
31
|
+
A theme in the spec applies to this plot only; kx.use() sets the notebook default.
|
|
32
|
+
"""
|
|
33
|
+
x, y, z, spec, by = _arrays(data, spec, by)
|
|
34
|
+
name, theme, flags = parse(spec or "line")
|
|
35
|
+
kind = KINDS[name]
|
|
36
|
+
if kind.needs_y and y is None:
|
|
37
|
+
raise ValueError(f"kind {name!r} needs both x and y")
|
|
38
|
+
if by is not None and not kind.takes_by:
|
|
39
|
+
raise ValueError(f"by= only works with kind {sorted(k.name for k in KINDS.values() if k.takes_by)}, "
|
|
40
|
+
f"not {name!r}")
|
|
41
|
+
if kind.check:
|
|
42
|
+
kind.check(y, z, flags)
|
|
43
|
+
if "date" in flags: # strings and numbers become dates; a Series keeps its name
|
|
44
|
+
x = pd.to_datetime(x)
|
|
45
|
+
|
|
46
|
+
style = plt.style.context(["default", style_path(theme)]) if theme else contextlib.nullcontext()
|
|
47
|
+
with style:
|
|
48
|
+
ax = ax or plt.subplots()[1]
|
|
49
|
+
kind.draw(ax, x, y, z, flags, **({"by": by} if by is not None else {}), **kwargs)
|
|
50
|
+
_common(ax, name, kind.value_axis, flags)
|
|
51
|
+
if title: ax.set_title(title)
|
|
52
|
+
if "tight" in flags and not isinstance(ax.figure.get_layout_engine(), ConstrainedLayoutEngine):
|
|
53
|
+
ax.figure.tight_layout() # a constrained figure (kx.grid) is laid out already
|
|
54
|
+
return ax
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _arrays(data: tuple, spec: str | Spec | None, by: ArrayLike | str | None) -> tuple:
|
|
58
|
+
"""(x, y, z, spec, by) from kx.plot's positional arguments: arrays, or a DataFrame and column names."""
|
|
59
|
+
data = list(data)
|
|
60
|
+
df = data.pop(0) if data and isinstance(data[0], pd.DataFrame) else None
|
|
61
|
+
last = data[-1] if data else None
|
|
62
|
+
if isinstance(last, Spec) or (isinstance(last, str) and (df is None or last not in df.columns)):
|
|
63
|
+
if spec is not None: # a trailing string that is not a column is the spec
|
|
64
|
+
raise TypeError(f"spec given twice ({data[-1]!r} and spec={spec!r})")
|
|
65
|
+
if df is not None and isinstance(last, str): # not a spec either, but close to a column: a typo
|
|
66
|
+
try:
|
|
67
|
+
parse(data[-1])
|
|
68
|
+
except ValueError:
|
|
69
|
+
if difflib.get_close_matches(data[-1], [str(c) for c in df.columns]):
|
|
70
|
+
_column(df, data[-1])
|
|
71
|
+
raise
|
|
72
|
+
spec = data.pop()
|
|
73
|
+
if df is not None:
|
|
74
|
+
if not data:
|
|
75
|
+
raise TypeError("kx.plot(df, ...) needs the column names to plot: kx.plot(df, 'x', 'y')")
|
|
76
|
+
data = [_column(df, c) for c in data]
|
|
77
|
+
by = _column(df, by) if isinstance(by, str) else by
|
|
78
|
+
elif isinstance(by, str):
|
|
79
|
+
raise TypeError(f"by={by!r} names a column, which needs a DataFrame first: kx.plot(df, 'x', by={by!r})")
|
|
80
|
+
if not 1 <= len(data) <= 3:
|
|
81
|
+
raise TypeError(f"kx.plot takes x, y and z: up to 3 arrays, got {len(data)}")
|
|
82
|
+
return *data, *[None] * (3 - len(data)), spec, by
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _column(df: pd.DataFrame, name: object) -> pd.Series:
|
|
86
|
+
"""df[name], or an error naming the columns that are close."""
|
|
87
|
+
if not isinstance(name, str):
|
|
88
|
+
raise TypeError(f"after a DataFrame, give column names, not {type(name).__name__}")
|
|
89
|
+
if name not in df.columns:
|
|
90
|
+
close = difflib.get_close_matches(name, [str(c) for c in df.columns], n=3)
|
|
91
|
+
hint = f" Did you mean {close}?" if close else f" Columns: {list(df.columns)}"
|
|
92
|
+
raise ValueError(f"no column {name!r} in the DataFrame.{hint}")
|
|
93
|
+
return df[name]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _common(ax: Axes, name: str, value_axis: str, flags: set[str]) -> None:
|
|
97
|
+
"""Flags every kind takes: legend, scales, value-axis format, ticks."""
|
|
98
|
+
values = ax.xaxis if value_axis == "x" else ax.yaxis
|
|
99
|
+
if "grid" in flags: ax.grid(True)
|
|
100
|
+
if flags & {"leg", "legout"} and ax.get_legend_handles_labels()[0]: # nothing labelled (scatter z): none
|
|
101
|
+
old = ax.get_legend()
|
|
102
|
+
outside = "legout" in flags or (name == "area" and "norm" in flags) # a 100% stack has no free corner
|
|
103
|
+
if old is None or outside: # moving a kind's own legend keeps its title
|
|
104
|
+
ax.legend(title=old.get_title().get_text() if old else None, **(OUTSIDE if outside else {}))
|
|
105
|
+
if flags & {"logx", "logxy"}: ax.set_xscale("log")
|
|
106
|
+
if flags & {"logy", "logxy"}: ax.set_yscale("log")
|
|
107
|
+
if "symlogy" in flags: ax.set_yscale("symlog")
|
|
108
|
+
if "zero" in flags: # stretch the value axis to include 0
|
|
109
|
+
lo, hi = values.get_view_interval()
|
|
110
|
+
(ax.set_xlim if value_axis == "x" else ax.set_ylim)(min(lo, 0), max(hi, 0))
|
|
111
|
+
if "eq" in flags: ax.set_aspect("equal")
|
|
112
|
+
if "pct" in flags and not isinstance(values.get_major_formatter(), mpl.ticker.PercentFormatter):
|
|
113
|
+
values.set_major_formatter(mpl.ticker.PercentFormatter(1)) # 0.25 -> 25%; area-norm is already %
|
|
114
|
+
if "si" in flags: values.set_major_formatter(mpl.ticker.EngFormatter(sep="")) # 1500 -> 1.5k
|
|
115
|
+
if "date" in flags:
|
|
116
|
+
loc = mdates.AutoDateLocator()
|
|
117
|
+
ax.xaxis.set_major_locator(loc)
|
|
118
|
+
ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(loc))
|
|
119
|
+
if "rot" in flags: # rotation stays for ticks matplotlib adds later
|
|
120
|
+
ax.tick_params(axis="x", labelrotation=45)
|
|
121
|
+
plt.setp(ax.get_xticklabels(), ha="right", rotation_mode="anchor")
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""kx.save: savefig that knows where Kaggle keeps files."""
|
|
2
|
+
import os
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
import matplotlib.pyplot as plt
|
|
6
|
+
from matplotlib.axes import Axes
|
|
7
|
+
from matplotlib.figure import Figure
|
|
8
|
+
|
|
9
|
+
KAGGLE = "/kaggle/working"
|
|
10
|
+
|
|
11
|
+
def save(name: str, fig: Figure | Axes | None = None, **kw: Any) -> str:
|
|
12
|
+
"""Save fig (or ax.figure, or the current figure) as `name` and return the path written.
|
|
13
|
+
|
|
14
|
+
A relative name goes to /kaggle/working on Kaggle and to the current folder elsewhere; missing folders
|
|
15
|
+
are created. Without an extension the theme's savefig.format is used (thesis: PDF). Other keywords
|
|
16
|
+
go to savefig. Call it before plt.show(), which leaves a new empty current figure, or pass ax / fig.
|
|
17
|
+
"""
|
|
18
|
+
fig = plt.gcf() if fig is None else fig.figure if isinstance(fig, Axes) else fig
|
|
19
|
+
path = os.path.expanduser(name)
|
|
20
|
+
if not os.path.isabs(path) and os.path.isdir(KAGGLE):
|
|
21
|
+
path = os.path.join(KAGGLE, path)
|
|
22
|
+
if not os.path.splitext(path)[1]:
|
|
23
|
+
path += "." + (kw.get("format") or plt.rcParams["savefig.format"])
|
|
24
|
+
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
|
|
25
|
+
fig.savefig(path, **kw)
|
|
26
|
+
return path
|