kx-plot 0.2.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.2.0 → kx_plot-0.3.0}/CHANGELOG.md +58 -1
- {kx_plot-0.2.0 → kx_plot-0.3.0}/PKG-INFO +19 -10
- {kx_plot-0.2.0 → kx_plot-0.3.0}/README.md +18 -9
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/__init__.py +16 -10
- 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.2.0 → kx_plot-0.3.0}/kx/_theme.py +13 -1
- 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.2.0 → kx_plot-0.3.0}/pyproject.toml +1 -1
- {kx_plot-0.2.0 → kx_plot-0.3.0}/tests/test_kx.py +396 -6
- kx_plot-0.2.0/kx/_plot.py +0 -50
- kx_plot-0.2.0/kx/_spec.py +0 -58
- kx_plot-0.2.0/kx/kinds/basic.py +0 -104
- kx_plot-0.2.0/kx/kinds/dist.py +0 -151
- {kx_plot-0.2.0 → kx_plot-0.3.0}/.gitignore +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/LICENSE +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/_data.py +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/_files.py +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/_util.py +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/data/cloud.csv +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/data/dists.csv +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/data/monthly.csv +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/data/waves.csv +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/kinds/__init__.py +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/cmaps/LICENCES.md +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/cmaps/balance.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/cmaps/bam.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/cmaps/batlow.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/cmaps/cork.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/cmaps/davos.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/cmaps/deep.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/cmaps/haline.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/cmaps/hawaii.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/cmaps/lipari.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/cmaps/oslo.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/cmaps/roma.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/cmaps/romaO.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/cmaps/thermal.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/cmaps/vik.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/dark.mplstyle +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/light.mplstyle +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/palettes/LICENCES.md +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/palettes/dark2.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/palettes/ibm.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/palettes/okabe.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/palettes/paired.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/palettes/petroff10.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/palettes/petroff6.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/palettes/petroff8.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/palettes/set1.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/palettes/set2.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/palettes/tab10.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/palettes/tab20.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/palettes/tableaucb.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/palettes/tolbright.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/palettes/tolhc.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/palettes/tollight.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/palettes/tolmc.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/palettes/tolvibrant.txt +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/paper.mplstyle +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/poster.mplstyle +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/science.mplstyle +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/talk.mplstyle +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/kx/styles/thesis.mplstyle +0 -0
- {kx_plot-0.2.0 → kx_plot-0.3.0}/tests/conftest.py +0 -0
|
@@ -6,6 +6,62 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
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
|
+
|
|
9
65
|
## [0.2.0] - 2026-10-09
|
|
10
66
|
|
|
11
67
|
### Added
|
|
@@ -102,7 +158,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
|
102
158
|
- `kx.use`, `kx.show`, `kx.source`, `kx.grammar`, `kx.load` and the demo CSVs
|
|
103
159
|
- a workflow that publishes the dataset to Kaggle
|
|
104
160
|
|
|
105
|
-
[Unreleased]: https://github.com/vhrabar/kx-plot/compare/v0.
|
|
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
|
|
106
163
|
[0.2.0]: https://github.com/vhrabar/kx-plot/compare/v0.1.0...v0.2.0
|
|
107
164
|
[0.1.0]: https://github.com/vhrabar/kx-plot/compare/v0.0.2...v0.1.0
|
|
108
165
|
[0.0.2]: https://github.com/vhrabar/kx-plot/compare/v0.0.1...v0.0.2
|
|
@@ -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
|
|
@@ -60,22 +60,31 @@ import kx; kx.use('dark')
|
|
|
60
60
|
kx.use('light', palette='okabe', cmap='cividis') # notebook default: theme, palette, colormap
|
|
61
61
|
kx.plot(x, y, z, 'scatter-grid-leg') # spec: kind-theme-flag-...
|
|
62
62
|
kx.plot(x, y, 'bar-paper') # a theme in the spec applies to this plot only
|
|
63
|
-
kx.
|
|
64
|
-
kx.
|
|
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)
|
|
65
71
|
```
|
|
66
72
|
|
|
67
|
-
| Token | Values
|
|
68
|
-
|
|
69
|
-
| kind | `line` `step` `area` `band` `scatter` `bar` `barh` `hist` `kde` `ecdf` `box` `violin` |
|
|
70
|
-
|
|
|
71
|
-
|
|
|
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` |
|
|
72
80
|
|
|
73
81
|
`stack` works with `area`, `bar`, `barh` and `hist`. `norm` is a 100% stack for `area` and a
|
|
74
82
|
density (area 1) for `hist`. `cum` makes `hist` cumulative; `hist-norm-cum` is the CDF.
|
|
75
83
|
`hist` puts every series on the same bins, so the bars line up.
|
|
76
84
|
|
|
77
|
-
Unknown tokens raise an error instead of being guessed
|
|
78
|
-
`kx.grammar()`, `kx.grammar('area')`, `kx.
|
|
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')`.
|
|
79
88
|
|
|
80
89
|
rcParams can be overridden in `kx.use` with `__` for dots: `kx.use('dark', figure__figsize=(8, 4))`.
|
|
81
90
|
|
|
@@ -32,22 +32,31 @@ 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.
|
|
36
|
-
kx.
|
|
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)
|
|
37
43
|
```
|
|
38
44
|
|
|
39
|
-
| Token | Values
|
|
40
|
-
|
|
41
|
-
| kind | `line` `step` `area` `band` `scatter` `bar` `barh` `hist` `kde` `ecdf` `box` `violin` |
|
|
42
|
-
|
|
|
43
|
-
|
|
|
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` |
|
|
44
52
|
|
|
45
53
|
`stack` works with `area`, `bar`, `barh` and `hist`. `norm` is a 100% stack for `area` and a
|
|
46
54
|
density (area 1) for `hist`. `cum` makes `hist` cumulative; `hist-norm-cum` is the CDF.
|
|
47
55
|
`hist` puts every series on the same bins, so the bars line up.
|
|
48
56
|
|
|
49
|
-
Unknown tokens raise an error instead of being guessed
|
|
50
|
-
`kx.grammar()`, `kx.grammar('area')`, `kx.
|
|
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')`.
|
|
51
60
|
|
|
52
61
|
rcParams can be overridden in `kx.use` with `__` for dots: `kx.use('dark', figure__figsize=(8, 4))`.
|
|
53
62
|
|
|
@@ -2,15 +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 | barh | hist | kde | ecdf | box | violin
|
|
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
|
-
|
|
9
|
-
|
|
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)
|
|
10
12
|
|
|
11
13
|
Palettes (kx.use(theme, palette="okabe")): any file name in styles/palettes/
|
|
12
14
|
Colormaps (kx.use(theme, cmap="magma")): kx.cmaps()
|
|
13
|
-
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.
|
|
14
19
|
"""
|
|
15
20
|
import glob
|
|
16
21
|
import importlib.metadata
|
|
@@ -19,13 +24,14 @@ import os
|
|
|
19
24
|
import re
|
|
20
25
|
|
|
21
26
|
from ._data import datasets, load
|
|
27
|
+
from ._grid import grid
|
|
22
28
|
from ._plot import plot
|
|
23
|
-
from .
|
|
24
|
-
from ._spec import
|
|
25
|
-
from ._theme import BUILTIN_CMAPS, VENDORED_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
|
|
26
32
|
|
|
27
|
-
__all__ = ["BUILTIN_CMAPS", "VENDORED_CMAPS", "
|
|
28
|
-
"palettes", "plot", "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"]
|
|
29
35
|
|
|
30
36
|
|
|
31
37
|
def _version() -> str:
|
|
@@ -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
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Spec grammar (kind-theme-flag-flag-...) and the registry of kinds."""
|
|
2
|
+
import difflib
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Any, NamedTuple
|
|
6
|
+
|
|
7
|
+
from ._theme import styles
|
|
8
|
+
|
|
9
|
+
COMMON_FLAGS = {"grid", "leg", "legout", "tight", "rot", # handled by kx.plot for every kind
|
|
10
|
+
"logx", "logy", "logxy", "symlogy", "zero", "eq", "pct", "si"}
|
|
11
|
+
EXCLUSIVE = ({"logy", "logxy", "symlogy"}, {"logx", "logxy"}, {"zero", "logy"}, {"zero", "logxy"},
|
|
12
|
+
{"pct", "si"}, {"sym", "logc"}) # pairs that ask for opposite things
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class Kind:
|
|
17
|
+
"""A plot kind: draw(ax, x, y, z, flags) plus what kx.plot checks before drawing."""
|
|
18
|
+
name: str
|
|
19
|
+
draw: Callable[..., None]
|
|
20
|
+
flags: frozenset[str] # kind-specific flags, on top of COMMON_FLAGS
|
|
21
|
+
needs_y: bool
|
|
22
|
+
check: Callable[[Any, Any, set[str]], None] | None # check(y, z, flags) raises on bad input
|
|
23
|
+
takes_by: bool = False # draw also gets by= (group labels for x)
|
|
24
|
+
value_axis: str = "y" # where pct, si and zero apply: "x" for barh
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
KINDS: dict[str, Kind] = {}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def kind(name: str, flags: tuple[str, ...] = (), needs_y: bool = True,
|
|
31
|
+
check: Callable[[Any, Any, set[str]], None] | None = None, takes_by: bool = False,
|
|
32
|
+
value_axis: str = "y") -> Callable:
|
|
33
|
+
"""Decorator that registers a draw function as kind `name`."""
|
|
34
|
+
def register(draw: Callable[..., None]) -> Callable[..., None]:
|
|
35
|
+
if name in KINDS or name in COMMON_FLAGS or "-" in name:
|
|
36
|
+
raise ValueError(f"kind name {name!r} is taken or has a '-'")
|
|
37
|
+
KINDS[name] = Kind(name, draw, frozenset(flags), needs_y, check, takes_by, value_axis)
|
|
38
|
+
return draw
|
|
39
|
+
return register
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def all_flags() -> set[str]:
|
|
43
|
+
"""Common flags and every kind-specific flag."""
|
|
44
|
+
return COMMON_FLAGS.union(*(k.flags for k in KINDS.values()))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Spec(NamedTuple):
|
|
48
|
+
"""A parsed spec. Unpacks as kind, theme, flags; str() gives the canonical slug."""
|
|
49
|
+
kind: str
|
|
50
|
+
theme: str | None
|
|
51
|
+
flags: frozenset[str]
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def slug(self) -> str:
|
|
55
|
+
"""kind, theme, then flags in alphabetical order: the same plot always gets the same string."""
|
|
56
|
+
return "-".join([self.kind, *([self.theme] if self.theme else []), *sorted(self.flags)])
|
|
57
|
+
|
|
58
|
+
def __str__(self) -> str:
|
|
59
|
+
return self.slug
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def parse(spec: str | Spec) -> Spec:
|
|
63
|
+
"""Split 'kind-theme-flag-...' into Spec(kind, theme, flags). Strict: no guessing, but hints."""
|
|
64
|
+
if isinstance(spec, Spec):
|
|
65
|
+
return spec
|
|
66
|
+
toks = spec.split("-")
|
|
67
|
+
themes, flags = set(styles()), all_flags()
|
|
68
|
+
valid = KINDS.keys() | flags | themes
|
|
69
|
+
unknown = [t for t in toks if t not in valid]
|
|
70
|
+
if unknown:
|
|
71
|
+
hints = [" or ".join(map(repr, sorted(close))) + f" for {t!r}"
|
|
72
|
+
for t in unknown if (close := difflib.get_close_matches(t, valid, n=2))]
|
|
73
|
+
hint = f" Did you mean {', '.join(hints)}?" if hints else ""
|
|
74
|
+
if "" in unknown:
|
|
75
|
+
hint += " An empty token means a '-' too many."
|
|
76
|
+
raise ValueError(f"unknown tokens: {unknown}.{hint} Run kx.grammar() to see valid ones.")
|
|
77
|
+
kinds = [t for t in toks if t in KINDS]
|
|
78
|
+
picked = [t for t in toks if t in themes]
|
|
79
|
+
if len(kinds) > 1:
|
|
80
|
+
raise ValueError(f"spec {spec!r} has more than one kind: {kinds}")
|
|
81
|
+
if len(picked) > 1:
|
|
82
|
+
raise ValueError(f"spec {spec!r} has more than one theme: {picked}")
|
|
83
|
+
kind = (kinds or ["line"])[0]
|
|
84
|
+
for flag in sorted(set(toks) & (flags - COMMON_FLAGS - KINDS[kind].flags)):
|
|
85
|
+
owners = sorted(k.name for k in KINDS.values() if flag in k.flags)
|
|
86
|
+
raise ValueError(f"flag {flag!r} only works with kind {owners}, not {kind!r}")
|
|
87
|
+
for group in EXCLUSIVE:
|
|
88
|
+
if len(both := sorted(group & set(toks))) > 1:
|
|
89
|
+
raise ValueError(f"flags {both} do not go together; pick one")
|
|
90
|
+
return Spec(kind, (picked or [None])[0], frozenset(toks) & flags)
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
"""Themes, palettes and colormaps: discovery and kx.
|
|
1
|
+
"""Themes, palettes and colormaps: discovery, kx.use and kx.context."""
|
|
2
|
+
import contextlib
|
|
3
|
+
from collections.abc import Iterator
|
|
2
4
|
from typing import Any
|
|
3
5
|
|
|
4
6
|
import matplotlib as mpl
|
|
@@ -92,3 +94,13 @@ def use(name: str = "dark", palette: str | list[str] | None = None, cmap: str |
|
|
|
92
94
|
plt.rcParams["axes.prop_cycle"] = plt.cycler(
|
|
93
95
|
color=colors, **{k: [v[i % len(v)] for i in range(len(colors))] for k, v in rest.items()})
|
|
94
96
|
plt.rcParams.update({k.replace("__", "."): v for k, v in rc.items()})
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@contextlib.contextmanager
|
|
100
|
+
def context(name: str = "dark", palette: str | list[str] | None = None, cmap: str | None = None,
|
|
101
|
+
**rc: Any) -> Iterator[None]:
|
|
102
|
+
"""kx.use for one with block: with kx.context('paper', palette='okabe'): ...
|
|
103
|
+
Same arguments as kx.use; the previous rcParams come back on exit, also after an error."""
|
|
104
|
+
with mpl.rc_context():
|
|
105
|
+
use(name, palette, cmap, **rc)
|
|
106
|
+
yield
|