kx-plot 0.3.0__tar.gz → 0.4.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 → kx_plot-0.4.0}/CHANGELOG.md +38 -1
- {kx_plot-0.3.0 → kx_plot-0.4.0}/PKG-INFO +24 -4
- {kx_plot-0.3.0 → kx_plot-0.4.0}/README.md +23 -3
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/__init__.py +26 -8
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/_plot.py +30 -1
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/_spec.py +6 -5
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/_theme.py +11 -2
- kx_plot-0.4.0/kx/_util.py +46 -0
- kx_plot-0.4.0/kx/data/passengers.csv +501 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/kinds/__init__.py +1 -1
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/kinds/basic.py +70 -39
- kx_plot-0.4.0/kx/kinds/table.py +130 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/pyproject.toml +1 -1
- {kx_plot-0.3.0 → kx_plot-0.4.0}/tests/test_kx.py +396 -5
- kx_plot-0.3.0/kx/_util.py +0 -22
- {kx_plot-0.3.0 → kx_plot-0.4.0}/.gitignore +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/LICENSE +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/_data.py +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/_files.py +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/_grid.py +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/_save.py +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/data/cloud.csv +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/data/daily.csv +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/data/dists.csv +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/data/monthly.csv +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/data/waves.csv +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/kinds/dist.py +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/cmaps/LICENCES.md +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/cmaps/balance.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/cmaps/bam.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/cmaps/batlow.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/cmaps/cork.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/cmaps/davos.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/cmaps/deep.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/cmaps/haline.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/cmaps/hawaii.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/cmaps/lipari.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/cmaps/oslo.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/cmaps/roma.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/cmaps/romaO.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/cmaps/thermal.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/cmaps/vik.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/dark.mplstyle +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/light.mplstyle +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/palettes/LICENCES.md +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/palettes/dark2.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/palettes/ibm.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/palettes/okabe.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/palettes/paired.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/palettes/petroff10.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/palettes/petroff6.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/palettes/petroff8.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/palettes/set1.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/palettes/set2.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/palettes/tab10.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/palettes/tab20.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/palettes/tableaucb.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/palettes/tolbright.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/palettes/tolhc.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/palettes/tollight.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/palettes/tolmc.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/palettes/tolvibrant.txt +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/paper.mplstyle +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/poster.mplstyle +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/science.mplstyle +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/talk.mplstyle +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/kx/styles/thesis.mplstyle +0 -0
- {kx_plot-0.3.0 → kx_plot-0.4.0}/tests/conftest.py +0 -0
|
@@ -6,6 +6,42 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [0.4.0] - 2026-10-18
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- **Plot kind** `heat`: a DataFrame or 2-D array as coloured cells, columns along x and index labels down y.
|
|
14
|
+
`corr` draws the correlations of the numeric columns on `rdbu` from -1 to 1, and `ann` writes each cell's value
|
|
15
|
+
in black or white, whichever reads on that cell. Takes `nocb`, `sym` and `logc` like `scatter`.
|
|
16
|
+
- **Plot kind** `crosstab`: how often each pair of categories occurs, as a heat map with `x` along the x axis and
|
|
17
|
+
`y` down the y axis: `kx.plot(df, 'sex', 'pclass', 'crosstab-ann')`. `norm` shows shares within each `x`
|
|
18
|
+
category (each column sums to 100%), and `logc` leaves pairs that never occur blank.
|
|
19
|
+
- **Plot kind** `count`: how often each category of `x` occurs, with missing values as their own `NaN` bar.
|
|
20
|
+
`by=` splits each bar into one per group (`kx.plot(df, 'pclass', spec='count', by='survived')`). `stack` puts the
|
|
21
|
+
groups on top of each other, `sort` puts the most common first and `ann` writes the counts. `norm` shows shares:
|
|
22
|
+
within each category with `by=` and `stack`, and within each group otherwise.
|
|
23
|
+
- **Plot kind** `missing`: the share of missing values in each column of a DataFrame, as bars lying down with
|
|
24
|
+
the most missing on top: `kx.plot(df, 'missing-ann')`. Columns without missing values show only with `all`,
|
|
25
|
+
and a frame with none shows "no missing values" instead of raising.
|
|
26
|
+
- **Plot kind** `nullmap`: where the missing values are, one row of the image per row of the table and the
|
|
27
|
+
columns along x. Missing cells are in the palette's first colour on the theme's background. `sort` puts the rows
|
|
28
|
+
with the most missing values on top and groups rows with the same gaps, so patterns show as blocks.
|
|
29
|
+
- **Plot kind** `hexbin`: how many points fall in each hexagon, or with `z` the mean of `z` there, with a
|
|
30
|
+
colorbar labelled `count` or with `z`'s name. Rows with a NaN are left out. Takes `nocb` and `logc` (`sym` with
|
|
31
|
+
`z` only), and `gridsize=` sets the number of hexagons across.
|
|
32
|
+
- `kx.missing(df)`: the same as `kx.plot(df, 'missing-ann')`. A spec adds a theme and flags,
|
|
33
|
+
`kx.missing(df, 'dark-wrap')`, and other keywords such as `title=` and `ax=` go to `kx.plot`.
|
|
34
|
+
- **Flag for every kind** `wrap`: long text tick labels break into lines of at most 12 characters at spaces,
|
|
35
|
+
on both axes. Numbers, dates and single long words are left as they are. Works together with `rot`.
|
|
36
|
+
- `kx.plot(df, spec)` and `kx.plot(matrix, spec)` hand the whole table to a table kind, with no column names. A
|
|
37
|
+
2-D array becomes a DataFrame labelled `0..n`. A table kind given columns, `y`, `z` or `by=` raises, and
|
|
38
|
+
`kx.grammar(kind)` says it takes a DataFrame or 2-D array.
|
|
39
|
+
- **Colourmaps** `blues`, `greys` and `rdbu`: lowercase names for matplotlib's ColorBrewer `Blues`, `Greys` and
|
|
40
|
+
`RdBu`, for `kx.use(cmap=...)` and in `kx.cmaps()`. `_r` reverses them like the others.
|
|
41
|
+
- **Demo dataset** `passengers`: 500 synthetic passengers (`age`, `fare`, `sex`, `pclass`, `port`, `deck`,
|
|
42
|
+
`ticket_type`, `survived`) with missing ages, decks and ports, for the table kinds: `kx.load('passengers')`.
|
|
43
|
+
It is generated by `scripts/make_passengers.py`, not taken from the Titanic data.
|
|
44
|
+
|
|
9
45
|
## [0.3.0] - 2026-10-12
|
|
10
46
|
|
|
11
47
|
### Added
|
|
@@ -158,7 +194,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
|
158
194
|
- `kx.use`, `kx.show`, `kx.source`, `kx.grammar`, `kx.load` and the demo CSVs
|
|
159
195
|
- a workflow that publishes the dataset to Kaggle
|
|
160
196
|
|
|
161
|
-
[Unreleased]: https://github.com/vhrabar/kx-plot/compare/v0.
|
|
197
|
+
[Unreleased]: https://github.com/vhrabar/kx-plot/compare/v0.4.0...HEAD
|
|
198
|
+
[0.4.0]: https://github.com/vhrabar/kx-plot/compare/v0.3.0...v0.4.0
|
|
162
199
|
[0.3.0]: https://github.com/vhrabar/kx-plot/compare/v0.2.0...v0.3.0
|
|
163
200
|
[0.2.0]: https://github.com/vhrabar/kx-plot/compare/v0.1.0...v0.2.0
|
|
164
201
|
[0.1.0]: https://github.com/vhrabar/kx-plot/compare/v0.0.2...v0.1.0
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: kx-plot
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.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
|
|
@@ -73,10 +73,11 @@ kx.plot(df.value, spec='box', by=df.group) # one box per group (also rid
|
|
|
73
73
|
| Token | Values |
|
|
74
74
|
|-------|-----------------------------------------------------------------------------------------------|
|
|
75
75
|
| kind | `line` `step` `area` `band` `scatter` `bar` `barh` `hist` `kde` `ridge` `ecdf` `box` `violin` |
|
|
76
|
-
| | `strip` `qq`
|
|
76
|
+
| | `strip` `qq` `count` `crosstab` `hexbin` `heat` `missing` `nullmap` |
|
|
77
77
|
| theme | `dark` `light` `paper` `science` `talk` `poster` `thesis` |
|
|
78
|
-
| flags | `grid` `leg` `legout` `tight` `rot` `logx` `logy` `logxy` `symlogy` `zero` `eq` `pct`
|
|
79
|
-
| | per kind: `stack` `norm` `cum` `date` `mk` `sort` `ann` `mean` `median` `nocb` `sym`
|
|
78
|
+
| flags | `grid` `leg` `legout` `tight` `rot` `wrap` `logx` `logy` `logxy` `symlogy` `zero` `eq` `pct` |
|
|
79
|
+
| | `si`; per kind: `stack` `norm` `cum` `date` `mk` `sort` `ann` `mean` `median` `nocb` `sym` |
|
|
80
|
+
| | `logc` `corr` `all` |
|
|
80
81
|
|
|
81
82
|
`stack` works with `area`, `bar`, `barh` and `hist`. `norm` is a 100% stack for `area` and a
|
|
82
83
|
density (area 1) for `hist`. `cum` makes `hist` cumulative; `hist-norm-cum` is the CDF.
|
|
@@ -86,6 +87,23 @@ Unknown tokens raise an error instead of being guessed, with the closest valid t
|
|
|
86
87
|
Everything is inspectable: `kx.grammar()`, `kx.grammar('area')`, `kx.parse('leg-scatter')`, `kx.show('dark')`,
|
|
87
88
|
`kx.source('scatter')`.
|
|
88
89
|
|
|
90
|
+
### Tables
|
|
91
|
+
|
|
92
|
+
`kx.load('passengers')` is a demo table with numbers, categories and NaNs to try these on.
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
kx.missing(df) # share of NaNs per column, the most missing on top
|
|
96
|
+
kx.plot(df, 'nullmap-sort') # where the NaNs are: one pixel row per table row
|
|
97
|
+
kx.plot(df, 'heat-corr-ann') # correlations of the numeric columns, -1 to 1
|
|
98
|
+
kx.plot(df, 'heat') # any numeric DataFrame or 2-D array as coloured cells
|
|
99
|
+
kx.plot(df, 'pclass', spec='count', by='survived') # rows per category, split by a second column
|
|
100
|
+
kx.plot(df, 'pclass', 'port', 'crosstab-norm-ann') # how often each pair of categories occurs
|
|
101
|
+
kx.plot(df, 'age', 'fare', 'hexbin-logc') # points per hexagon; with a z, its mean per hexagon
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
`heat`, `missing` and `nullmap` take the whole table and no column names; `kx.plot(df[cols], 'heat')` for some
|
|
105
|
+
columns. `wrap` breaks long tick labels onto several lines.
|
|
106
|
+
|
|
89
107
|
rcParams can be overridden in `kx.use` with `__` for dots: `kx.use('dark', figure__figsize=(8, 4))`.
|
|
90
108
|
|
|
91
109
|
Every kind, option, flag and config, with its output, is in the
|
|
@@ -118,7 +136,9 @@ Add `_r` to any name to reverse it, e.g. `cmap="thermal_r"`.
|
|
|
118
136
|
|------------------------------------------------|----------------------------------|
|
|
119
137
|
| `viridis` `magma` `plasma` `inferno` `cividis` | Sequential, perceptually uniform |
|
|
120
138
|
| `turbo` | Sequential, rainbow |
|
|
139
|
+
| `blues` `greys` | Sequential, ColorBrewer |
|
|
121
140
|
| `coolwarm` | Diverging |
|
|
141
|
+
| `rdbu` | Diverging, ColorBrewer |
|
|
122
142
|
| `berlin` `managua` `vanimo` | Diverging, dark centre |
|
|
123
143
|
| `twilight` | Cyclic, for angles and phases |
|
|
124
144
|
| `thermal` `haline` `deep` | Sequential, cmocean (vendored) |
|
|
@@ -45,10 +45,11 @@ kx.plot(df.value, spec='box', by=df.group) # one box per group (also rid
|
|
|
45
45
|
| Token | Values |
|
|
46
46
|
|-------|-----------------------------------------------------------------------------------------------|
|
|
47
47
|
| kind | `line` `step` `area` `band` `scatter` `bar` `barh` `hist` `kde` `ridge` `ecdf` `box` `violin` |
|
|
48
|
-
| | `strip` `qq`
|
|
48
|
+
| | `strip` `qq` `count` `crosstab` `hexbin` `heat` `missing` `nullmap` |
|
|
49
49
|
| theme | `dark` `light` `paper` `science` `talk` `poster` `thesis` |
|
|
50
|
-
| flags | `grid` `leg` `legout` `tight` `rot` `logx` `logy` `logxy` `symlogy` `zero` `eq` `pct`
|
|
51
|
-
| | per kind: `stack` `norm` `cum` `date` `mk` `sort` `ann` `mean` `median` `nocb` `sym`
|
|
50
|
+
| flags | `grid` `leg` `legout` `tight` `rot` `wrap` `logx` `logy` `logxy` `symlogy` `zero` `eq` `pct` |
|
|
51
|
+
| | `si`; per kind: `stack` `norm` `cum` `date` `mk` `sort` `ann` `mean` `median` `nocb` `sym` |
|
|
52
|
+
| | `logc` `corr` `all` |
|
|
52
53
|
|
|
53
54
|
`stack` works with `area`, `bar`, `barh` and `hist`. `norm` is a 100% stack for `area` and a
|
|
54
55
|
density (area 1) for `hist`. `cum` makes `hist` cumulative; `hist-norm-cum` is the CDF.
|
|
@@ -58,6 +59,23 @@ Unknown tokens raise an error instead of being guessed, with the closest valid t
|
|
|
58
59
|
Everything is inspectable: `kx.grammar()`, `kx.grammar('area')`, `kx.parse('leg-scatter')`, `kx.show('dark')`,
|
|
59
60
|
`kx.source('scatter')`.
|
|
60
61
|
|
|
62
|
+
### Tables
|
|
63
|
+
|
|
64
|
+
`kx.load('passengers')` is a demo table with numbers, categories and NaNs to try these on.
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
kx.missing(df) # share of NaNs per column, the most missing on top
|
|
68
|
+
kx.plot(df, 'nullmap-sort') # where the NaNs are: one pixel row per table row
|
|
69
|
+
kx.plot(df, 'heat-corr-ann') # correlations of the numeric columns, -1 to 1
|
|
70
|
+
kx.plot(df, 'heat') # any numeric DataFrame or 2-D array as coloured cells
|
|
71
|
+
kx.plot(df, 'pclass', spec='count', by='survived') # rows per category, split by a second column
|
|
72
|
+
kx.plot(df, 'pclass', 'port', 'crosstab-norm-ann') # how often each pair of categories occurs
|
|
73
|
+
kx.plot(df, 'age', 'fare', 'hexbin-logc') # points per hexagon; with a z, its mean per hexagon
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
`heat`, `missing` and `nullmap` take the whole table and no column names; `kx.plot(df[cols], 'heat')` for some
|
|
77
|
+
columns. `wrap` breaks long tick labels onto several lines.
|
|
78
|
+
|
|
61
79
|
rcParams can be overridden in `kx.use` with `__` for dots: `kx.use('dark', figure__figsize=(8, 4))`.
|
|
62
80
|
|
|
63
81
|
Every kind, option, flag and config, with its output, is in the
|
|
@@ -90,7 +108,9 @@ Add `_r` to any name to reverse it, e.g. `cmap="thermal_r"`.
|
|
|
90
108
|
|------------------------------------------------|----------------------------------|
|
|
91
109
|
| `viridis` `magma` `plasma` `inferno` `cividis` | Sequential, perceptually uniform |
|
|
92
110
|
| `turbo` | Sequential, rainbow |
|
|
111
|
+
| `blues` `greys` | Sequential, ColorBrewer |
|
|
93
112
|
| `coolwarm` | Diverging |
|
|
113
|
+
| `rdbu` | Diverging, ColorBrewer |
|
|
94
114
|
| `berlin` `managua` `vanimo` | Diverging, dark centre |
|
|
95
115
|
| `twilight` | Cyclic, for angles and phases |
|
|
96
116
|
| `thermal` `haline` `deep` | Sequential, cmocean (vendored) |
|
|
@@ -3,17 +3,22 @@ kx: tiny matplotlib helper.
|
|
|
3
3
|
|
|
4
4
|
Token grammar for kx.plot(spec): kind-theme-flag-flag-...
|
|
5
5
|
kind : line | step | area | band | scatter | bar | barh | hist | kde | ridge | ecdf | box | violin | strip
|
|
6
|
-
| qq
|
|
6
|
+
| qq | heat | crosstab | count | missing | nullmap | hexbin
|
|
7
7
|
theme : any file name in styles/
|
|
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
|
-
|
|
11
|
-
|
|
8
|
+
flags : grid | leg | legout | tight | rot | wrap | logx | logy | logxy | symlogy | zero | eq | pct | si
|
|
9
|
+
and per kind: stack norm cum (bars, area, hist), date mk (lines), sort ann (bars, count),
|
|
10
|
+
stack norm (count),
|
|
11
|
+
mean median ann (distributions), nocb sym logc (scatter, heat, hexbin), corr ann (heat),
|
|
12
|
+
norm ann nocb logc (crosstab), ann all (missing), sort (nullmap).
|
|
13
|
+
kx.grammar(kind) lists them.
|
|
14
|
+
by= : group labels for x, one series per group (kde, ridge, ecdf, box, violin, strip, qq, count)
|
|
15
|
+
table : heat, missing and nullmap take a whole DataFrame or 2-D array, with no column names: kx.plot(df, 'heat-corr')
|
|
12
16
|
|
|
13
17
|
Palettes (kx.use(theme, palette="okabe")): any file name in styles/palettes/
|
|
14
18
|
Colormaps (kx.use(theme, cmap="magma")): kx.cmaps()
|
|
15
19
|
with kx.context(theme, ...): the same as kx.use, for one block only.
|
|
16
20
|
kx.save("fig.png"): saves to /kaggle/working on Kaggle, the current folder elsewhere.
|
|
21
|
+
kx.missing(df): the share of missing values per column, the same as kx.plot(df, 'missing-ann').
|
|
17
22
|
kx.grid(5): a figure of 5 panels as a flat array of axes, for kx.plot(..., ax=).
|
|
18
23
|
kx.grammar("area") and kx.source("area") explain one kind; kx.parse(spec) shows how a spec is read.
|
|
19
24
|
"""
|
|
@@ -22,16 +27,21 @@ import importlib.metadata
|
|
|
22
27
|
import inspect
|
|
23
28
|
import os
|
|
24
29
|
import re
|
|
30
|
+
from typing import Any
|
|
31
|
+
|
|
32
|
+
import pandas as pd
|
|
33
|
+
from matplotlib.axes import Axes
|
|
25
34
|
|
|
26
35
|
from ._data import datasets, load
|
|
27
36
|
from ._grid import grid
|
|
28
37
|
from ._plot import plot
|
|
29
38
|
from ._save import save
|
|
30
39
|
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
|
|
40
|
+
from ._theme import BREWER_CMAPS, BUILTIN_CMAPS, VENDORED_CMAPS, cmaps, context, palette, palettes, show, styles, use
|
|
32
41
|
|
|
33
|
-
__all__ = ["BUILTIN_CMAPS", "VENDORED_CMAPS", "Spec", "__version__", "cmaps", "context", "datasets",
|
|
34
|
-
"grid", "load", "palette", "palettes", "parse", "plot", "save", "show", "source",
|
|
42
|
+
__all__ = ["BREWER_CMAPS", "BUILTIN_CMAPS", "VENDORED_CMAPS", "Spec", "__version__", "cmaps", "context", "datasets",
|
|
43
|
+
"grammar", "grid", "load", "missing", "palette", "palettes", "parse", "plot", "save", "show", "source",
|
|
44
|
+
"styles", "use"]
|
|
35
45
|
|
|
36
46
|
|
|
37
47
|
def _version() -> str:
|
|
@@ -65,6 +75,8 @@ def grammar(kind: str | None = None) -> None:
|
|
|
65
75
|
k = _kind(kind)
|
|
66
76
|
print(f"{k.name}: {inspect.getdoc(k.draw)}")
|
|
67
77
|
print("flags:", sorted(COMMON_FLAGS), "+", sorted(k.flags) or "none of its own")
|
|
78
|
+
if k.takes_table:
|
|
79
|
+
print("data : takes a DataFrame or 2-D array")
|
|
68
80
|
if k.takes_by:
|
|
69
81
|
print("by= : group labels for x, one per group")
|
|
70
82
|
return
|
|
@@ -84,3 +96,9 @@ def source(kind: str | None = None) -> None:
|
|
|
84
96
|
for p in sorted(glob.glob(os.path.join(here, "**", "*.py"), recursive=True)):
|
|
85
97
|
with open(p) as f:
|
|
86
98
|
print(f"# ---------- kx/{os.path.relpath(p, here)} ----------\n{f.read()}")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def missing(df: pd.DataFrame, spec: str = "", **kw: Any) -> Axes:
|
|
102
|
+
"""The share of missing values in each column, labelled: kx.plot(df, 'missing-ann-' + spec).
|
|
103
|
+
kx.missing(df, 'dark-wrap') adds a theme and flags; other keywords (title=, ax=, ...) go to kx.plot."""
|
|
104
|
+
return plot(df, "-".join(["missing", "ann", *([spec] if spec else [])]), **kw)
|
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
"""kx.plot: the one-liner. Kinds live in kx/kinds/; this file checks input and applies common flags."""
|
|
2
2
|
import contextlib
|
|
3
3
|
import difflib
|
|
4
|
+
import textwrap
|
|
4
5
|
from typing import Any
|
|
5
6
|
|
|
6
7
|
import matplotlib as mpl
|
|
7
8
|
import matplotlib.dates as mdates
|
|
8
9
|
import matplotlib.pyplot as plt
|
|
10
|
+
import numpy as np
|
|
9
11
|
import pandas as pd
|
|
10
12
|
from matplotlib.axes import Axes
|
|
13
|
+
from matplotlib.category import StrCategoryFormatter
|
|
11
14
|
from matplotlib.layout_engine import ConstrainedLayoutEngine
|
|
12
15
|
from numpy.typing import ArrayLike
|
|
13
16
|
|
|
@@ -16,12 +19,14 @@ from ._spec import KINDS, Spec, parse
|
|
|
16
19
|
from ._theme import style_path
|
|
17
20
|
|
|
18
21
|
OUTSIDE = {"loc": "center left", "bbox_to_anchor": (1, 0.5)} # legend right of the axes
|
|
22
|
+
WRAP = 12 # wrap: characters per tick label line
|
|
19
23
|
|
|
20
24
|
|
|
21
25
|
def plot(*data: ArrayLike | pd.DataFrame | str, spec: str | Spec | None = None, title: str | None = None,
|
|
22
26
|
ax: Axes | None = None, by: ArrayLike | str | None = None, **kwargs: Any) -> Axes:
|
|
23
27
|
"""kx.plot(x, y, z, 'scatter-dark-grid-leg') or kx.plot(x, y, 'bar-light')
|
|
24
28
|
kx.plot(df, 'month', 'y2025', 'y2026', 'bar') names columns of a DataFrame.
|
|
29
|
+
kx.plot(df, 'heat') a table kind takes the whole DataFrame (or a 2-D array) instead.
|
|
25
30
|
|
|
26
31
|
Up to three arrays x, y, z, then the spec (or spec=). by= gives a group label per x value,
|
|
27
32
|
one curve, box or violin per group: kx.plot(df, 'value', spec='kde', by='group').
|
|
@@ -33,6 +38,9 @@ def plot(*data: ArrayLike | pd.DataFrame | str, spec: str | Spec | None = None,
|
|
|
33
38
|
x, y, z, spec, by = _arrays(data, spec, by)
|
|
34
39
|
name, theme, flags = parse(spec or "line")
|
|
35
40
|
kind = KINDS[name]
|
|
41
|
+
if kind.takes_table and not (isinstance(x, pd.DataFrame) and y is None and by is None):
|
|
42
|
+
raise TypeError(f"kind {name!r} takes a whole table and no columns, y, z or by=: kx.plot(df, {name!r}), "
|
|
43
|
+
f"or kx.plot(df[cols], {name!r}) for some columns")
|
|
36
44
|
if kind.needs_y and y is None:
|
|
37
45
|
raise ValueError(f"kind {name!r} needs both x and y")
|
|
38
46
|
if by is not None and not kind.takes_by:
|
|
@@ -70,9 +78,16 @@ def _arrays(data: tuple, spec: str | Spec | None, by: ArrayLike | str | None) ->
|
|
|
70
78
|
_column(df, data[-1])
|
|
71
79
|
raise
|
|
72
80
|
spec = data.pop()
|
|
81
|
+
table = KINDS[parse(spec or "line").kind].takes_table
|
|
82
|
+
if table and df is None and len(data) == 1 and np.ndim(data[0]) == 2:
|
|
83
|
+
df, data = pd.DataFrame(data[0]), [] # a 2-D array is a table with 0..n labels
|
|
73
84
|
if df is not None:
|
|
85
|
+
if not data and table:
|
|
86
|
+
return df, None, None, spec, by
|
|
74
87
|
if not data:
|
|
75
|
-
|
|
88
|
+
tables = ", ".join(sorted(k.name for k in KINDS.values() if k.takes_table))
|
|
89
|
+
raise TypeError("kx.plot(df, ...) needs the column names to plot: kx.plot(df, 'x', 'y')"
|
|
90
|
+
+ (f", or a table kind: {tables}" if tables else ""))
|
|
76
91
|
data = [_column(df, c) for c in data]
|
|
77
92
|
by = _column(df, by) if isinstance(by, str) else by
|
|
78
93
|
elif isinstance(by, str):
|
|
@@ -116,6 +131,20 @@ def _common(ax: Axes, name: str, value_axis: str, flags: set[str]) -> None:
|
|
|
116
131
|
loc = mdates.AutoDateLocator()
|
|
117
132
|
ax.xaxis.set_major_locator(loc)
|
|
118
133
|
ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(loc))
|
|
134
|
+
if "wrap" in flags:
|
|
135
|
+
for axis in (ax.xaxis, ax.yaxis):
|
|
136
|
+
_wrap(axis)
|
|
119
137
|
if "rot" in flags: # rotation stays for ticks matplotlib adds later
|
|
120
138
|
ax.tick_params(axis="x", labelrotation=45)
|
|
121
139
|
plt.setp(ax.get_xticklabels(), ha="right", rotation_mode="anchor")
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _wrap(axis: mpl.axis.Axis) -> None:
|
|
143
|
+
"""Text tick labels broken into lines of WRAP characters at spaces; numbers and dates are left alone."""
|
|
144
|
+
def fill(text: str) -> str:
|
|
145
|
+
return textwrap.fill(text, WRAP, break_long_words=False)
|
|
146
|
+
old = axis.get_major_formatter()
|
|
147
|
+
if isinstance(old, StrCategoryFormatter): # text plotted directly: matplotlib's categories
|
|
148
|
+
axis.set_major_formatter(mpl.ticker.FuncFormatter(lambda v, pos: fill(old(v, pos))))
|
|
149
|
+
elif isinstance(axis.get_major_locator(), mpl.ticker.FixedLocator): # set_xticks(ticks, labels): stay fixed
|
|
150
|
+
axis.set_ticks(axis.get_majorticklocs(), [fill(t.get_text()) for t in axis.get_majorticklabels()])
|
|
@@ -6,10 +6,10 @@ from typing import Any, NamedTuple
|
|
|
6
6
|
|
|
7
7
|
from ._theme import styles
|
|
8
8
|
|
|
9
|
-
COMMON_FLAGS = {"grid", "leg", "legout", "tight", "rot",
|
|
9
|
+
COMMON_FLAGS = {"grid", "leg", "legout", "tight", "rot", "wrap", # handled by kx.plot for every kind
|
|
10
10
|
"logx", "logy", "logxy", "symlogy", "zero", "eq", "pct", "si"}
|
|
11
11
|
EXCLUSIVE = ({"logy", "logxy", "symlogy"}, {"logx", "logxy"}, {"zero", "logy"}, {"zero", "logxy"},
|
|
12
|
-
{"pct", "si"}, {"sym", "logc"})
|
|
12
|
+
{"pct", "si"}, {"sym", "logc"}, {"corr", "logc"}) # pairs that ask for opposite things
|
|
13
13
|
|
|
14
14
|
|
|
15
15
|
@dataclass(frozen=True)
|
|
@@ -22,6 +22,7 @@ class Kind:
|
|
|
22
22
|
check: Callable[[Any, Any, set[str]], None] | None # check(y, z, flags) raises on bad input
|
|
23
23
|
takes_by: bool = False # draw also gets by= (group labels for x)
|
|
24
24
|
value_axis: str = "y" # where pct, si and zero apply: "x" for barh
|
|
25
|
+
takes_table: bool = False # x is a whole DataFrame (or 2-D array), with no y or z
|
|
25
26
|
|
|
26
27
|
|
|
27
28
|
KINDS: dict[str, Kind] = {}
|
|
@@ -29,12 +30,12 @@ KINDS: dict[str, Kind] = {}
|
|
|
29
30
|
|
|
30
31
|
def kind(name: str, flags: tuple[str, ...] = (), needs_y: bool = True,
|
|
31
32
|
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`."""
|
|
33
|
+
value_axis: str = "y", table: bool = False) -> Callable:
|
|
34
|
+
"""Decorator that registers a draw function as kind `name`. table=True: x is the whole DataFrame."""
|
|
34
35
|
def register(draw: Callable[..., None]) -> Callable[..., None]:
|
|
35
36
|
if name in KINDS or name in COMMON_FLAGS or "-" in name:
|
|
36
37
|
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
|
+
KINDS[name] = Kind(name, draw, frozenset(flags), needs_y and not table, check, takes_by, value_axis, table)
|
|
38
39
|
return draw
|
|
39
40
|
return register
|
|
40
41
|
|
|
@@ -11,6 +11,8 @@ from . import _files
|
|
|
11
11
|
|
|
12
12
|
BUILTIN_CMAPS = ("viridis", "magma", "plasma", "inferno", "cividis", "turbo",
|
|
13
13
|
"twilight", "coolwarm", "berlin", "managua", "vanimo")
|
|
14
|
+
# lowercase names for matplotlib's ColorBrewer maps, registered as copies
|
|
15
|
+
BREWER_CMAPS = {"blues": "Blues", "greys": "Greys", "rdbu": "RdBu"}
|
|
14
16
|
# styles/cmaps/<name>.txt: cmocean, then Crameri's Scientific colour maps 8
|
|
15
17
|
VENDORED_CMAPS = ("thermal", "haline", "deep", "balance",
|
|
16
18
|
"batlow", "lipari", "hawaii", "oslo", "davos", "vik", "roma", "bam", "cork", "romaO")
|
|
@@ -53,11 +55,18 @@ def _read_hex(path: str) -> list[str]:
|
|
|
53
55
|
|
|
54
56
|
|
|
55
57
|
def _register_cmaps() -> None:
|
|
56
|
-
"""Add the vendored colormaps to matplotlib, once."""
|
|
58
|
+
"""Add the vendored colormaps and the lowercase ColorBrewer names to matplotlib, once."""
|
|
57
59
|
for name in VENDORED_CMAPS:
|
|
58
60
|
if name not in mpl.colormaps:
|
|
59
61
|
cmap = ListedColormap(_read_hex(_files.path("styles", "cmaps", f"{name}.txt")), name=name)
|
|
60
62
|
mpl.colormaps.register(cmap)
|
|
63
|
+
for name, brewer in BREWER_CMAPS.items():
|
|
64
|
+
if name not in mpl.colormaps:
|
|
65
|
+
# mpl.colormaps.register(mpl.colormaps[brewer], name=name)
|
|
66
|
+
# older mpl syntax
|
|
67
|
+
cmap = mpl.colormaps[brewer]
|
|
68
|
+
cmap.name = name
|
|
69
|
+
mpl.colormaps.register(cmap)
|
|
61
70
|
|
|
62
71
|
|
|
63
72
|
_register_cmaps()
|
|
@@ -65,7 +74,7 @@ _register_cmaps()
|
|
|
65
74
|
|
|
66
75
|
def cmaps() -> list[str]:
|
|
67
76
|
"""List supported colormap names that this matplotlib version has, plus the vendored ones."""
|
|
68
|
-
return sorted(n for n in BUILTIN_CMAPS
|
|
77
|
+
return sorted(n for n in (*BUILTIN_CMAPS, *BREWER_CMAPS, *VENDORED_CMAPS) if n in mpl.colormaps)
|
|
69
78
|
|
|
70
79
|
|
|
71
80
|
def show(name: str) -> None:
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Small helpers shared by the kinds."""
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
import matplotlib as mpl
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
from matplotlib.axes import Axes
|
|
8
|
+
from matplotlib.cm import ScalarMappable
|
|
9
|
+
from matplotlib.colorbar import Colorbar
|
|
10
|
+
from numpy.typing import ArrayLike
|
|
11
|
+
|
|
12
|
+
COLOUR = ("nocb", "sym", "logc") # flags for numeric values on a colour scale
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def label(arr: ArrayLike, default: str) -> str:
|
|
16
|
+
"""Use a pandas Series name as legend label when there is one."""
|
|
17
|
+
name = getattr(arr, "name", None)
|
|
18
|
+
return str(name) if name is not None else default
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def categories(z: ArrayLike) -> list[Any] | None:
|
|
22
|
+
"""Category values of z if it is text, bool or categorical; None if z is numeric."""
|
|
23
|
+
s = z if isinstance(z, pd.Series) else pd.Series(np.asarray(z))
|
|
24
|
+
if isinstance(s.dtype, pd.CategoricalDtype):
|
|
25
|
+
return list(s.cat.categories)
|
|
26
|
+
if pd.api.types.is_numeric_dtype(s) and not pd.api.types.is_bool_dtype(s):
|
|
27
|
+
return None
|
|
28
|
+
return sorted(s.dropna().unique(), key=str)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def norm(values: ArrayLike, flags: set[str]) -> mpl.colors.Normalize | None:
|
|
32
|
+
"""sym = limits ±max|z| so 0 sits mid-colormap, logc = log colour scale. None = matplotlib's linear default."""
|
|
33
|
+
v = np.asarray(values, dtype=float)
|
|
34
|
+
if "sym" in flags:
|
|
35
|
+
top = np.nanmax(np.abs(v))
|
|
36
|
+
return mpl.colors.Normalize(-top, top)
|
|
37
|
+
if "logc" in flags:
|
|
38
|
+
if np.nanmin(v) <= 0:
|
|
39
|
+
raise ValueError("flag 'logc' needs z > 0; use 'sym' for values around 0")
|
|
40
|
+
return mpl.colors.LogNorm()
|
|
41
|
+
return None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def colorbar(ax: Axes, mappable: ScalarMappable, label: str, flags: set[str]) -> Colorbar | None:
|
|
45
|
+
"""A colorbar for mappable next to ax, unless nocb."""
|
|
46
|
+
return None if "nocb" in flags else ax.figure.colorbar(mappable, ax=ax, label=label)
|