bivario 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
bivario-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,50 @@
1
+ Metadata-Version: 2.3
2
+ Name: bivario
3
+ Version: 0.1.0
4
+ Summary: Python library for plotting bivariate choropleth maps
5
+ Author: Kamil Raczycki
6
+ Author-email: Kamil Raczycki <kraczycki@kraina.ai>
7
+ License: MIT
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Topic :: Scientific/Engineering :: GIS
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Operating System :: Unix
18
+ Classifier: Operating System :: MacOS
19
+ Classifier: Operating System :: Microsoft :: Windows
20
+ Requires-Dist: colour-science>=0.4.6
21
+ Requires-Dist: folium>=0.20.0
22
+ Requires-Dist: geopandas>=1.0.1
23
+ Requires-Dist: mapclassify>=2.8.1
24
+ Requires-Dist: matplotlib>=3.9.4
25
+ Requires-Dist: narwhals>=2.8.0
26
+ Requires-Dist: numpy>=2.0.2
27
+ Requires-Python: >=3.10
28
+ Project-URL: Changelog, https://github.com/RaczeQ/bivario/blob/main/CHANGELOG.md
29
+ Project-URL: Homepage, https://github.com/RaczeQ/bivario
30
+ Project-URL: Repository, https://github.com/RaczeQ/bivario
31
+ Description-Content-Type: text/markdown
32
+
33
+ # bivario
34
+ Python library for plotting bivariate choropleth maps in Matplotlib and Folium.
35
+
36
+ <p align="center">
37
+ <img src="https://raw.githubusercontent.com/RaczeQ/bivario/main/images/bivario_logo.png" width="500"><br/>
38
+ </p>
39
+
40
+ <p align="center">
41
+ <img alt="GitHub" src="https://img.shields.io/github/license/raczeq/bivario?logo=mit&logoColor=%23fff">
42
+ <img src="https://img.shields.io/github/checks-status/raczeq/bivario/main?logo=GitHubActions&logoColor=%23fff" alt="Checks">
43
+ <a href="https://github.com/raczeq/bivario/actions/workflows/ci-prod.yml" target="_blank"><img alt="GitHub Workflow Status - PROD" src="https://img.shields.io/github/actions/workflow/status/raczeq/bivario/ci-prod.yml?label=build-prod&logo=GitHubActions&logoColor=%23fff"></a>
44
+ <a href="https://results.pre-commit.ci/latest/github/raczeq/bivario/main" target="_blank"><img src="https://results.pre-commit.ci/badge/github/raczeq/bivario/main.svg" alt="pre-commit.ci status"></a>
45
+ <a href="https://www.codefactor.io/repository/github/raczeq/bivario"><img alt="CodeFactor Grade" src="https://img.shields.io/codefactor/grade/github/raczeq/bivario?logo=codefactor&logoColor=%23fff"></a>
46
+ <a href="https://app.codecov.io/gh/raczeq/bivario/tree/main"><img alt="Codecov" src="https://img.shields.io/codecov/c/github/raczeq/bivario?logo=codecov&token=PRS4E02ZX0&logoColor=%23fff"></a>
47
+ <a href="https://pypi.org/project/bivario" target="_blank"><img src="https://img.shields.io/pypi/v/bivario?color=%2334D058&label=pypi%20package&logo=pypi&logoColor=%23fff" alt="Package version"></a>
48
+ <a href="https://pypi.org/project/bivario" target="_blank"><img src="https://img.shields.io/pypi/pyversions/bivario.svg?color=%2334D058&logo=python&logoColor=%23fff" alt="Supported Python versions"></a>
49
+ <a href="https://pypi.org/project/bivario" target="_blank"><img alt="PyPI - Downloads" src="https://img.shields.io/pypi/dm/bivario"></a>
50
+ </p>
@@ -0,0 +1,18 @@
1
+ # bivario
2
+ Python library for plotting bivariate choropleth maps in Matplotlib and Folium.
3
+
4
+ <p align="center">
5
+ <img src="https://raw.githubusercontent.com/RaczeQ/bivario/main/images/bivario_logo.png" width="500"><br/>
6
+ </p>
7
+
8
+ <p align="center">
9
+ <img alt="GitHub" src="https://img.shields.io/github/license/raczeq/bivario?logo=mit&logoColor=%23fff">
10
+ <img src="https://img.shields.io/github/checks-status/raczeq/bivario/main?logo=GitHubActions&logoColor=%23fff" alt="Checks">
11
+ <a href="https://github.com/raczeq/bivario/actions/workflows/ci-prod.yml" target="_blank"><img alt="GitHub Workflow Status - PROD" src="https://img.shields.io/github/actions/workflow/status/raczeq/bivario/ci-prod.yml?label=build-prod&logo=GitHubActions&logoColor=%23fff"></a>
12
+ <a href="https://results.pre-commit.ci/latest/github/raczeq/bivario/main" target="_blank"><img src="https://results.pre-commit.ci/badge/github/raczeq/bivario/main.svg" alt="pre-commit.ci status"></a>
13
+ <a href="https://www.codefactor.io/repository/github/raczeq/bivario"><img alt="CodeFactor Grade" src="https://img.shields.io/codefactor/grade/github/raczeq/bivario?logo=codefactor&logoColor=%23fff"></a>
14
+ <a href="https://app.codecov.io/gh/raczeq/bivario/tree/main"><img alt="Codecov" src="https://img.shields.io/codecov/c/github/raczeq/bivario?logo=codecov&token=PRS4E02ZX0&logoColor=%23fff"></a>
15
+ <a href="https://pypi.org/project/bivario" target="_blank"><img src="https://img.shields.io/pypi/v/bivario?color=%2334D058&label=pypi%20package&logo=pypi&logoColor=%23fff" alt="Package version"></a>
16
+ <a href="https://pypi.org/project/bivario" target="_blank"><img src="https://img.shields.io/pypi/pyversions/bivario.svg?color=%2334D058&logo=python&logoColor=%23fff" alt="Supported Python versions"></a>
17
+ <a href="https://pypi.org/project/bivario" target="_blank"><img alt="PyPI - Downloads" src="https://img.shields.io/pypi/dm/bivario"></a>
18
+ </p>
@@ -0,0 +1,4 @@
1
+ """Bivario library."""
2
+
3
+ __app_name__ = "bivario"
4
+ __version__ = "0.1.0"
@@ -0,0 +1,421 @@
1
+ import base64
2
+ import io
3
+ import warnings
4
+ from typing import TYPE_CHECKING, Any, Literal, cast
5
+
6
+ import folium
7
+ import geopandas as gpd
8
+ import numpy as np
9
+ from branca.element import MacroElement
10
+ from folium.template import Template
11
+ from mapclassify import classify
12
+ from mapclassify.classifiers import _format_intervals
13
+ from matplotlib import pyplot as plt
14
+ from matplotlib.axes import Axes
15
+ from matplotlib.colors import rgb2hex
16
+ from matplotlib.figure import Figure
17
+ from xyzservices import TileProvider
18
+
19
+ from bivario._legend import DPI, auto_rotate_xticks, plot_bivariate_legend
20
+ from bivario.cmap import (
21
+ ALL_BIVARIATE_MODES_PARAMS,
22
+ BIVARIATE_CMAP_MODES,
23
+ _validate_values,
24
+ bivariate_from_params,
25
+ get_default_bivariate_params,
26
+ )
27
+
28
+ if TYPE_CHECKING:
29
+ from mapclassify.classifiers import MapClassifier
30
+
31
+ from bivario.typing import ValueInput
32
+
33
+ DARK_MODE_TILES_KEYWORDS = ("dark",)
34
+
35
+
36
+ class FloatBivariateMatplotlibLegend(MacroElement): # type: ignore[misc]
37
+ """Adds a floating bivariate legend in HTML canvas on top of the map."""
38
+
39
+ _template = Template(
40
+ """
41
+ {% macro header(this,kwargs) %}
42
+ <style>
43
+ #{{this.get_name()}} {
44
+ position: absolute;
45
+ pointer-events: none;
46
+ {%- for property, value in this.css.items() %}
47
+ {{ property }}: {{ value }};
48
+ {%- endfor %}
49
+ }
50
+ </style>
51
+ {% endmacro %}
52
+
53
+ {% macro html(this,kwargs) %}
54
+ <img id="{{this.get_name()}}" alt="float_image"
55
+ src="{{ this.image }}"
56
+ style="z-index: 999999">
57
+ </img>
58
+ {% endmacro %}
59
+ """
60
+ )
61
+
62
+ def __init__(
63
+ self,
64
+ fig: Figure,
65
+ ax: Axes,
66
+ legend_size_px: int,
67
+ legend_loc: Literal["bl", "br", "tl", "tr"] | None = None,
68
+ legend_offset_px: float | tuple[float, float] | None = None,
69
+ legend_background: bool = True,
70
+ legend_border: bool = True,
71
+ padding_top_right_corner: bool = False,
72
+ **kwargs: Any,
73
+ ) -> None:
74
+ """
75
+ Create a floating bivariate legend for folium maps.
76
+
77
+ Args:
78
+ fig (Figure): Matplotlib figure containing the legend.
79
+ ax (Axes): Matplotlib axes containing the legend.
80
+ legend_size_px (int): Size of the legend in pixels.
81
+ legend_loc (Literal["bl", "br", "tl", "tr"] | None, optional): Location of the legend
82
+ on the map. Can be "bl" (bottom-left), "br" (bottom-right), "tl" (top-left),
83
+ or "tr" (top-right). Defaults to "bl".
84
+ legend_offset_px (float | tuple[float, float] | None, optional): Offset of the legend
85
+ from the specified location in pixels. If None, uses default offsets based on
86
+ location. Defaults to None.
87
+ legend_background (bool, optional): Whether to add a background to the legend.
88
+ Defaults to True.
89
+ legend_border (bool, optional): Whether to add a border to the legend.
90
+ Defaults to True.
91
+ padding_top_right_corner (bool, optional): Whether to add padding for top-right
92
+ legend corner for readabilty. Defaults to False.
93
+ **kwargs (Any): Additional CSS properties for the legend.
94
+ """
95
+ super().__init__()
96
+ self._name = "FloatBivariateMatplotlibLegend"
97
+
98
+ self.css = kwargs
99
+
100
+ if legend_background:
101
+ self.css["background"] = "rgba(255, 255, 255, 0.8)"
102
+ self.css["padding"] = "2px" if padding_top_right_corner else "0 0 2px 2px"
103
+
104
+ if legend_border:
105
+ self.css["border"] = "2px solid rgba(0, 0, 0, 0.2)"
106
+ self.css["border-radius"] = "4px"
107
+ self.css["background-clip"] = "padding-box"
108
+
109
+ self.resize_fig(fig=fig, ax=ax, legend_size_px=legend_size_px)
110
+
111
+ self.image = "data:image/svg+xml;base64," + self.figure_to_base64_string(fig)
112
+
113
+ plt.close()
114
+
115
+ self.css.pop("bottom", None)
116
+ self.css.pop("top", None)
117
+ self.css.pop("left", None)
118
+ self.css.pop("right", None)
119
+ self.css.pop("transform", None)
120
+
121
+ legend_loc = legend_loc or "bl"
122
+
123
+ match legend_loc:
124
+ case "bl":
125
+ legend_position_x, legend_position_y = self.parse_offset(
126
+ legend_offset_px or (5, 40)
127
+ )
128
+ self.css["bottom"] = f"{legend_position_y}px"
129
+ self.css["left"] = f"{legend_position_x}px"
130
+ case "br":
131
+ legend_position_x, legend_position_y = self.parse_offset(
132
+ legend_offset_px or (5, 19)
133
+ )
134
+ self.css["bottom"] = f"{legend_position_y}px"
135
+ self.css["right"] = f"{legend_position_x}px"
136
+ case "tl":
137
+ legend_position_x, legend_position_y = self.parse_offset(
138
+ legend_offset_px or (10, 79)
139
+ )
140
+ self.css["top"] = f"{legend_position_y}px"
141
+ self.css["left"] = f"{legend_position_x}px"
142
+ case "tr":
143
+ legend_position_x, legend_position_y = self.parse_offset(
144
+ legend_offset_px or (10, 10)
145
+ )
146
+ self.css["top"] = f"{legend_position_y}px"
147
+ self.css["right"] = f"{legend_position_x}px"
148
+
149
+ print(self.css)
150
+
151
+ def resize_fig(
152
+ self, fig: Figure, ax: Axes, legend_size_px: int, tolerance_px: float = 0.1
153
+ ) -> None:
154
+ """Resize figure so that the Axes data area matches the target legend size in pixels."""
155
+ fig.canvas.draw()
156
+ renderer = fig.canvas.get_renderer()
157
+
158
+ # Get bounding boxes (in display / pixel coordinates)
159
+ bbox_ax = ax.get_window_extent(renderer)
160
+
161
+ # Compute inner data area size (in pixels)
162
+ data_width_px = bbox_ax.width
163
+ data_height_px = bbox_ax.height
164
+
165
+ while (
166
+ abs(legend_size_px - data_width_px) > tolerance_px
167
+ or abs(legend_size_px - data_height_px) > tolerance_px
168
+ ):
169
+ # Calculate scale factor so data area = target_data_px
170
+ scale = legend_size_px / min(data_width_px, data_height_px)
171
+
172
+ # Compute new figure size (inches)
173
+ w_in, h_in = fig.get_size_inches()
174
+ new_w_in = w_in * scale
175
+ new_h_in = h_in * scale
176
+
177
+ fig.set_size_inches(new_w_in, new_h_in)
178
+
179
+ auto_rotate_xticks(ax)
180
+
181
+ # Redraw with new size
182
+ fig.canvas.draw()
183
+
184
+ renderer = fig.canvas.get_renderer()
185
+
186
+ # Get bounding boxes (in display / pixel coordinates)
187
+ bbox_ax = ax.get_window_extent(renderer)
188
+
189
+ data_width_px = bbox_ax.width
190
+ data_height_px = bbox_ax.height
191
+
192
+ def figure_to_base64_string(self, fig: Figure) -> str:
193
+ """Convert Matplotlib figure to base64-encoded SVG string."""
194
+ buffered = io.BytesIO()
195
+ fig.savefig(
196
+ buffered, format="svg", transparent=True, dpi=DPI, bbox_inches="tight", pad_inches=0
197
+ )
198
+ return base64.b64encode(buffered.getvalue()).decode("utf-8")
199
+
200
+ def parse_offset(self, legend_offset_px: float | tuple[float, float]) -> tuple[float, float]:
201
+ """Parse legend offset into x and y components."""
202
+ if isinstance(legend_offset_px, (int, float)):
203
+ legend_position_x = legend_position_y = legend_offset_px
204
+ else:
205
+ legend_position_x, legend_position_y = legend_offset_px
206
+ return (legend_position_x, legend_position_y)
207
+
208
+
209
+ def explore_bivariate_data(
210
+ gdf: gpd.GeoDataFrame,
211
+ column_a: "str | ValueInput",
212
+ column_b: "str | ValueInput",
213
+ column_a_label: str | None = None,
214
+ column_b_label: str | None = None,
215
+ scheme: str | None | bool = True,
216
+ k: int = 5,
217
+ tiles: str | folium.TileLayer | TileProvider | None = None,
218
+ cmap_mode: BIVARIATE_CMAP_MODES = "name",
219
+ cmap_params: ALL_BIVARIATE_MODES_PARAMS | None = None,
220
+ cmap_kwargs: dict[str, Any] | None = None,
221
+ dark_mode: bool | None = None,
222
+ alpha: bool = True,
223
+ alpha_norm_quantile: float = 0.9,
224
+ legend: bool = True,
225
+ legend_size_px: int = 200,
226
+ legend_loc: Literal["bl", "br", "tl", "tr"] | None = None,
227
+ legend_offset_px: float | tuple[float, float] | None = None,
228
+ legend_background: bool = True,
229
+ legend_border: bool = True,
230
+ legend_kwargs: dict[str, Any] | None = None,
231
+ **kwargs: Any,
232
+ ) -> folium.Map:
233
+ """
234
+ Explore geospatial data with a bivariate colormap on a folium map.
235
+
236
+ Args:
237
+ gdf (gpd.GeoDataFrame): Geospatial data to plot.
238
+ column_a (str | ValueInput): Column name for the first variable or list/array of values.
239
+ column_b (str | ValueInput): Column name for the second variable or list/array of values.
240
+ column_a_label (str | None, optional): Label for column a. If None, will use column name.
241
+ Defaults to None.
242
+ column_b_label (str | None, optional): Label for column b. If None, will use column name.
243
+ Defaults to None.
244
+ scheme (str | None | bool, optional): Mapclassify binning scheme for the data. If True, uses
245
+ "NaturalBreaks". If False, no binning is applied. If str, uses the specified scheme.
246
+ If None, no binning is applied. Defaults to True.
247
+ k (int, optional): Number of classes for binning. Defaults to 5.
248
+ tiles (str | folium.TileLayer | TileProvider | None, optional): Tile layer for the map.
249
+ If None, will set based on dark mode - "CartoDB DarkMatter" for the dark mode, and
250
+ "CartoDB Positron" for the light mode. Defaults to None.
251
+ cmap_mode (BIVARIATE_CMAP_MODES, optional): Bivariate colormap mode to use. Can be
252
+ "accents", "cmaps", "corners", or "name". Defaults to "name".
253
+ cmap_params (ALL_BIVARIATE_MODES_PARAMS | None, optional): Parameters for the bivariate
254
+ colormap. If None, will use default parameters based on the cmap_mode. Defaults to None.
255
+ cmap_kwargs (dict[str, Any] | None, optional): Additional keyword arguments for the
256
+ bivariate colormap generation. Defaults to None.
257
+ dark_mode (bool | None, optional): Whether to use dark mode for the map tiles. If None,
258
+ will infer from the tiles if provided, otherwise defaults to False. Defaults to None
259
+ alpha (bool, optional): Whether to apply alpha transparency based on the data values. Will
260
+ set higher values to be more opaque. It is calculated based on the normalized values of
261
+ both columns. Defaults to True.
262
+ alpha_norm_quantile (float, optional): Quantile for normalizing alpha transparency.
263
+ Will be used to calculate the maximum value for alpha scaling. It is recommended to use
264
+ value below 1 to avoid outliers affecting the transparency too much. Defaults to 0.9.
265
+ legend (bool, optional): Whether to add a bivariate legend to the map. Defaults to True.
266
+ legend_size_px (int, optional): Size of the legend in pixels. Defaults to 200.
267
+ legend_loc (Literal["bl", "br", "tl", "tr"] | None, optional): Location of the legend
268
+ on the map. Can be "bl" (bottom-left), "br" (bottom-right), "tl" (top-left),
269
+ or "tr" (top-right). Defaults to "bl".
270
+ legend_offset_px (float | tuple[float, float] | None, optional): Offset of the legend
271
+ from the specified location in pixels. If None, uses default offsets based on location.
272
+ Defaults to None.
273
+ legend_background (bool, optional): Whether to add a background to the legend.
274
+ Defaults to True.
275
+ legend_border (bool, optional): Whether to add a border to the legend. Defaults to True.
276
+ legend_kwargs (dict[str, Any] | None, optional): Additional keyword arguments for the
277
+ legend plotting function. Defaults to None.
278
+ **kwargs (Any): Additional keyword arguments for the folium map.
279
+
280
+ Returns:
281
+ folium.Map: Folium map with the bivariate colormap applied.
282
+ """
283
+ # alpha - yes / no - allow iterable as list of floats between 0 and 1
284
+
285
+ for column in (column_a, column_b):
286
+ if isinstance(column, str) and column not in gdf.columns:
287
+ raise ValueError(f"Column '{column}' not found in GeoDataFrame.")
288
+
289
+ if cmap_params is None:
290
+ cmap_params = get_default_bivariate_params(cmap_mode)
291
+
292
+ original_values_a = gdf[column_a] if isinstance(column_a, str) else column_a
293
+ original_values_b = gdf[column_b] if isinstance(column_b, str) else column_b
294
+
295
+ _values_a, _values_b = _validate_values(
296
+ gdf[column_a] if isinstance(column_a, str) else column_a,
297
+ gdf[column_b] if isinstance(column_b, str) else column_b,
298
+ )
299
+
300
+ # If tiles are not defined - set based on dark mode
301
+ if tiles is None:
302
+ if dark_mode is None:
303
+ dark_mode = False
304
+
305
+ tiles = "CartoDB DarkMatter" if dark_mode else "CartoDB Positron"
306
+ # If tiles are defined, set dark mode based on tiles if not defined
307
+ elif dark_mode is None:
308
+ dark_mode = False
309
+ tiles_name = ""
310
+ if isinstance(tiles, str):
311
+ tiles_name = tiles.lower()
312
+ elif isinstance(tiles, TileProvider):
313
+ tiles_name = str(tiles.name).lower()
314
+
315
+ for keyword in DARK_MODE_TILES_KEYWORDS:
316
+ if keyword in tiles_name:
317
+ dark_mode = True
318
+ break
319
+
320
+ cmap_kwargs = cmap_kwargs or {}
321
+ if "dark_mode" not in cmap_kwargs:
322
+ cmap_kwargs["dark_mode"] = dark_mode
323
+
324
+ set_alpha = alpha # now its bool, but can be a list of values, then check if not empty
325
+
326
+ if set_alpha:
327
+ if alpha_norm_quantile < 0 or alpha_norm_quantile > 1:
328
+ raise ValueError("alpha_norm_quantile must be between 0 and 1 (inclusive).")
329
+
330
+ alpha_values = np.sqrt(
331
+ np.minimum(
332
+ 1,
333
+ np.maximum(
334
+ _values_a / np.quantile(_values_a, alpha_norm_quantile),
335
+ _values_b / np.quantile(_values_b, alpha_norm_quantile),
336
+ ),
337
+ )
338
+ ).tolist()
339
+ if "style_kwds" not in kwargs:
340
+ kwargs["style_kwds"] = {}
341
+
342
+ kwargs["style_kwds"]["style_function"] = lambda x: dict(
343
+ opacity=0, fillOpacity=alpha_values[int(x["id"])]
344
+ )
345
+
346
+ tick_labels_a = None
347
+ tick_labels_b = None
348
+
349
+ if isinstance(scheme, bool):
350
+ scheme = "NaturalBreaks" if scheme else None
351
+
352
+ if scheme is not None:
353
+ binning_a = cast("MapClassifier", classify(_values_a, scheme=scheme, k=k))
354
+ binning_b = cast("MapClassifier", classify(_values_b, scheme=scheme, k=k))
355
+
356
+ _values_a = binning_a.yb
357
+ _values_b = binning_b.yb
358
+
359
+ tick_labels_a = [_l.replace(".0", "") for _l in _format_intervals(binning_a, "{:,.1f}")[0]]
360
+ tick_labels_b = [_l.replace(".0", "") for _l in _format_intervals(binning_b, "{:,.1f}")[0]]
361
+
362
+ values_cmap = bivariate_from_params(
363
+ values_a=_values_a,
364
+ values_b=_values_b,
365
+ mode=cmap_mode,
366
+ params=cmap_params,
367
+ **cmap_kwargs,
368
+ )
369
+
370
+ hex_values = [rgb2hex(values_cmap[i, :]) for i in range(values_cmap.shape[0])]
371
+
372
+ if "legend" in kwargs:
373
+ kwargs.pop("legend")
374
+
375
+ if "embed" in kwargs:
376
+ kwargs.pop("embed")
377
+ warnings.warn(
378
+ "Embed folium parameter must be set to true. Ignoring user definition.", stacklevel=0
379
+ )
380
+
381
+ m = gdf.explore(
382
+ color=hex_values,
383
+ legend=False,
384
+ tiles=tiles,
385
+ embed=True,
386
+ **kwargs,
387
+ )
388
+
389
+ if legend:
390
+ legend_kwargs = legend_kwargs or {}
391
+
392
+ ax = plot_bivariate_legend(
393
+ values_a=original_values_a,
394
+ values_b=original_values_b,
395
+ cmap_mode=cmap_mode,
396
+ cmap_params=cmap_params,
397
+ cmap_kwargs=cmap_kwargs,
398
+ label_a=column_a_label,
399
+ label_b=column_b_label,
400
+ tick_labels_a=tick_labels_a,
401
+ tick_labels_b=tick_labels_b,
402
+ font_colour="#333" if legend_background else None,
403
+ grid_size=legend_size_px if scheme is None else k,
404
+ dark_mode=dark_mode,
405
+ **legend_kwargs,
406
+ )
407
+
408
+ fig = cast("Figure", ax.figure)
409
+
410
+ FloatBivariateMatplotlibLegend(
411
+ fig=fig,
412
+ ax=ax,
413
+ legend_size_px=legend_size_px,
414
+ legend_loc=legend_loc,
415
+ legend_offset_px=legend_offset_px,
416
+ legend_background=legend_background,
417
+ legend_border=legend_border,
418
+ padding_top_right_corner=scheme is not None,
419
+ ).add_to(m)
420
+
421
+ return m
@@ -0,0 +1,173 @@
1
+ from contextlib import suppress
2
+ from typing import TYPE_CHECKING, Any, cast
3
+
4
+ import narwhals as nw
5
+ import numpy as np
6
+ from matplotlib import pyplot as plt
7
+ from matplotlib.axes import Axes
8
+ from PIL import Image
9
+
10
+ from bivario.cmap import (
11
+ ALL_BIVARIATE_MODES_PARAMS,
12
+ BIVARIATE_CMAP_MODES,
13
+ _validate_values,
14
+ bivariate_from_params,
15
+ get_default_bivariate_params,
16
+ )
17
+
18
+ if TYPE_CHECKING:
19
+ from bivario.typing import ValueInput
20
+
21
+ DPI = 100
22
+
23
+
24
+ def plot_bivariate_legend(
25
+ values_a: "ValueInput",
26
+ values_b: "ValueInput",
27
+ ax: Axes | None = None,
28
+ cmap_mode: BIVARIATE_CMAP_MODES = "name",
29
+ cmap_params: ALL_BIVARIATE_MODES_PARAMS | None = None,
30
+ cmap_kwargs: dict[str, Any] | None = None,
31
+ grid_size: int | None = None,
32
+ label_a: str | None = None,
33
+ label_b: str | None = None,
34
+ tick_labels_a: list[Any] | None = None,
35
+ tick_labels_b: list[Any] | None = None,
36
+ dark_mode: bool = False,
37
+ font_colour: str | None = None,
38
+ tick_fontsize_px: int = 10,
39
+ ) -> Axes:
40
+ if (tick_labels_a is not None and tick_labels_b is None) or (
41
+ tick_labels_a is None and tick_labels_b is not None
42
+ ):
43
+ raise ValueError("Both tick labels for a and b values must be either None, or present.")
44
+
45
+ if ax is None:
46
+ _, ax = plt.subplots(dpi=DPI, layout="compressed")
47
+
48
+ parsed_values_a, parsed_values_b = _validate_values(values_a, values_b)
49
+
50
+ label_a = label_a or _try_parse_label(values_a) or "Value A"
51
+ label_b = label_b or _try_parse_label(values_b) or "Value B"
52
+
53
+ cmap_params = cmap_params or get_default_bivariate_params(cmap_mode)
54
+
55
+ cmap_kwargs = cmap_kwargs or {}
56
+ if "dark_mode" not in cmap_kwargs:
57
+ cmap_kwargs["dark_mode"] = dark_mode
58
+
59
+ grid_size = grid_size or 100
60
+ xx, yy = np.mgrid[0:grid_size, 0:grid_size]
61
+
62
+ legend_cmap = bivariate_from_params(
63
+ values_a=xx,
64
+ values_b=yy,
65
+ mode=cmap_mode,
66
+ params=cmap_params,
67
+ **cmap_kwargs,
68
+ )
69
+
70
+ img = Image.fromarray(np.uint8((legend_cmap) * 255))
71
+
72
+ tick_fontsize_pt = tick_fontsize_px * 72 / ax.figure.dpi
73
+
74
+ colour = font_colour or ("white" if dark_mode else "black")
75
+ _set_colour_theme(ax, colour)
76
+ y_min = parsed_values_a.min()
77
+ y_max = parsed_values_a.max()
78
+ x_min = parsed_values_b.min()
79
+ x_max = parsed_values_b.max()
80
+ height_range = y_max - y_min
81
+ width_range = x_max - x_min
82
+ aspect = width_range / height_range
83
+ ax.imshow(
84
+ img,
85
+ origin="lower",
86
+ extent=(x_min, x_max, y_min, y_max) if tick_labels_a is None else None,
87
+ aspect=aspect if tick_labels_a is None else None,
88
+ interpolation="nearest",
89
+ )
90
+ ax.tick_params(axis="both", which="both", length=0)
91
+
92
+ ax.annotate(
93
+ "",
94
+ xy=(0, 1),
95
+ xytext=(0, 0),
96
+ arrowprops=dict(
97
+ arrowstyle="->",
98
+ lw=1,
99
+ color=colour,
100
+ shrinkA=0,
101
+ shrinkB=0,
102
+ ),
103
+ xycoords="axes fraction",
104
+ )
105
+ ax.annotate(
106
+ "",
107
+ xy=(1, 0),
108
+ xytext=(0, 0),
109
+ arrowprops=dict(
110
+ arrowstyle="->",
111
+ lw=1,
112
+ color=colour,
113
+ shrinkA=0,
114
+ shrinkB=0,
115
+ ),
116
+ xycoords="axes fraction",
117
+ )
118
+
119
+ ax.set_ylabel(label_a, fontsize=tick_fontsize_pt)
120
+ ax.set_xlabel(label_b, fontsize=tick_fontsize_pt)
121
+ ax.tick_params(labelsize=tick_fontsize_pt)
122
+
123
+ if tick_labels_a:
124
+ yticks = np.linspace(-0.5, legend_cmap.shape[0] - 0.5, len(tick_labels_a))
125
+ ax.set_yticks(yticks)
126
+ ax.set_yticklabels(tick_labels_a)
127
+
128
+ if tick_labels_b:
129
+ xticks = np.linspace(-0.5, legend_cmap.shape[1] - 0.5, len(tick_labels_b))
130
+ ax.set_xticks(xticks)
131
+ ax.set_xticklabels(tick_labels_b)
132
+ auto_rotate_xticks(ax)
133
+
134
+ return ax
135
+
136
+
137
+ def _try_parse_label(values: "ValueInput") -> str | None:
138
+ with suppress(TypeError):
139
+ return cast("str", nw.from_native(values, series_only=True).name)
140
+
141
+ return None
142
+
143
+
144
+ def _set_colour_theme(ax: Axes, colour: str) -> None:
145
+ # ticks and tick labels
146
+ ax.tick_params(axis="both", which="both", colors=colour)
147
+
148
+ # axis labels and title
149
+ ax.xaxis.label.set_color(colour)
150
+ ax.yaxis.label.set_color(colour)
151
+
152
+ # spines (borders)
153
+ for spine in ax.spines.values():
154
+ spine.set_visible(False)
155
+
156
+
157
+ def auto_rotate_xticks(ax: Axes, rotation: float = 45) -> None:
158
+ """Detect overlapping x-tick labels and rotate them if needed."""
159
+ fig = ax.figure
160
+ fig.canvas.draw()
161
+
162
+ # Get bounding boxes of tick labels in display coords
163
+ tick_labels = ax.get_xticklabels()
164
+ bboxes = [label.get_window_extent() for label in tick_labels if label.get_text()]
165
+
166
+ overlap = False
167
+ for i in range(len(bboxes) - 1):
168
+ if bboxes[i].overlaps(bboxes[i + 1]):
169
+ overlap = True
170
+ break
171
+
172
+ if overlap:
173
+ plt.setp(tick_labels, rotation=rotation, ha="right")
@@ -0,0 +1,299 @@
1
+ """
2
+ Bivariate colourmaps generators.
3
+
4
+ Returned values are in RGB colour space as floats in range from 0 to 1.
5
+
6
+ Colour operations are done in the OKLab colour space.
7
+ """
8
+
9
+ from typing import TYPE_CHECKING, Any, Literal, cast
10
+
11
+ import narwhals as nw
12
+ import numpy as np
13
+ from colour import Oklab_to_XYZ, XYZ_to_Oklab, XYZ_to_sRGB, sRGB_to_XYZ
14
+ from matplotlib.colors import Colormap, to_rgb
15
+ from matplotlib.pyplot import get_cmap
16
+ from matplotlib.typing import ColourType
17
+
18
+ from bivario.palettes import BIVARIATE_CORNER_PALETTES
19
+
20
+ if TYPE_CHECKING:
21
+ import numpy.typing as npt
22
+
23
+ from bivario.typing import BivariateColourmap, NumericArray, ValueInput
24
+
25
+ NumericKinds = {"b", "i", "u", "f"}
26
+
27
+ __all__ = [
28
+ "bivariate_from_cmaps",
29
+ "bivariate_from_accents",
30
+ "bivariate_from_corners",
31
+ "bivariate_from_name",
32
+ "bivariate_from_params",
33
+ ]
34
+
35
+ BIVARIATE_CMAP_MODES = Literal["accents", "cmaps", "corners", "name"]
36
+
37
+ CMAPS_PARAMS = tuple[str | Colormap, str | Colormap]
38
+ CORNERS_PARAMS = tuple[ColourType, ColourType, ColourType, ColourType]
39
+ ACCENTS_PARAMS = tuple[ColourType, ColourType]
40
+ ALL_BIVARIATE_MODES_PARAMS = str | ACCENTS_PARAMS | CMAPS_PARAMS | CORNERS_PARAMS
41
+
42
+
43
+ def bivariate_from_params(
44
+ values_a: "ValueInput",
45
+ values_b: "ValueInput",
46
+ params: ALL_BIVARIATE_MODES_PARAMS,
47
+ mode: BIVARIATE_CMAP_MODES | None = None,
48
+ **kwargs: Any,
49
+ ) -> "BivariateColourmap":
50
+ """Generate a 2D bivariate palette."""
51
+ # can operate on all other functions, used for API usage
52
+
53
+ # match types first - detect corners and name
54
+ if isinstance(params, str):
55
+ name = params
56
+ return bivariate_from_name(values_a=values_a, values_b=values_b, name=name, **kwargs)
57
+ # detected corners
58
+ elif len(params) == 4:
59
+ accent_a, accent_b, low, high = params
60
+ return bivariate_from_corners(
61
+ values_a=values_a,
62
+ values_b=values_b,
63
+ accent_a=accent_a,
64
+ accent_b=accent_b,
65
+ low=low,
66
+ high=high,
67
+ )
68
+
69
+ match mode:
70
+ case "accents":
71
+ accent_a, accent_b = cast("ACCENTS_PARAMS", params)
72
+ return bivariate_from_accents(
73
+ values_a=values_a, values_b=values_b, accent_a=accent_a, accent_b=accent_b, **kwargs
74
+ )
75
+ case "cmaps":
76
+ cmap_a, cmap_b = cast("CMAPS_PARAMS", params) # type: ignore[redundant-cast]
77
+ return bivariate_from_cmaps(
78
+ values_a=values_a, values_b=values_b, cmap_a=cmap_a, cmap_b=cmap_b, **kwargs
79
+ )
80
+ case "corners":
81
+ accent_a, accent_b, low, high = cast("CORNERS_PARAMS", params)
82
+ return bivariate_from_corners(
83
+ values_a=values_a,
84
+ values_b=values_b,
85
+ accent_a=accent_a,
86
+ accent_b=accent_b,
87
+ low=low,
88
+ high=high,
89
+ )
90
+ case "name":
91
+ name = cast("str", params)
92
+ return bivariate_from_name(values_a=values_a, values_b=values_b, name=name, **kwargs)
93
+
94
+ case _:
95
+ raise ValueError(f"Unknown bivariate cmap mode: '{mode}'.")
96
+
97
+
98
+ def get_default_bivariate_params(mode: BIVARIATE_CMAP_MODES) -> ALL_BIVARIATE_MODES_PARAMS:
99
+ match mode:
100
+ case "accents":
101
+ accent_a = (0.95, 0.40, 0.20)
102
+ accent_b = (0.10, 0.70, 0.65)
103
+ return (accent_a, accent_b)
104
+ case "cmaps":
105
+ return ("Oranges", "Blues")
106
+ case "corners":
107
+ loaded_palette = BIVARIATE_CORNER_PALETTES["electric_neon"]
108
+ return (
109
+ loaded_palette.accent_a,
110
+ loaded_palette.accent_b,
111
+ loaded_palette.low,
112
+ loaded_palette.high,
113
+ )
114
+ case "name":
115
+ return "electric_neon"
116
+
117
+ case _:
118
+ raise ValueError(f"Unknown bivariate cmap mode: '{mode}'.")
119
+
120
+
121
+ def bivariate_from_cmaps(
122
+ values_a: "ValueInput",
123
+ values_b: "ValueInput",
124
+ cmap_a: str | Colormap,
125
+ cmap_b: str | Colormap,
126
+ ) -> "BivariateColourmap":
127
+ """Blend two 1D colourmaps into a 2D bivariate palette."""
128
+ _values_a, _values_b = _validate_values(values_a, values_b)
129
+
130
+ va_plot = _normalize_values(_values_a)
131
+ vb_plot = _normalize_values(_values_b)
132
+
133
+ cmap_a = get_cmap(cmap_a)
134
+ cmap_b = get_cmap(cmap_b)
135
+
136
+ va_colour = cmap_a(va_plot)[..., :3]
137
+ vb_colour = cmap_b(vb_plot)[..., :3]
138
+
139
+ va_colour_oklab = XYZ_to_Oklab(sRGB_to_XYZ(va_colour))
140
+ vb_colour_oklab = XYZ_to_Oklab(sRGB_to_XYZ(vb_colour))
141
+
142
+ z_colour = np.zeros_like(va_colour, dtype=float)
143
+
144
+ it = np.nditer(np.zeros(z_colour.shape[:-1]), flags=["multi_index"], op_flags=[["readwrite"]])
145
+ while not it.finished:
146
+ pos_a, pos_b = va_plot[it.multi_index], vb_plot[it.multi_index]
147
+
148
+ loc_diff = pos_b - pos_a
149
+ lerp_t = (loc_diff + 1) / 2
150
+
151
+ colour_a = va_colour_oklab[it.multi_index]
152
+ colour_b = vb_colour_oklab[it.multi_index]
153
+
154
+ mixed_colour = _lerp(colour_a, colour_b, lerp_t)
155
+ mixed_colour_rgb = np.clip(XYZ_to_sRGB(Oklab_to_XYZ(mixed_colour)), 0, 1)
156
+
157
+ z_colour[it.multi_index] = mixed_colour_rgb
158
+ it.iternext()
159
+
160
+ return z_colour
161
+
162
+
163
+ def bivariate_from_corners(
164
+ values_a: "ValueInput",
165
+ values_b: "ValueInput",
166
+ accent_a: ColourType,
167
+ accent_b: ColourType,
168
+ low: ColourType,
169
+ high: ColourType,
170
+ # accent_a=(0.95, 0.40, 0.20),
171
+ # accent_b=(0.10, 0.70, 0.65),
172
+ # low=(0.95, 0.85, 0.55),
173
+ # high=(0.15, 0.20, 0.50),
174
+ ) -> "BivariateColourmap":
175
+ """Generate a 2D bivariate palette from four RGB values."""
176
+ _values_a, _values_b = _validate_values(values_a, values_b)
177
+
178
+ va_plot = _normalize_values(_values_a)
179
+ vb_plot = _normalize_values(_values_b)
180
+
181
+ z_colour = np.zeros((*va_plot.shape, 3), dtype=float)
182
+
183
+ a_colour_oklab = XYZ_to_Oklab(sRGB_to_XYZ(np.array(to_rgb(accent_a))))
184
+ b_colour_oklab = XYZ_to_Oklab(sRGB_to_XYZ(np.array(to_rgb(accent_b))))
185
+ low_colour_oklab = XYZ_to_Oklab(sRGB_to_XYZ(np.array(to_rgb(low))))
186
+ high_colour_oklab = XYZ_to_Oklab(sRGB_to_XYZ(np.array(to_rgb(high))))
187
+
188
+ it = np.nditer(np.zeros(z_colour.shape[:-1]), flags=["multi_index"], op_flags=[["readwrite"]])
189
+ while not it.finished:
190
+ pos_a, pos_b = va_plot[it.multi_index], vb_plot[it.multi_index]
191
+
192
+ first_colour = _lerp(low_colour_oklab, a_colour_oklab, pos_a)
193
+ second_colour = _lerp(b_colour_oklab, high_colour_oklab, pos_a)
194
+ middle_colour = _lerp(first_colour, second_colour, pos_b)
195
+
196
+ mixed_colour_rgb = np.clip(XYZ_to_sRGB(Oklab_to_XYZ(middle_colour)), 0, 1)
197
+
198
+ z_colour[it.multi_index] = mixed_colour_rgb
199
+ it.iternext()
200
+
201
+ return z_colour
202
+
203
+
204
+ def bivariate_from_accents(
205
+ values_a: "ValueInput",
206
+ values_b: "ValueInput",
207
+ accent_a: ColourType,
208
+ accent_b: ColourType,
209
+ *,
210
+ dark_mode: bool = False,
211
+ light: ColourType = (1, 1, 1),
212
+ dark: ColourType = (0.15, 0.15, 0.15),
213
+ ) -> "BivariateColourmap":
214
+ """Blend two accent colours into a 2D bivariate palette."""
215
+ if dark_mode:
216
+ return bivariate_from_corners(values_a, values_b, accent_a, accent_b, low=dark, high=light)
217
+
218
+ return bivariate_from_corners(values_a, values_b, accent_a, accent_b, low=light, high=dark)
219
+
220
+
221
+ def bivariate_from_name(
222
+ values_a: "ValueInput",
223
+ values_b: "ValueInput",
224
+ name: str,
225
+ dark_mode: bool = False,
226
+ invert_accents: bool = False,
227
+ ) -> "BivariateColourmap":
228
+ """Load bivariate palette from name."""
229
+ loaded_palette = BIVARIATE_CORNER_PALETTES.get(name)
230
+ if loaded_palette is None:
231
+ raise ValueError(
232
+ f"Unrecognized palette: {name}. "
233
+ f"Available palettes: {list(BIVARIATE_CORNER_PALETTES.keys())}."
234
+ )
235
+
236
+ accent_a, accent_b = loaded_palette.accent_a, loaded_palette.accent_b
237
+ if invert_accents:
238
+ accent_a, accent_b = accent_b, accent_a
239
+
240
+ low, high = loaded_palette.low, loaded_palette.high
241
+ if dark_mode:
242
+ low, high = high, low
243
+
244
+ return bivariate_from_corners(
245
+ values_a=values_a,
246
+ values_b=values_b,
247
+ accent_a=accent_a,
248
+ accent_b=accent_b,
249
+ low=low,
250
+ high=high,
251
+ )
252
+
253
+
254
+ def _lerp(
255
+ c_a: "npt.NDArray[np.floating]", c_b: "npt.NDArray[np.floating]", t: float
256
+ ) -> "npt.NDArray[np.floating]":
257
+ return (1 - t) * c_a + t * c_b
258
+
259
+
260
+ def _validate_values(
261
+ values_a: "ValueInput", values_b: "ValueInput"
262
+ ) -> "tuple[NumericArray, NumericArray]":
263
+ values_a_array = _values_to_numpy(values_a)
264
+ values_b_array = _values_to_numpy(values_b)
265
+
266
+ if values_a_array.shape != values_b_array.shape:
267
+ raise ValueError(
268
+ f"Two arrays have different shape: {values_a_array.shape} vs {values_b_array.shape}."
269
+ )
270
+
271
+ return values_a_array, values_b_array
272
+
273
+
274
+ def _normalize_values(values: "NumericArray") -> "NumericArray":
275
+ v_min: float = values.astype(float).min()
276
+ v_max: float = values.astype(float).max()
277
+
278
+ # Rescale values to fit into colourmap range (0->1)
279
+ return (values - v_min) / (v_max - v_min)
280
+
281
+
282
+ def _values_to_numpy(values: "ValueInput") -> "NumericArray":
283
+ try:
284
+ values_array: np.ndarray = nw.from_native(values, series_only=True).to_numpy()
285
+ except TypeError:
286
+ values_array = np.array(values)
287
+
288
+ _validate_numeric_noncomplex(values_array)
289
+
290
+ return values_array
291
+
292
+
293
+ def _validate_numeric_noncomplex(arr: "npt.NDArray[Any]") -> None:
294
+ if arr.dtype.kind not in NumericKinds:
295
+ raise TypeError(
296
+ f"unsupported dtype {arr.dtype}; only boolean/integer/unsigned/float allowed"
297
+ )
298
+ if np.issubdtype(arr.dtype, np.complexfloating):
299
+ raise TypeError("complex dtypes are not allowed")
@@ -0,0 +1,169 @@
1
+ """Predefined corner palettes for bivariate colormaps."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+ colour_tuple = tuple[float, float, float]
6
+
7
+
8
+ @dataclass
9
+ class BivariateCornerPalette:
10
+ """Bivariate palette defined by corner colours."""
11
+
12
+ accent_a: colour_tuple
13
+ accent_b: colour_tuple
14
+ low: colour_tuple
15
+ high: colour_tuple
16
+
17
+
18
+ BIVARIATE_CORNER_PALETTES = {
19
+ "plum_mint": BivariateCornerPalette(
20
+ accent_a=(0.66, 0.36, 0.80),
21
+ accent_b=(0.07, 0.64, 0.58),
22
+ low=(0.97, 0.94, 0.70),
23
+ high=(0.12, 0.14, 0.40),
24
+ ),
25
+ "peacock_court": BivariateCornerPalette(
26
+ accent_a=(0.58, 0.18, 0.70),
27
+ accent_b=(0.10, 0.58, 0.66),
28
+ low=(0.98, 0.97, 0.86),
29
+ high=(0.10, 0.12, 0.22),
30
+ ),
31
+ "rosewood_pine": BivariateCornerPalette(
32
+ accent_a=(0.88, 0.26, 0.60),
33
+ accent_b=(0.07, 0.62, 0.40),
34
+ low=(0.98, 0.96, 0.72),
35
+ high=(0.14, 0.20, 0.36),
36
+ ),
37
+ "flamingo_lagoon": BivariateCornerPalette(
38
+ accent_a=(0.96, 0.44, 0.60),
39
+ accent_b=(0.14, 0.70, 0.56),
40
+ low=(0.99, 0.98, 0.92),
41
+ high=(0.12, 0.18, 0.22),
42
+ ),
43
+ "sunrise_harbor": BivariateCornerPalette(
44
+ accent_a=(0.95, 0.40, 0.20),
45
+ accent_b=(0.10, 0.62, 0.65),
46
+ low=(0.98, 0.94, 0.60),
47
+ high=(0.12, 0.18, 0.50),
48
+ ),
49
+ "coral_ocean": BivariateCornerPalette(
50
+ accent_a=(0.94, 0.43, 0.46),
51
+ accent_b=(0.06, 0.64, 0.68),
52
+ low=(0.98, 0.95, 0.68),
53
+ high=(0.12, 0.22, 0.42),
54
+ ),
55
+ "glacier_ember": BivariateCornerPalette(
56
+ accent_a=(0.94, 0.48, 0.22),
57
+ accent_b=(0.10, 0.48, 0.70),
58
+ low=(1.00, 1.00, 0.98),
59
+ high=(0.12, 0.14, 0.28),
60
+ ),
61
+ "verdant_orchard": BivariateCornerPalette(
62
+ accent_a=(0.68, 0.28, 0.72),
63
+ accent_b=(0.18, 0.72, 0.40),
64
+ low=(0.98, 0.97, 0.72),
65
+ high=(0.14, 0.16, 0.34),
66
+ ),
67
+ "frosted_marigold": BivariateCornerPalette(
68
+ accent_a=(0.96, 0.62, 0.18),
69
+ accent_b=(0.12, 0.56, 0.52),
70
+ low=(0.99, 0.99, 0.96),
71
+ high=(0.10, 0.12, 0.18),
72
+ ),
73
+ "marigold_current": BivariateCornerPalette(
74
+ accent_a=(0.98, 0.58, 0.12),
75
+ accent_b=(0.10, 0.52, 0.68),
76
+ low=(0.99, 0.96, 0.70),
77
+ high=(0.12, 0.18, 0.34),
78
+ ),
79
+ "amber_drift": BivariateCornerPalette(
80
+ accent_a=(0.96, 0.50, 0.18),
81
+ accent_b=(0.12, 0.46, 0.72),
82
+ low=(0.99, 0.96, 0.64),
83
+ high=(0.12, 0.16, 0.38),
84
+ ),
85
+ "triadic_garden": BivariateCornerPalette(
86
+ accent_a=(0.66, 0.32, 0.82),
87
+ accent_b=(0.94, 0.48, 0.18),
88
+ low=(0.98, 0.97, 0.86),
89
+ high=(0.14, 0.16, 0.34),
90
+ ),
91
+ "electric_neon": BivariateCornerPalette(
92
+ accent_a=(0.12, 0.86, 0.78),
93
+ accent_b=(0.94, 0.30, 0.34),
94
+ low=(0.99, 0.97, 0.88),
95
+ high=(0.14, 0.16, 0.32),
96
+ ),
97
+ "solar_pasture": BivariateCornerPalette(
98
+ accent_a=(0.98, 0.74, 0.18),
99
+ accent_b=(0.14, 0.66, 0.44),
100
+ low=(0.99, 0.98, 0.90),
101
+ high=(0.12, 0.16, 0.30),
102
+ ),
103
+ "jungle_roar": BivariateCornerPalette(
104
+ accent_a=(0.96, 0.48, 0.16),
105
+ accent_b=(0.12, 0.62, 0.38),
106
+ low=(0.99, 0.97, 0.68),
107
+ high=(0.08, 0.14, 0.12),
108
+ ),
109
+ "citrus_forest": BivariateCornerPalette(
110
+ accent_a=(0.90, 0.50, 0.10),
111
+ accent_b=(0.15, 0.65, 0.45),
112
+ low=(0.95, 0.95, 0.60),
113
+ high=(0.10, 0.15, 0.40),
114
+ ),
115
+ "berry_bush": BivariateCornerPalette(
116
+ accent_a=(0.75, 0.20, 0.40),
117
+ accent_b=(0.20, 0.60, 0.50),
118
+ low=(0.95, 0.90, 0.85),
119
+ high=(0.15, 0.15, 0.45),
120
+ ),
121
+ "late_sunset": BivariateCornerPalette(
122
+ accent_a=(0.98, 0.56, 0.12),
123
+ accent_b=(0.92, 0.20, 0.78),
124
+ low=(0.99, 0.98, 0.92),
125
+ high=(0.12, 0.16, 0.34),
126
+ ),
127
+ "bubblegum": BivariateCornerPalette(
128
+ accent_a=(0.10, 0.78, 0.86),
129
+ accent_b=(0.94, 0.30, 0.56),
130
+ low=(0.99, 0.96, 0.86),
131
+ high=(0.14, 0.16, 0.34),
132
+ ),
133
+ "kaleidoscope": BivariateCornerPalette(
134
+ accent_a=(0.12, 0.96, 0.82),
135
+ accent_b=(0.96, 0.28, 0.54),
136
+ low=(0.98, 0.72, 0.20),
137
+ high=(0.46, 0.30, 0.96),
138
+ ),
139
+ "radiant_shift": BivariateCornerPalette(
140
+ accent_a=(0.98, 0.82, 0.28),
141
+ accent_b=(0.78, 0.46, 0.86),
142
+ low=(0.99, 0.98, 0.92),
143
+ high=(0.36, 0.28, 0.92),
144
+ ),
145
+ "blade_runner": BivariateCornerPalette(
146
+ accent_a=(0.10, 0.60, 0.70),
147
+ accent_b=(0.96, 0.50, 0.18),
148
+ low=(0.99, 0.97, 0.86),
149
+ high=(0.14, 0.16, 0.34),
150
+ ),
151
+ "grand_budapest": BivariateCornerPalette(
152
+ accent_a=(0.94, 0.56, 0.78),
153
+ accent_b=(0.72, 0.36, 0.88),
154
+ low=(0.99, 0.98, 0.96),
155
+ high=(0.16, 0.12, 0.26),
156
+ ),
157
+ "folk_warmth": BivariateCornerPalette(
158
+ accent_a=(0.92, 0.56, 0.22),
159
+ accent_b=(0.78, 0.46, 0.62),
160
+ low=(0.99, 0.97, 0.90),
161
+ high=(0.12, 0.14, 0.28),
162
+ ),
163
+ "earth": BivariateCornerPalette(
164
+ accent_a=(0.18, 0.56, 0.36),
165
+ accent_b=(0.86, 0.66, 0.38),
166
+ low=(0.99, 0.98, 0.90),
167
+ high=(0.10, 0.12, 0.20),
168
+ ),
169
+ }
File without changes
@@ -0,0 +1,14 @@
1
+ """Typing aliases for bivario package."""
2
+
3
+ from collections.abc import Iterable
4
+ from typing import TypeAlias
5
+
6
+ import numpy as np
7
+ import numpy.typing as npt
8
+ from narwhals.typing import IntoSeries
9
+
10
+ NumericDType: TypeAlias = np.integer | np.floating | np.bool_
11
+ NumericArray: TypeAlias = npt.NDArray[NumericDType]
12
+ ValueInput: TypeAlias = IntoSeries | NumericArray | Iterable[float | int | bool]
13
+
14
+ BivariateColourmap: TypeAlias = npt.NDArray[np.floating]
@@ -0,0 +1,143 @@
1
+ [project]
2
+ name = "bivario"
3
+ version = "0.1.0"
4
+ description = "Python library for plotting bivariate choropleth maps"
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Kamil Raczycki", email = "kraczycki@kraina.ai" }
8
+ ]
9
+ requires-python = ">=3.10"
10
+ dependencies = [
11
+ "colour-science>=0.4.6",
12
+ "folium>=0.20.0",
13
+ "geopandas>=1.0.1",
14
+ "mapclassify>=2.8.1",
15
+ "matplotlib>=3.9.4",
16
+ "narwhals>=2.8.0",
17
+ "numpy>=2.0.2",
18
+ ]
19
+ license = { text = "MIT" }
20
+ classifiers = [
21
+ "Development Status :: 3 - Alpha",
22
+ "License :: OSI Approved :: MIT License",
23
+ "Topic :: Scientific/Engineering :: GIS",
24
+ "Intended Audience :: Science/Research",
25
+ "Intended Audience :: Developers",
26
+ "Programming Language :: Python :: 3",
27
+ "Programming Language :: Python :: 3.10",
28
+ "Programming Language :: Python :: 3.11",
29
+ "Programming Language :: Python :: 3.12",
30
+ "Operating System :: Unix",
31
+ "Operating System :: MacOS",
32
+ "Operating System :: Microsoft :: Windows",
33
+ ]
34
+
35
+ [project.urls]
36
+ Homepage = "https://github.com/RaczeQ/bivario"
37
+ Repository = "https://github.com/RaczeQ/bivario"
38
+ Changelog = "https://github.com/RaczeQ/bivario/blob/main/CHANGELOG.md"
39
+
40
+ [dependency-groups]
41
+ dev = [
42
+ {include-group = "lint"},
43
+ {include-group = "test"},
44
+ {include-group = "notebook"},
45
+ "bumpver>=2025.1131",
46
+ ]
47
+ lint = [
48
+ "pre-commit>=4.3.0",
49
+ "ruff>=0.14.0",
50
+ ]
51
+ notebook = [
52
+ "duckdb>=1.4.1",
53
+ "ipykernel>=6.30.1",
54
+ "pyarrow>=21.0.0",
55
+ ]
56
+ test = [
57
+ "pytest>=8.4.2",
58
+ "tox-uv>=1.29.0",
59
+ ]
60
+
61
+ [build-system]
62
+ requires = ["uv_build>=0.9.1,<0.10.0"]
63
+ build-backend = "uv_build"
64
+
65
+ [tool.uv.build-backend]
66
+ module-name = "bivario"
67
+ module-root = ""
68
+
69
+ [tool.black]
70
+ line-length = 100
71
+ target-version = ["py310", "py311", "py312"]
72
+ preview = true
73
+
74
+ [tool.ruff]
75
+ line-length = 100
76
+ target-version = "py310"
77
+ extend-exclude = ["old"]
78
+
79
+ [tool.ruff.lint]
80
+ select = [
81
+ "E",
82
+ "W", # pycodestyle
83
+ "F", # pyflakes
84
+ "UP", # pyupgrade
85
+ "D", # pydocstyle
86
+ "I", # isort
87
+ "B", # flake8-bugbear
88
+ "NPY", # NumPy
89
+ "YTT", # flake8-2020
90
+ "Q", # flake8-quotes
91
+ "PLE",
92
+ "PLW", # pylint (add "PLR" in the future)
93
+ "PIE", # misc lints
94
+ "TID", # tidy imports
95
+ "ISC", # implicit string concatenation
96
+ "TCH", # type-checking imports
97
+ # "N", # pep8-naming
98
+ # "ANN", # flake8-annotations
99
+ ]
100
+ ignore = ["D212"]
101
+
102
+ [tool.ruff.lint.pydocstyle]
103
+ convention = "google"
104
+
105
+ [tool.ruff.lint.pycodestyle]
106
+ max-doc-length = 100
107
+
108
+ [tool.mypy]
109
+ strict = true
110
+ show_column_numbers = true
111
+ disallow_untyped_defs = true
112
+ no_implicit_optional = true
113
+ check_untyped_defs = true
114
+ warn_return_any = true
115
+ # plugins = 'numpy.typing.mypy_plugin'
116
+
117
+ [tool.docformatter]
118
+ syntax = 'google'
119
+ black = true
120
+ recursive = true
121
+ wrap-summaries = 100
122
+ wrap-descriptions = 100
123
+ # force-wrap = false # uncomment after https://github.com/PyCQA/docformatter/issues/68 is resolved
124
+ tab-width = 4
125
+ blank = false
126
+ pre-summary-newline = true
127
+ close-quotes-on-newline = true
128
+ wrap-one-line = true
129
+
130
+ [tool.bumpver]
131
+ current_version = "0.1.0"
132
+ version_pattern = "MAJOR.MINOR.PATCH[PYTAGNUM]"
133
+ commit_message = "chore(CI/CD): bump version {old_version} -> {new_version}"
134
+ commit = true
135
+ tag = false
136
+ push = false
137
+
138
+ [tool.bumpver.file_patterns]
139
+ "pyproject.toml" = [
140
+ '^current_version = "{version}"$',
141
+ '^version = "{version}"$',
142
+ ]
143
+ "bivario/__init__.py" = ['^__version__ = "{version}"$']