basemaplibre 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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kamil Raczycki
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,123 @@
1
+ Metadata-Version: 2.4
2
+ Name: basemaplibre
3
+ Version: 0.1.0
4
+ Summary: Basemaps for matplotlib and GeoPandas from MapLibre styles, inspired by contextily.
5
+ Keywords: maplibre,basemap,matplotlib,geopandas,contextily,vector tiles,gis
6
+ Author: Kamil Raczycki
7
+ Author-email: Kamil Raczycki <kraczycki@kraina.ai>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Framework :: Matplotlib
12
+ Classifier: Topic :: Scientific/Engineering :: GIS
13
+ Classifier: Topic :: Scientific/Engineering :: Visualization
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Operating System :: Unix
22
+ Classifier: Operating System :: MacOS
23
+ Classifier: Operating System :: Microsoft :: Windows
24
+ Requires-Dist: ml2drender>=0.4.3
25
+ Requires-Dist: httpx>=0.28.1,<1
26
+ Requires-Dist: matplotlib>=3.9.1
27
+ Requires-Dist: numpy>=1.26
28
+ Requires-Dist: pyproj>=3.6
29
+ Requires-Python: >=3.11
30
+ Project-URL: Homepage, https://github.com/RaczeQ/basemaplibre
31
+ Project-URL: Repository, https://github.com/RaczeQ/basemaplibre
32
+ Project-URL: Documentation, https://raczeq.github.io/basemaplibre/
33
+ Project-URL: Changelog, https://github.com/RaczeQ/basemaplibre/blob/main/CHANGELOG.md
34
+ Description-Content-Type: text/markdown
35
+
36
+ # basemaplibre
37
+
38
+ Basemaps for [matplotlib](https://matplotlib.org/) and [GeoPandas](https://geopandas.org/) from [MapLibre styles](https://maplibre.org/maplibre-style-spec/), with the parameters of [contextily](https://contextily.readthedocs.io/)'s `add_basemap`.
39
+
40
+ contextily downloads raster tiles in Web Mercator, merges them and warps them to the CRS of your data. `basemaplibre` renders the style (vector tiles, labels, icons) with [ml2drender](https://github.com/Kanahiro/ml2drender) for the extent of the axes, at their resolution and directly in their CRS, so labels stay upright and sharp. No GPU, no browser, no system libraries.
41
+
42
+ <p align="center">
43
+ <img alt="GitHub" src="https://img.shields.io/github/license/raczeq/basemaplibre?logo=mit&logoColor=%23fff">
44
+ <img src="https://img.shields.io/github/checks-status/raczeq/basemaplibre/main?logo=GitHubActions&logoColor=%23fff" alt="Checks">
45
+ <a href="https://github.com/raczeq/basemaplibre/actions/workflows/ci-prod.yml" target="_blank"><img alt="GitHub Workflow Status - PROD" src="https://img.shields.io/github/actions/workflow/status/raczeq/basemaplibre/ci-prod.yml?label=build-prod&logo=GitHubActions&logoColor=%23fff"></a>
46
+ <a href="https://results.pre-commit.ci/latest/github/raczeq/basemaplibre/main" target="_blank"><img src="https://results.pre-commit.ci/badge/github/raczeq/basemaplibre/main.svg" alt="pre-commit.ci status"></a>
47
+ <a href="https://app.codecov.io/gh/raczeq/basemaplibre/tree/main"><img alt="Codecov" src="https://img.shields.io/codecov/c/github/raczeq/basemaplibre?logo=codecov&logoColor=%23fff"></a>
48
+ <a href="https://pypi.org/project/basemaplibre" target="_blank"><img src="https://img.shields.io/pypi/v/basemaplibre?color=%2334D058&label=pypi%20package&logo=pypi&logoColor=%23fff" alt="Package version"></a>
49
+ <a href="https://pypi.org/project/basemaplibre" target="_blank"><img src="https://img.shields.io/pypi/pyversions/basemaplibre.svg?color=%2334D058&logo=python&logoColor=%23fff" alt="Supported Python versions"></a>
50
+ </p>
51
+
52
+ [Documentation](https://raczeq.github.io/basemaplibre/) · [Style gallery](https://raczeq.github.io/basemaplibre/gallery/) · [API reference](https://raczeq.github.io/basemaplibre/api/)
53
+
54
+ <p align="center">
55
+ <img src="https://raw.githubusercontent.com/RaczeQ/basemaplibre/main/images/compare.webp" alt="The same axes in EPSG:3035 with the default basemaps of contextily, whose labels are turned and blurred, and of basemaplibre">
56
+ </p>
57
+
58
+ ## Installation
59
+
60
+ ```bash
61
+ pip install basemaplibre
62
+ ```
63
+
64
+ ## Usage
65
+
66
+ ```python
67
+ import geopandas
68
+ import basemaplibre as bml
69
+
70
+ gdf = geopandas.read_file("districts.gpkg")
71
+ ax = gdf.plot(alpha=0.5, edgecolor="k")
72
+ bml.add_basemap(ax, crs=gdf.crs, source="OpenFreeMap.Positron")
73
+ ```
74
+
75
+ `labels="above"` draws the map under your data and its labels above it:
76
+
77
+ <p align="center">
78
+ <img src="https://raw.githubusercontent.com/RaczeQ/basemaplibre/main/images/labels.webp" alt="A choropleth over a basemap with its labels hidden by the data, and with labels above it">
79
+ </p>
80
+
81
+ | | |
82
+ |---|---|
83
+ | `add_basemap(ax, ...)` | Draws a style under the data of `ax`. |
84
+ | `add_attribution(ax, text, ...)` | Writes `text` in the bottom right corner of `ax`, wrapped to its width, on a translucent white box as MapLibre does. |
85
+ | `set_cache_dir(path)` | Keeps downloads in `path`, reused by later sessions that set it again, instead of a temporary directory removed at exit. |
86
+ | `STYLES` | Named styles that load without an API key, for `source`. |
87
+
88
+ ## Differences from contextily
89
+
90
+ - `source` is a MapLibre style: a `dict`, the URL of its JSON, a name of `STYLES` (default `OpenFreeMap.Liberty`) or a local `.json` file. Other sources (an `xyzservices` provider, a URL of raster tiles, a raster file) are left to `contextily.add_basemap`, with a `UserWarning`. contextily is not a dependency: install it for those.
91
+ - The style is drawn directly in `crs` (anything `pyproj.CRS.from_user_input` reads) if ml2drender [supports the projection](https://github.com/Kanahiro/ml2drender#projected-coordinate-reference-systems), so `resampling` is ignored. Axes that stretch latitudes, as GeoPandas does in EPSG:4326, get the projection they show, so labels keep their shape.
92
+ - `zoom` is contextily's zoom of 256-pixel tiles (the style is evaluated at MapLibre zoom `zoom - 1`); `"auto"` draws the style at its size on a web page.
93
+ - The basemap is rendered when it is added, and again when the axes are drawn with other limits, at another size or at another dpi: it stays sharp and up to date after zooming, panning, `fig.tight_layout()` or `fig.savefig(dpi=300)`. Rendering may download tiles, and its errors are raised where the figure is drawn. The image has the dpi the figure is drawn at, but 200 pixels to the inch at least.
94
+ - New: `labels=False` drops the labels and icons, `labels="only"` draws only them, above the data, and `labels="above"` draws the map under the data and its labels above it; `pixel_ratio` fixes the resolution; `load` replaces fetching with HTTPX. OpenHistoricalMap's styles are drawn as of today, as on its website.
95
+ - Downloads are cached on disk as in contextily (`set_cache_dir` keeps them across sessions), but for the style and its TileJSON, which name the current tiles. Failed requests are tried twice more.
96
+
97
+ ## Styles
98
+
99
+ `STYLES` has maps of the world (OpenFreeMap, VersaTiles, CARTO, Maptoolkit, OpenHistoricalMap, MapLibre) and of national mapping agencies (basemap.de, swisstopo, IGN, PDOK, GSI), terrain (Mapterhorn) and imagery (VersaTiles, EOX, USGS, GSI, PDOK, IGN). The [gallery](https://raczeq.github.io/basemaplibre/gallery/) shows each of them, with the coverage and terms of their services: check the terms before heavy use.
100
+
101
+ <p align="center">
102
+ <img src="https://raw.githubusercontent.com/RaczeQ/basemaplibre/main/images/styles.webp" alt="Maps of nine of the named styles">
103
+ </p>
104
+
105
+ `Mapterhorn.Hillshade` is transparent, to shade another basemap (here, under its labels):
106
+
107
+ ```python
108
+ bml.add_basemap(ax, source="OpenFreeMap.Positron", labels="above")
109
+ bml.add_basemap(ax, source="Mapterhorn.Hillshade")
110
+ ```
111
+
112
+ ## Development
113
+
114
+ ```bash
115
+ uv sync # install
116
+ uv run pre-commit install --hook-type pre-commit --hook-type commit-msg
117
+ uv run tox # tests
118
+ uv run tox -e docs # execute the notebooks, draw the gallery, build the docs to site/
119
+ uv run zensical serve # preview them
120
+ uv run python scripts/readme.py # draw the images of the README
121
+ ```
122
+
123
+ The notebooks in `examples/` are kept without outputs: they are executed when the docs are built, on release.
@@ -0,0 +1,88 @@
1
+ # basemaplibre
2
+
3
+ Basemaps for [matplotlib](https://matplotlib.org/) and [GeoPandas](https://geopandas.org/) from [MapLibre styles](https://maplibre.org/maplibre-style-spec/), with the parameters of [contextily](https://contextily.readthedocs.io/)'s `add_basemap`.
4
+
5
+ contextily downloads raster tiles in Web Mercator, merges them and warps them to the CRS of your data. `basemaplibre` renders the style (vector tiles, labels, icons) with [ml2drender](https://github.com/Kanahiro/ml2drender) for the extent of the axes, at their resolution and directly in their CRS, so labels stay upright and sharp. No GPU, no browser, no system libraries.
6
+
7
+ <p align="center">
8
+ <img alt="GitHub" src="https://img.shields.io/github/license/raczeq/basemaplibre?logo=mit&logoColor=%23fff">
9
+ <img src="https://img.shields.io/github/checks-status/raczeq/basemaplibre/main?logo=GitHubActions&logoColor=%23fff" alt="Checks">
10
+ <a href="https://github.com/raczeq/basemaplibre/actions/workflows/ci-prod.yml" target="_blank"><img alt="GitHub Workflow Status - PROD" src="https://img.shields.io/github/actions/workflow/status/raczeq/basemaplibre/ci-prod.yml?label=build-prod&logo=GitHubActions&logoColor=%23fff"></a>
11
+ <a href="https://results.pre-commit.ci/latest/github/raczeq/basemaplibre/main" target="_blank"><img src="https://results.pre-commit.ci/badge/github/raczeq/basemaplibre/main.svg" alt="pre-commit.ci status"></a>
12
+ <a href="https://app.codecov.io/gh/raczeq/basemaplibre/tree/main"><img alt="Codecov" src="https://img.shields.io/codecov/c/github/raczeq/basemaplibre?logo=codecov&logoColor=%23fff"></a>
13
+ <a href="https://pypi.org/project/basemaplibre" target="_blank"><img src="https://img.shields.io/pypi/v/basemaplibre?color=%2334D058&label=pypi%20package&logo=pypi&logoColor=%23fff" alt="Package version"></a>
14
+ <a href="https://pypi.org/project/basemaplibre" target="_blank"><img src="https://img.shields.io/pypi/pyversions/basemaplibre.svg?color=%2334D058&logo=python&logoColor=%23fff" alt="Supported Python versions"></a>
15
+ </p>
16
+
17
+ [Documentation](https://raczeq.github.io/basemaplibre/) · [Style gallery](https://raczeq.github.io/basemaplibre/gallery/) · [API reference](https://raczeq.github.io/basemaplibre/api/)
18
+
19
+ <p align="center">
20
+ <img src="https://raw.githubusercontent.com/RaczeQ/basemaplibre/main/images/compare.webp" alt="The same axes in EPSG:3035 with the default basemaps of contextily, whose labels are turned and blurred, and of basemaplibre">
21
+ </p>
22
+
23
+ ## Installation
24
+
25
+ ```bash
26
+ pip install basemaplibre
27
+ ```
28
+
29
+ ## Usage
30
+
31
+ ```python
32
+ import geopandas
33
+ import basemaplibre as bml
34
+
35
+ gdf = geopandas.read_file("districts.gpkg")
36
+ ax = gdf.plot(alpha=0.5, edgecolor="k")
37
+ bml.add_basemap(ax, crs=gdf.crs, source="OpenFreeMap.Positron")
38
+ ```
39
+
40
+ `labels="above"` draws the map under your data and its labels above it:
41
+
42
+ <p align="center">
43
+ <img src="https://raw.githubusercontent.com/RaczeQ/basemaplibre/main/images/labels.webp" alt="A choropleth over a basemap with its labels hidden by the data, and with labels above it">
44
+ </p>
45
+
46
+ | | |
47
+ |---|---|
48
+ | `add_basemap(ax, ...)` | Draws a style under the data of `ax`. |
49
+ | `add_attribution(ax, text, ...)` | Writes `text` in the bottom right corner of `ax`, wrapped to its width, on a translucent white box as MapLibre does. |
50
+ | `set_cache_dir(path)` | Keeps downloads in `path`, reused by later sessions that set it again, instead of a temporary directory removed at exit. |
51
+ | `STYLES` | Named styles that load without an API key, for `source`. |
52
+
53
+ ## Differences from contextily
54
+
55
+ - `source` is a MapLibre style: a `dict`, the URL of its JSON, a name of `STYLES` (default `OpenFreeMap.Liberty`) or a local `.json` file. Other sources (an `xyzservices` provider, a URL of raster tiles, a raster file) are left to `contextily.add_basemap`, with a `UserWarning`. contextily is not a dependency: install it for those.
56
+ - The style is drawn directly in `crs` (anything `pyproj.CRS.from_user_input` reads) if ml2drender [supports the projection](https://github.com/Kanahiro/ml2drender#projected-coordinate-reference-systems), so `resampling` is ignored. Axes that stretch latitudes, as GeoPandas does in EPSG:4326, get the projection they show, so labels keep their shape.
57
+ - `zoom` is contextily's zoom of 256-pixel tiles (the style is evaluated at MapLibre zoom `zoom - 1`); `"auto"` draws the style at its size on a web page.
58
+ - The basemap is rendered when it is added, and again when the axes are drawn with other limits, at another size or at another dpi: it stays sharp and up to date after zooming, panning, `fig.tight_layout()` or `fig.savefig(dpi=300)`. Rendering may download tiles, and its errors are raised where the figure is drawn. The image has the dpi the figure is drawn at, but 200 pixels to the inch at least.
59
+ - New: `labels=False` drops the labels and icons, `labels="only"` draws only them, above the data, and `labels="above"` draws the map under the data and its labels above it; `pixel_ratio` fixes the resolution; `load` replaces fetching with HTTPX. OpenHistoricalMap's styles are drawn as of today, as on its website.
60
+ - Downloads are cached on disk as in contextily (`set_cache_dir` keeps them across sessions), but for the style and its TileJSON, which name the current tiles. Failed requests are tried twice more.
61
+
62
+ ## Styles
63
+
64
+ `STYLES` has maps of the world (OpenFreeMap, VersaTiles, CARTO, Maptoolkit, OpenHistoricalMap, MapLibre) and of national mapping agencies (basemap.de, swisstopo, IGN, PDOK, GSI), terrain (Mapterhorn) and imagery (VersaTiles, EOX, USGS, GSI, PDOK, IGN). The [gallery](https://raczeq.github.io/basemaplibre/gallery/) shows each of them, with the coverage and terms of their services: check the terms before heavy use.
65
+
66
+ <p align="center">
67
+ <img src="https://raw.githubusercontent.com/RaczeQ/basemaplibre/main/images/styles.webp" alt="Maps of nine of the named styles">
68
+ </p>
69
+
70
+ `Mapterhorn.Hillshade` is transparent, to shade another basemap (here, under its labels):
71
+
72
+ ```python
73
+ bml.add_basemap(ax, source="OpenFreeMap.Positron", labels="above")
74
+ bml.add_basemap(ax, source="Mapterhorn.Hillshade")
75
+ ```
76
+
77
+ ## Development
78
+
79
+ ```bash
80
+ uv sync # install
81
+ uv run pre-commit install --hook-type pre-commit --hook-type commit-msg
82
+ uv run tox # tests
83
+ uv run tox -e docs # execute the notebooks, draw the gallery, build the docs to site/
84
+ uv run zensical serve # preview them
85
+ uv run python scripts/readme.py # draw the images of the README
86
+ ```
87
+
88
+ The notebooks in `examples/` are kept without outputs: they are executed when the docs are built, on release.
@@ -0,0 +1,15 @@
1
+ """
2
+ Basemaps for matplotlib and GeoPandas rendered from MapLibre styles.
3
+
4
+ The parameters are those of contextily's `add_basemap`, but the basemap is a MapLibre style (vector
5
+ tiles, labels, icons) rendered with ml2drender: for the extent of the axes, at their resolution and
6
+ directly in their CRS, instead of raster tiles that are merged and warped.
7
+ """
8
+
9
+ from basemaplibre._plotting import add_attribution, add_basemap
10
+ from basemaplibre._render import set_cache_dir
11
+ from basemaplibre._source import STYLES
12
+
13
+ __version__ = "0.1.0"
14
+
15
+ __all__ = ["STYLES", "add_attribution", "add_basemap", "set_cache_dir"]
@@ -0,0 +1,48 @@
1
+ """The attribution in the corner of the axes: a matplotlib annotation."""
2
+
3
+ from typing import TYPE_CHECKING, cast
4
+
5
+ from matplotlib import font_manager, rcParams
6
+ from matplotlib.text import Annotation
7
+
8
+ if TYPE_CHECKING:
9
+ from matplotlib.backend_bases import RendererBase
10
+
11
+ # The attribution box's padding, in font sizes.
12
+ PAD = 0.2
13
+ # Fonts of Chinese, Japanese and Korean (macOS, Windows, Linux), which matplotlib's default lacks,
14
+ # for attributions such as GSI's: those installed back up the default font.
15
+ _CJK_FONTS = [
16
+ "Hiragino Sans",
17
+ "Yu Gothic",
18
+ "Microsoft YaHei",
19
+ "Malgun Gothic",
20
+ "Noto Sans CJK JP",
21
+ ]
22
+
23
+
24
+ def font_family() -> list[str]:
25
+ """Return matplotlib's default font family, then the installed fonts of `_CJK_FONTS`."""
26
+ installed = {font.name for font in font_manager.fontManager.ttflist}
27
+ return [*rcParams["font.family"], *(name for name in _CJK_FONTS if name in installed)]
28
+
29
+
30
+ class Attribution(Annotation):
31
+ """An annotation whose words are wrapped to the width of its axes whenever it is drawn."""
32
+
33
+ def draw(self, renderer: "RendererBase") -> None:
34
+ """Wrap the text, then draw it."""
35
+ if self.axes is not None:
36
+ font = self.get_fontproperties()
37
+ # The text and the padding of its box on both sides.
38
+ width = self.axes.get_window_extent(renderer).width
39
+ width -= cast("float", renderer.points_to_pixels(2 * PAD * font.get_size_in_points()))
40
+ lines: list[str] = []
41
+ for word in self.get_text().split():
42
+ line = f"{lines[-1]} {word}" if lines else word
43
+ if lines and renderer.get_text_width_height_descent(line, font, False)[0] <= width:
44
+ lines[-1] = line
45
+ else:
46
+ lines.append(word)
47
+ self.set_text("\n".join(lines))
48
+ super().draw(renderer)
@@ -0,0 +1,144 @@
1
+ """The image of a basemap: a matplotlib image rendered for the axes as they are drawn."""
2
+
3
+ from typing import TYPE_CHECKING, Any, NamedTuple
4
+
5
+ from matplotlib.image import AxesImage
6
+ from ml2drender import ProjectedBox
7
+
8
+ from basemaplibre._render import Bbox, Crs, attribution_text, on_screen, projected_box
9
+
10
+ if TYPE_CHECKING:
11
+ from collections.abc import Callable
12
+
13
+ import numpy as np
14
+ from matplotlib.axes import Axes
15
+ from matplotlib.backend_bases import RendererBase
16
+ from matplotlib.text import Text
17
+ from numpy.typing import NDArray
18
+
19
+ Render = Callable[[Crs, ProjectedBox], tuple[NDArray[np.uint8], str]]
20
+
21
+ # CSS pixels in an inch: with the automatic zoom, a style's 12 px text is 9 points high on paper.
22
+ _CSS_PER_INCH = 96
23
+ # The image's pixels per inch of the figure, at least: twice matplotlib's default dpi (about two per
24
+ # CSS pixel, as on HiDPI screens). Figures of that dpi are rendered once for both kinds of screens
25
+ # and for saving at up to twice their dpi.
26
+ _MIN_DPI = 200
27
+
28
+
29
+ class View(NamedTuple):
30
+ """What axes show: their extent and what to render for it."""
31
+
32
+ extent: Bbox # (left, right, bottom, top), in the CRS of the axes
33
+ size: int # in CSS pixels, of the long side
34
+ crs: Crs
35
+ box: ProjectedBox
36
+
37
+ @property
38
+ def key(self) -> tuple[object, ...]:
39
+ """What differs between the images of views."""
40
+ return self.extent, self.size, self.box.pixels
41
+
42
+
43
+ class Framing(NamedTuple):
44
+ """How to render what axes show."""
45
+
46
+ crs: Crs
47
+ zoom: float | None = None # of 256-pixel XYZ tiles; None is automatic
48
+ zoom_adjust: float = 0 # of the automatic zoom
49
+ pixel_ratio: float | None = None # None is the resolution of the figure
50
+ size: int | None = None # in CSS pixels, of the long side, instead of the zoom
51
+
52
+ def view(self, ax: "Axes", magnification: float = 1.0) -> View:
53
+ """
54
+ Return the view of `ax`, whose size and limits are those drawn.
55
+
56
+ `magnification` is the pixels drawn to one of the figure: more than one in vector graphics,
57
+ which matplotlib draws at 72 dpi.
58
+ """
59
+ xmin, xmax, ymin, ymax = ax.axis()
60
+ (left, right), (bottom, top) = sorted((xmin, xmax)), sorted((ymin, ymax))
61
+ extent = (left, right, bottom, top)
62
+ display, dpi = ax.get_window_extent(), ax.figure.dpi
63
+ stretch = 1.0
64
+ if display.width:
65
+ stretch = display.height * (right - left) / (display.width * (top - bottom))
66
+ crs, box = on_screen(self.crs, (left, bottom, right, top), stretch)
67
+ width, height = box[2] - box[0], box[3] - box[1]
68
+ # Pixels of the figure to the unit of the CRS.
69
+ pixels = max(display.width / width, display.height / height)
70
+ size = self.size
71
+ if size is None:
72
+ if self.zoom is None:
73
+ scale = pixels * _CSS_PER_INCH / dpi * 2**self.zoom_adjust
74
+ else:
75
+ scale = 256 * 2**self.zoom / crs.units_per_turn
76
+ # In whole CSS pixels (at least one): the scale drawn.
77
+ size = max(1, round(max(width, height) * scale))
78
+ ratio = self.pixel_ratio
79
+ if ratio is None:
80
+ ratio = pixels * max(width, height) / size * max(magnification, _MIN_DPI / dpi)
81
+ return View(extent, size, crs, projected_box(box, size, ratio))
82
+
83
+
84
+ class BasemapImage(AxesImage):
85
+ """
86
+ An image rendered anew whenever its axes are drawn with another view.
87
+
88
+ That is with other limits, at another size or at another resolution.
89
+ """
90
+
91
+ _framing: Framing
92
+ _drawn: tuple[object, ...] # the key of the view
93
+ _render: "Render | None" # None (of an unpickled figure) keeps the image
94
+ _attribution: "Text | None"
95
+
96
+ @classmethod
97
+ def of(
98
+ cls,
99
+ image: AxesImage,
100
+ framing: Framing,
101
+ view: View,
102
+ render: "Render",
103
+ attribution: "Text | None",
104
+ ) -> "BasemapImage":
105
+ """
106
+ Turn `image`, of `imshow` (which takes its many arguments), into a `BasemapImage` of `view`.
107
+
108
+ As mplot3d does with the artists of the 2D methods. The attributions of other views are
109
+ added to `attribution`, if any.
110
+ """
111
+ image.__class__ = cls
112
+ assert isinstance(image, cls)
113
+ image._framing, image._drawn = framing, view.key
114
+ image._render, image._attribution = render, attribution
115
+ return image
116
+
117
+ def make_image(
118
+ self, renderer: "RendererBase", magnification: float = 1.0, unsampled: bool = False
119
+ ) -> Any:
120
+ """Render the view of the axes, if another than the last, then make the image drawn."""
121
+ # Here and not in draw, which vector graphics do not call for images drawn as one.
122
+ self._update(renderer.get_image_magnification())
123
+ return super().make_image(renderer, magnification, unsampled)
124
+
125
+ def _update(self, magnification: float) -> None:
126
+ display = self.axes.get_window_extent()
127
+ # Not while dragged: the image moves with the axes (matplotlib has no public sign of it).
128
+ dragged = hasattr(self.axes, "_pan_start")
129
+ if self._render is None or dragged or min(display.width, display.height) < 1:
130
+ return
131
+ view = self._framing.view(self.axes, magnification)
132
+ if view.key == self._drawn:
133
+ return
134
+ image, text = self._render(view.crs, view.box)
135
+ self.set_data(image)
136
+ self._extent = view.extent # set_extent would change the limits of the axes and their data
137
+ self._drawn = view.key
138
+ if self._attribution is not None:
139
+ self._attribution.set_text(attribution_text([self._attribution.get_text(), text]))
140
+
141
+ def __getstate__(self) -> dict[str, Any]:
142
+ """Return the state to pickle: without the loader, which may be a local function."""
143
+ state: Any = super().__getstate__()
144
+ return {**state, "_render": None}