kx-plot 0.2.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.
Files changed (74) hide show
  1. kx_plot-0.4.0/CHANGELOG.md +203 -0
  2. {kx_plot-0.2.0 → kx_plot-0.4.0}/PKG-INFO +39 -10
  3. {kx_plot-0.2.0 → kx_plot-0.4.0}/README.md +38 -9
  4. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/__init__.py +34 -10
  5. kx_plot-0.4.0/kx/_grid.py +25 -0
  6. kx_plot-0.4.0/kx/_plot.py +150 -0
  7. kx_plot-0.4.0/kx/_save.py +26 -0
  8. kx_plot-0.4.0/kx/_spec.py +91 -0
  9. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/_theme.py +24 -3
  10. kx_plot-0.4.0/kx/_util.py +46 -0
  11. kx_plot-0.4.0/kx/data/daily.csv +731 -0
  12. kx_plot-0.4.0/kx/data/passengers.csv +501 -0
  13. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/kinds/__init__.py +1 -1
  14. kx_plot-0.4.0/kx/kinds/basic.py +181 -0
  15. kx_plot-0.4.0/kx/kinds/dist.py +274 -0
  16. kx_plot-0.4.0/kx/kinds/table.py +130 -0
  17. {kx_plot-0.2.0 → kx_plot-0.4.0}/pyproject.toml +1 -1
  18. kx_plot-0.4.0/tests/test_kx.py +1309 -0
  19. kx_plot-0.2.0/CHANGELOG.md +0 -109
  20. kx_plot-0.2.0/kx/_plot.py +0 -50
  21. kx_plot-0.2.0/kx/_spec.py +0 -58
  22. kx_plot-0.2.0/kx/_util.py +0 -22
  23. kx_plot-0.2.0/kx/kinds/basic.py +0 -104
  24. kx_plot-0.2.0/kx/kinds/dist.py +0 -151
  25. kx_plot-0.2.0/tests/test_kx.py +0 -528
  26. {kx_plot-0.2.0 → kx_plot-0.4.0}/.gitignore +0 -0
  27. {kx_plot-0.2.0 → kx_plot-0.4.0}/LICENSE +0 -0
  28. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/_data.py +0 -0
  29. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/_files.py +0 -0
  30. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/data/cloud.csv +0 -0
  31. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/data/dists.csv +0 -0
  32. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/data/monthly.csv +0 -0
  33. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/data/waves.csv +0 -0
  34. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/cmaps/LICENCES.md +0 -0
  35. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/cmaps/balance.txt +0 -0
  36. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/cmaps/bam.txt +0 -0
  37. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/cmaps/batlow.txt +0 -0
  38. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/cmaps/cork.txt +0 -0
  39. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/cmaps/davos.txt +0 -0
  40. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/cmaps/deep.txt +0 -0
  41. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/cmaps/haline.txt +0 -0
  42. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/cmaps/hawaii.txt +0 -0
  43. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/cmaps/lipari.txt +0 -0
  44. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/cmaps/oslo.txt +0 -0
  45. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/cmaps/roma.txt +0 -0
  46. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/cmaps/romaO.txt +0 -0
  47. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/cmaps/thermal.txt +0 -0
  48. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/cmaps/vik.txt +0 -0
  49. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/dark.mplstyle +0 -0
  50. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/light.mplstyle +0 -0
  51. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/palettes/LICENCES.md +0 -0
  52. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/palettes/dark2.txt +0 -0
  53. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/palettes/ibm.txt +0 -0
  54. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/palettes/okabe.txt +0 -0
  55. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/palettes/paired.txt +0 -0
  56. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/palettes/petroff10.txt +0 -0
  57. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/palettes/petroff6.txt +0 -0
  58. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/palettes/petroff8.txt +0 -0
  59. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/palettes/set1.txt +0 -0
  60. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/palettes/set2.txt +0 -0
  61. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/palettes/tab10.txt +0 -0
  62. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/palettes/tab20.txt +0 -0
  63. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/palettes/tableaucb.txt +0 -0
  64. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/palettes/tolbright.txt +0 -0
  65. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/palettes/tolhc.txt +0 -0
  66. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/palettes/tollight.txt +0 -0
  67. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/palettes/tolmc.txt +0 -0
  68. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/palettes/tolvibrant.txt +0 -0
  69. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/paper.mplstyle +0 -0
  70. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/poster.mplstyle +0 -0
  71. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/science.mplstyle +0 -0
  72. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/talk.mplstyle +0 -0
  73. {kx_plot-0.2.0 → kx_plot-0.4.0}/kx/styles/thesis.mplstyle +0 -0
  74. {kx_plot-0.2.0 → kx_plot-0.4.0}/tests/conftest.py +0 -0
@@ -0,0 +1,203 @@
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.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
+
45
+ ## [0.3.0] - 2026-10-12
46
+
47
+ ### Added
48
+
49
+ - **Plot kind** `qq`: sorted values against normal quantiles, one series per array or `by=` group, with a dashed
50
+ line through each one's quartiles. The quantiles come from Python's `statistics`, so no scipy is needed.
51
+ - **Plot kind** `ridge`: density curves stacked top to bottom, one per array or `by=` group, on one shared height
52
+ scale; `overlap=` sets the tallest ridge's height in rows. `mean` and `median` mark each ridge.
53
+ - **Plot kind** `strip`: every value as a point, one column per array or `by=` group, jittered sideways so ties
54
+ stay visible (the same way every run; `jitter=` sets the spread). Takes `mean` and `ann` like `box`.
55
+ - `kx.grid(n, cols=3)` makes a figure of `n` panels and returns them as a flat array of axes. Each panel gets
56
+ the theme's figure size, empty cells are removed, and constrained layout leaves room for colorbars and outside
57
+ legends. Other keywords go to `plt.subplots`.
58
+ - `kx.save('fig.png')` saves the current figure (or the one of a given `ax` or figure) and returns the path.
59
+ A relative name goes to `/kaggle/working` on Kaggle and to the current folder elsewhere; missing folders are
60
+ created. Without an extension the theme's format is used, so `thesis` saves a PDF.
61
+ - `with kx.context(theme, palette=..., cmap=..., **rc):` takes the same arguments as `kx.use` and puts the
62
+ previous settings back when the block ends, also after an error.
63
+ - `kx.parse(spec)` returns a `Spec` with `kind`, `theme` and `flags`. Printed, it is the canonical spec string
64
+ (kind, theme, then flags A–Z), and `kx.plot` takes a `Spec` wherever it takes a spec string. Mistyped tokens get
65
+ the closest valid ones as a hint.
66
+ - `kx.plot(df, 'x', 'y', 'z', spec)` names DataFrame columns, and `by=` can name a column. A mistyped column
67
+ gets the closest names as a hint.
68
+ - `kx.plot(..., **kwargs)` passes other keywords to the matplotlib call that draws the kind, over kx's defaults:
69
+ `kx.plot(x, y, 'line', linewidth=3)`. `bins=` sets the shared `hist` bins and `width=` (`height=` for
70
+ `barh`) the space each category's bars fill.
71
+ - **Flags for every kind**
72
+ - Layout: `legout` puts the legend outside on the right, keeping a kind's legend title. `rot` rotates the x tick
73
+ labels 45°.
74
+ - Axes: `logxy` (log on both), `symlogy` (symmetric log y, so negatives work), `zero` (the value axis includes 0)
75
+ and `eq` (equal aspect).
76
+ - Number format: `pct` (0.25 → 25%) and `si` (1500 → 1.5k) on the value axis, which is x for `barh` and y
77
+ otherwise.
78
+ - **Flags for some kinds**
79
+ - `date` for `line`, `step`, `area`, `band` and `scatter`: `x` is read as dates (text works too) and gets compact
80
+ date ticks.
81
+ - `mk` for `line`, `step`, `area` and `band`: a marker on every point.
82
+ - `sort` for `bar` and `barh`: largest first, by `y`, or by the total with `stack`.
83
+ - `ann` for `bar` and `barh`: the value on each bar, inside each segment with `stack`.
84
+ - `mean` and `median` for `hist`, `kde` and `ecdf`: a dashed / dotted line at each series' mean / median.
85
+ `mean` for `box` and `violin`: a diamond at each mean. `ann` writes the values.
86
+ - `nocb`, `sym` and `logc` for `scatter` with a numeric `z`: no colorbar, colour limits symmetric around 0,
87
+ log colour scale.
88
+ - Flags that ask for opposite things (`pct` and `si`, `logy` and `logxy`, `zero` and a log y, `sym` and `logc`)
89
+ raise an error.
90
+
91
+ ### Changed
92
+
93
+ - The `tight` flag leaves a figure with constrained layout (such as `kx.grid`'s) alone instead of failing
94
+ when it has a colorbar.
95
+
96
+ ### Fixed
97
+
98
+ - `leg` and `legout` on a plot with nothing to label, such as `scatter` with a numeric `z`, no longer warn
99
+ "No artists with labels found"; the plot just has no legend.
100
+
101
+ ## [0.2.0] - 2026-10-09
102
+
103
+ ### Added
104
+
105
+ - **Plot kinds**
106
+ - `barh`: horizontal bars, first category on top. `y` and `z` are grouped like `bar`.
107
+ - `kde`: smooth density curves (Gaussian KDE in numpy, no scipy needed), one per array.
108
+ - `ecdf`: empirical CDF, the share of values at or below each x, one step curve per array.
109
+ - `box`: box plots side by side (median, quartiles, 1.5 IQR whiskers, outliers), one per array.
110
+ - `violin`: violin plots side by side with the median and quartiles marked, one per array.
111
+ - **Flags**
112
+ - `stack` now works with `bar` and `barh`: `z` is drawn on top of `y`, so the bar's end is the total.
113
+ - `stack`, `norm` (density) and the new `cum` (cumulative) work with `hist`.
114
+ - `kx.plot(..., by=groups)` splits `x` into one curve, box or violin per group (for `kde`, `ecdf`, `box`, `violin`).
115
+ - cmocean colourmaps `thermal`, `haline`, `deep` and `balance` for `kx.use(cmap=...)`.
116
+ - Crameri colourmaps (Scientific colour maps 8) `batlow`, `lipari`, `hawaii`, `oslo`, `davos`, `vik`, `roma`,
117
+ `bam`, `cork` and cyclic `romaO`, vendored the same way.
118
+ - `kx.use(cmap="<name>_r")` reverses any colourmap in `kx.cmaps()`.
119
+ - Palettes `tollight` (Paul Tol), `set1` and `paired` (ColorBrewer) and `tab20` (Tableau, 20 categories).
120
+
121
+ ### Changed
122
+
123
+ - `hist` puts every series on the same bins, so overlaid bars line up.
124
+
125
+ ## [0.1.0] - 2026-10-08
126
+
127
+ ### Added
128
+
129
+ - **PyPI package:** `pip install kx-plot`, then `import kx`. The wheel ships the themes, palettes and demo CSVs.
130
+ - **Palettes:** Paul Tol (`tolbright`, `tolvibrant`, `tolhc`, `tolmc`), Petroff (`petroff6`, `petroff8`, `petroff10`),
131
+ Tableau (`tab10`, `tableaucb`), ColorBrewer (`set2`, `dark2`) and `ibm`. Their licences are in
132
+ `kx/styles/palettes/LICENCES.md`.
133
+
134
+ ### Changed
135
+
136
+ - **`kx.py` is now the `kx/` package**, with the themes in `kx/styles/` and the demo CSVs in `kx/data/`.
137
+ `kx.source()` prints every file in the package.
138
+
139
+ ## [0.0.2] - 2026-10-08
140
+
141
+ ### Added
142
+
143
+ - **Plot kinds**
144
+ - `step`: like `line`, drawn as steps centred on each x.
145
+ - `area`: filled areas, overlapping and semi-transparent by default.
146
+ - `area-stack` stacks `z` on top of `y`, so the top edge is the total.
147
+ - `area-norm` draws a 100% stack with a percent y axis. With `leg`, the legend goes outside on the right.
148
+ - `band`: a `y` line with a shaded `y ± z` band in the same colour. `z` is required.
149
+ - `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.
150
+ - **Flags**
151
+ - `stack` and `norm`. Both work with `area` only for now.
152
+ - **Themes**
153
+ - `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.
154
+ - `talk`: slides (16:9), 18 pt sans, thick lines, Okabe-Ito colours.
155
+ - `poster`: 12 × 9 in, 26 pt sans, very thick lines, saves at 300 dpi.
156
+ - `thesis`: A4 text width (160 mm), Computer Modern 10/9 pt without needing LaTeX, saves as PDF when the file name has no extension.
157
+ - **Palettes**
158
+ - Named palettes live in `styles/palettes/<name>.txt`, one hex colour per line. Any file added there is found automatically.
159
+ - `okabe`: the Okabe-Ito palette, 8 colours that stay distinguishable for every common type of colour blindness.
160
+ - `kx.palettes()` lists the palettes and `kx.palette(name)` returns a palette's colours.
161
+ - `kx.use(theme, palette="okabe")` accepts a palette name as well as a list of colours.
162
+ - **Colormaps**
163
+ - `kx.use(theme, cmap=...)` sets the colormap for continuous colour.
164
+ - The supported matplotlib colormaps are `viridis`, `magma`, `plasma`, `inferno`, `cividis`, `turbo`, `twilight`, `coolwarm`, `berlin`, `managua` and `vanimo`.
165
+ - `kx.cmaps()` lists only the ones the installed matplotlib has. `berlin`, `managua` and `vanimo` need matplotlib 3.10 or newer.
166
+ - **Docs**
167
+ - `Example Usage.ipynb`: a detailed walkthrough for the public Kaggle notebook. It loads `kx` from the attached dataset.
168
+ - `kx.grammar()` lists the palettes and colormaps as well as the kinds, themes and flags.
169
+
170
+ ### Changed
171
+
172
+ - **`paper` theme, reworked for greyscale print:**
173
+ - black, dark grey and mid grey colours, each paired with a linestyle (solid, dashed, dotted, dash-dot)
174
+ - greyscale colormap
175
+ - 300 dpi export with a white background
176
+ - serif font for maths text as well
177
+ - 110 dpi in notebooks instead of 150
178
+ - **Palettes keep the theme's other cycled properties:** they replace only the colours, so `paper` + `okabe` keeps `paper`'s linestyles.
179
+ - **`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.
180
+ - **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.
181
+ - **`previews/demo.ipynb`:** cut down to a short demo of each kind and theme. The full walkthrough is now `Example Usage.ipynb`.
182
+ - **Strict errors** also cover:
183
+ - `stack` or `norm` on a kind that doesn't support them
184
+ - `band` without `z`
185
+ - `area-norm` with only one series
186
+
187
+ ## [0.0.1] - 2026-10-07
188
+
189
+ ### Added
190
+
191
+ - `kx.plot` with the kinds `line`, `scatter`, `bar` and `hist`
192
+ - the flags `grid`, `leg`, `logx`, `logy` and `tight`
193
+ - the themes `dark`, `light` and `paper`
194
+ - `kx.use`, `kx.show`, `kx.source`, `kx.grammar`, `kx.load` and the demo CSVs
195
+ - a workflow that publishes the dataset to Kaggle
196
+
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
199
+ [0.3.0]: https://github.com/vhrabar/kx-plot/compare/v0.2.0...v0.3.0
200
+ [0.2.0]: https://github.com/vhrabar/kx-plot/compare/v0.1.0...v0.2.0
201
+ [0.1.0]: https://github.com/vhrabar/kx-plot/compare/v0.0.2...v0.1.0
202
+ [0.0.2]: https://github.com/vhrabar/kx-plot/compare/v0.0.1...v0.0.2
203
+ [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.2.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
@@ -60,22 +60,49 @@ 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.plot(df.value, spec='kde', by=df.group) # one density curve per group
64
- kx.plot(df.value, spec='box', by=df.group) # one box per group (also ecdf, violin)
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
- | theme | `dark` `light` `paper` `science` `talk` `poster` `thesis` |
71
- | flags | `grid` `leg` `logx` `logy` `tight`, plus `stack` `norm` `cum` (below) |
73
+ | Token | Values |
74
+ |-------|-----------------------------------------------------------------------------------------------|
75
+ | kind | `line` `step` `area` `band` `scatter` `bar` `barh` `hist` `kde` `ridge` `ecdf` `box` `violin` |
76
+ | | `strip` `qq` `count` `crosstab` `hexbin` `heat` `missing` `nullmap` |
77
+ | theme | `dark` `light` `paper` `science` `talk` `poster` `thesis` |
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` |
72
81
 
73
82
  `stack` works with `area`, `bar`, `barh` and `hist`. `norm` is a 100% stack for `area` and a
74
83
  density (area 1) for `hist`. `cum` makes `hist` cumulative; `hist-norm-cum` is the CDF.
75
84
  `hist` puts every series on the same bins, so the bars line up.
76
85
 
77
- Unknown tokens raise an error instead of being guessed. Everything is inspectable:
78
- `kx.grammar()`, `kx.grammar('area')`, `kx.show('dark')`, `kx.source('scatter')`.
86
+ Unknown tokens raise an error instead of being guessed, with the closest valid tokens as a hint.
87
+ Everything is inspectable: `kx.grammar()`, `kx.grammar('area')`, `kx.parse('leg-scatter')`, `kx.show('dark')`,
88
+ `kx.source('scatter')`.
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.
79
106
 
80
107
  rcParams can be overridden in `kx.use` with `__` for dots: `kx.use('dark', figure__figsize=(8, 4))`.
81
108
 
@@ -109,7 +136,9 @@ Add `_r` to any name to reverse it, e.g. `cmap="thermal_r"`.
109
136
  |------------------------------------------------|----------------------------------|
110
137
  | `viridis` `magma` `plasma` `inferno` `cividis` | Sequential, perceptually uniform |
111
138
  | `turbo` | Sequential, rainbow |
139
+ | `blues` `greys` | Sequential, ColorBrewer |
112
140
  | `coolwarm` | Diverging |
141
+ | `rdbu` | Diverging, ColorBrewer |
113
142
  | `berlin` `managua` `vanimo` | Diverging, dark centre |
114
143
  | `twilight` | Cyclic, for angles and phases |
115
144
  | `thermal` `haline` `deep` | Sequential, cmocean (vendored) |
@@ -32,22 +32,49 @@ import kx; kx.use('dark')
32
32
  kx.use('light', palette='okabe', cmap='cividis') # notebook default: theme, palette, colormap
33
33
  kx.plot(x, y, z, 'scatter-grid-leg') # spec: kind-theme-flag-...
34
34
  kx.plot(x, y, 'bar-paper') # a theme in the spec applies to this plot only
35
- kx.plot(df.value, spec='kde', by=df.group) # one density curve per group
36
- kx.plot(df.value, spec='box', by=df.group) # one box per group (also ecdf, violin)
35
+ 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
- | theme | `dark` `light` `paper` `science` `talk` `poster` `thesis` |
43
- | flags | `grid` `leg` `logx` `logy` `tight`, plus `stack` `norm` `cum` (below) |
45
+ | Token | Values |
46
+ |-------|-----------------------------------------------------------------------------------------------|
47
+ | kind | `line` `step` `area` `band` `scatter` `bar` `barh` `hist` `kde` `ridge` `ecdf` `box` `violin` |
48
+ | | `strip` `qq` `count` `crosstab` `hexbin` `heat` `missing` `nullmap` |
49
+ | theme | `dark` `light` `paper` `science` `talk` `poster` `thesis` |
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` |
44
53
 
45
54
  `stack` works with `area`, `bar`, `barh` and `hist`. `norm` is a 100% stack for `area` and a
46
55
  density (area 1) for `hist`. `cum` makes `hist` cumulative; `hist-norm-cum` is the CDF.
47
56
  `hist` puts every series on the same bins, so the bars line up.
48
57
 
49
- Unknown tokens raise an error instead of being guessed. Everything is inspectable:
50
- `kx.grammar()`, `kx.grammar('area')`, `kx.show('dark')`, `kx.source('scatter')`.
58
+ Unknown tokens raise an error instead of being guessed, with the closest valid tokens as a hint.
59
+ Everything is inspectable: `kx.grammar()`, `kx.grammar('area')`, `kx.parse('leg-scatter')`, `kx.show('dark')`,
60
+ `kx.source('scatter')`.
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.
51
78
 
52
79
  rcParams can be overridden in `kx.use` with `__` for dots: `kx.use('dark', figure__figsize=(8, 4))`.
53
80
 
@@ -81,7 +108,9 @@ Add `_r` to any name to reverse it, e.g. `cmap="thermal_r"`.
81
108
  |------------------------------------------------|----------------------------------|
82
109
  | `viridis` `magma` `plasma` `inferno` `cividis` | Sequential, perceptually uniform |
83
110
  | `turbo` | Sequential, rainbow |
111
+ | `blues` `greys` | Sequential, ColorBrewer |
84
112
  | `coolwarm` | Diverging |
113
+ | `rdbu` | Diverging, ColorBrewer |
85
114
  | `berlin` `managua` `vanimo` | Diverging, dark centre |
86
115
  | `twilight` | Cyclic, for angles and phases |
87
116
  | `thermal` `haline` `deep` | Sequential, cmocean (vendored) |
@@ -2,30 +2,46 @@
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 | heat | crosstab | count | missing | nullmap | hexbin
6
7
  theme : any file name in styles/
7
- flags : grid | leg | logx | logy | tight | stack | norm | cum
8
- (stack: area, bar, barh, hist; norm: area, hist; cum: hist)
9
- by= : group labels for x, one curve/box/violin per group (kde, ecdf, box, violin)
8
+ 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')
10
16
 
11
17
  Palettes (kx.use(theme, palette="okabe")): any file name in styles/palettes/
12
18
  Colormaps (kx.use(theme, cmap="magma")): kx.cmaps()
13
- kx.grammar("area") and kx.source("area") explain one kind.
19
+ with kx.context(theme, ...): the same as kx.use, for one block only.
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').
22
+ kx.grid(5): a figure of 5 panels as a flat array of axes, for kx.plot(..., ax=).
23
+ kx.grammar("area") and kx.source("area") explain one kind; kx.parse(spec) shows how a spec is read.
14
24
  """
15
25
  import glob
16
26
  import importlib.metadata
17
27
  import inspect
18
28
  import os
19
29
  import re
30
+ from typing import Any
31
+
32
+ import pandas as pd
33
+ from matplotlib.axes import Axes
20
34
 
21
35
  from ._data import datasets, load
36
+ from ._grid import grid
22
37
  from ._plot import plot
23
- from ._spec import COMMON_FLAGS, KINDS, all_flags
24
- from ._spec import parse as _parse # noqa: F401 (tests)
25
- from ._theme import BUILTIN_CMAPS, VENDORED_CMAPS, cmaps, palette, palettes, show, styles, use
38
+ from ._save import save
39
+ from ._spec import COMMON_FLAGS, KINDS, Spec, all_flags, parse
40
+ from ._theme import BREWER_CMAPS, BUILTIN_CMAPS, VENDORED_CMAPS, cmaps, context, palette, palettes, show, styles, use
26
41
 
27
- __all__ = ["BUILTIN_CMAPS", "VENDORED_CMAPS", "__version__", "cmaps", "datasets", "grammar", "load", "palette",
28
- "palettes", "plot", "show", "source", "styles", "use"]
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"]
29
45
 
30
46
 
31
47
  def _version() -> str:
@@ -59,6 +75,8 @@ def grammar(kind: str | None = None) -> None:
59
75
  k = _kind(kind)
60
76
  print(f"{k.name}: {inspect.getdoc(k.draw)}")
61
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")
62
80
  if k.takes_by:
63
81
  print("by= : group labels for x, one per group")
64
82
  return
@@ -78,3 +96,9 @@ def source(kind: str | None = None) -> None:
78
96
  for p in sorted(glob.glob(os.path.join(here, "**", "*.py"), recursive=True)):
79
97
  with open(p) as f:
80
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)
@@ -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,150 @@
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
+ import textwrap
5
+ from typing import Any
6
+
7
+ import matplotlib as mpl
8
+ import matplotlib.dates as mdates
9
+ import matplotlib.pyplot as plt
10
+ import numpy as np
11
+ import pandas as pd
12
+ from matplotlib.axes import Axes
13
+ from matplotlib.category import StrCategoryFormatter
14
+ from matplotlib.layout_engine import ConstrainedLayoutEngine
15
+ from numpy.typing import ArrayLike
16
+
17
+ from . import kinds # noqa: F401 (registers every kind)
18
+ from ._spec import KINDS, Spec, parse
19
+ from ._theme import style_path
20
+
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
23
+
24
+
25
+ def plot(*data: ArrayLike | pd.DataFrame | str, spec: str | Spec | None = None, title: str | None = None,
26
+ ax: Axes | None = None, by: ArrayLike | str | None = None, **kwargs: Any) -> Axes:
27
+ """kx.plot(x, y, z, 'scatter-dark-grid-leg') or kx.plot(x, y, 'bar-light')
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.
30
+
31
+ Up to three arrays x, y, z, then the spec (or spec=). by= gives a group label per x value,
32
+ one curve, box or violin per group: kx.plot(df, 'value', spec='kde', by='group').
33
+ Other keywords go to the kind's matplotlib call and win over kx's defaults:
34
+ kx.plot(x, y, 'line', linewidth=3), kx.plot(x, spec='hist', bins=50). kx.grammar(kind) says which call.
35
+
36
+ A theme in the spec applies to this plot only; kx.use() sets the notebook default.
37
+ """
38
+ x, y, z, spec, by = _arrays(data, spec, by)
39
+ name, theme, flags = parse(spec or "line")
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")
44
+ if kind.needs_y and y is None:
45
+ raise ValueError(f"kind {name!r} needs both x and y")
46
+ if by is not None and not kind.takes_by:
47
+ raise ValueError(f"by= only works with kind {sorted(k.name for k in KINDS.values() if k.takes_by)}, "
48
+ f"not {name!r}")
49
+ if kind.check:
50
+ kind.check(y, z, flags)
51
+ if "date" in flags: # strings and numbers become dates; a Series keeps its name
52
+ x = pd.to_datetime(x)
53
+
54
+ style = plt.style.context(["default", style_path(theme)]) if theme else contextlib.nullcontext()
55
+ with style:
56
+ ax = ax or plt.subplots()[1]
57
+ kind.draw(ax, x, y, z, flags, **({"by": by} if by is not None else {}), **kwargs)
58
+ _common(ax, name, kind.value_axis, flags)
59
+ if title: ax.set_title(title)
60
+ if "tight" in flags and not isinstance(ax.figure.get_layout_engine(), ConstrainedLayoutEngine):
61
+ ax.figure.tight_layout() # a constrained figure (kx.grid) is laid out already
62
+ return ax
63
+
64
+
65
+ def _arrays(data: tuple, spec: str | Spec | None, by: ArrayLike | str | None) -> tuple:
66
+ """(x, y, z, spec, by) from kx.plot's positional arguments: arrays, or a DataFrame and column names."""
67
+ data = list(data)
68
+ df = data.pop(0) if data and isinstance(data[0], pd.DataFrame) else None
69
+ last = data[-1] if data else None
70
+ if isinstance(last, Spec) or (isinstance(last, str) and (df is None or last not in df.columns)):
71
+ if spec is not None: # a trailing string that is not a column is the spec
72
+ raise TypeError(f"spec given twice ({data[-1]!r} and spec={spec!r})")
73
+ if df is not None and isinstance(last, str): # not a spec either, but close to a column: a typo
74
+ try:
75
+ parse(data[-1])
76
+ except ValueError:
77
+ if difflib.get_close_matches(data[-1], [str(c) for c in df.columns]):
78
+ _column(df, data[-1])
79
+ raise
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
84
+ if df is not None:
85
+ if not data and table:
86
+ return df, None, None, spec, by
87
+ if not data:
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 ""))
91
+ data = [_column(df, c) for c in data]
92
+ by = _column(df, by) if isinstance(by, str) else by
93
+ elif isinstance(by, str):
94
+ raise TypeError(f"by={by!r} names a column, which needs a DataFrame first: kx.plot(df, 'x', by={by!r})")
95
+ if not 1 <= len(data) <= 3:
96
+ raise TypeError(f"kx.plot takes x, y and z: up to 3 arrays, got {len(data)}")
97
+ return *data, *[None] * (3 - len(data)), spec, by
98
+
99
+
100
+ def _column(df: pd.DataFrame, name: object) -> pd.Series:
101
+ """df[name], or an error naming the columns that are close."""
102
+ if not isinstance(name, str):
103
+ raise TypeError(f"after a DataFrame, give column names, not {type(name).__name__}")
104
+ if name not in df.columns:
105
+ close = difflib.get_close_matches(name, [str(c) for c in df.columns], n=3)
106
+ hint = f" Did you mean {close}?" if close else f" Columns: {list(df.columns)}"
107
+ raise ValueError(f"no column {name!r} in the DataFrame.{hint}")
108
+ return df[name]
109
+
110
+
111
+ def _common(ax: Axes, name: str, value_axis: str, flags: set[str]) -> None:
112
+ """Flags every kind takes: legend, scales, value-axis format, ticks."""
113
+ values = ax.xaxis if value_axis == "x" else ax.yaxis
114
+ if "grid" in flags: ax.grid(True)
115
+ if flags & {"leg", "legout"} and ax.get_legend_handles_labels()[0]: # nothing labelled (scatter z): none
116
+ old = ax.get_legend()
117
+ outside = "legout" in flags or (name == "area" and "norm" in flags) # a 100% stack has no free corner
118
+ if old is None or outside: # moving a kind's own legend keeps its title
119
+ ax.legend(title=old.get_title().get_text() if old else None, **(OUTSIDE if outside else {}))
120
+ if flags & {"logx", "logxy"}: ax.set_xscale("log")
121
+ if flags & {"logy", "logxy"}: ax.set_yscale("log")
122
+ if "symlogy" in flags: ax.set_yscale("symlog")
123
+ if "zero" in flags: # stretch the value axis to include 0
124
+ lo, hi = values.get_view_interval()
125
+ (ax.set_xlim if value_axis == "x" else ax.set_ylim)(min(lo, 0), max(hi, 0))
126
+ if "eq" in flags: ax.set_aspect("equal")
127
+ if "pct" in flags and not isinstance(values.get_major_formatter(), mpl.ticker.PercentFormatter):
128
+ values.set_major_formatter(mpl.ticker.PercentFormatter(1)) # 0.25 -> 25%; area-norm is already %
129
+ if "si" in flags: values.set_major_formatter(mpl.ticker.EngFormatter(sep="")) # 1500 -> 1.5k
130
+ if "date" in flags:
131
+ loc = mdates.AutoDateLocator()
132
+ ax.xaxis.set_major_locator(loc)
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)
137
+ if "rot" in flags: # rotation stays for ticks matplotlib adds later
138
+ ax.tick_params(axis="x", labelrotation=45)
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()])
@@ -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