Tiles Module — Web-tile Basemaps#
The cleopatra.basemap.tiles module adds an optional, pure-Python web-tile basemap helper:
add_tiles fetches XYZ map tiles covering an axes' current extent, stitches them with
Pillow, and renders the composite underneath your data. No GDAL is required.
It is gated behind the cleopatra[tiles] optional extra (pillow, pyproj,
xyzservices):
If the extra is not installed, the functions raise a clear ImportError with the install
hint.
Usage#
import matplotlib
matplotlib.use("Agg") # any backend; Agg shown for headless rendering
import matplotlib.pyplot as plt
from cleopatra.basemap.tiles import add_tiles
fig, ax = plt.subplots()
# plot something in Web Mercator (EPSG:3857) coordinates ...
ax.plot([1_000_000.0, 1_200_000.0], [6_000_000.0, 6_200_000.0])
# ... and drop an OpenStreetMap basemap underneath it
add_tiles(ax, crs=3857)
# a different provider, a fixed zoom, a custom User-Agent (recommended in production):
add_tiles(
ax,
source="CartoDB.Positron",
crs="EPSG:4326",
zoom=8,
user_agent="my-app/1.0 (+https://example.org)",
)
fig.savefig("map.png")
Note
add_tiles reads the axes' current xlim/ylim, so plot your data first. When the
data CRS is Web Mercator the tiles are placed in-place; for any other crs= the
mosaic's own Web-Mercator coverage is reprojected into the target CRS and used as the
image extent (the axis limits stay at the data bounds), so the basemap aligns with the
data even though the fetched tiles cover a tile-snapped area larger than it. A residual
Mercator-vs-linear nonlinearity remains for very large extents — for pixel-accurate
results reproject the source data to EPSG:3857 before plotting. If a coarse mosaic
overflows a limited-domain target CRS (e.g. a whole-world mosaic into a UTM zone), the
reprojection is skipped with a warning and the basemap falls back to the data bounds
(slightly misaligned); use a higher zoom or reproject the data to EPSG:3857 to avoid it.
The automatic zoom uses
a min_tiles_across floor (default 2) so a mid-range extent is not rendered from one or
two coarse tiles; the number of tiles is capped by max_tiles (default
MAX_TILES = 256), and the zoom is stepped down if a level would need more.
Module Documentation#
cleopatra.basemap.tiles
#
Web-tile basemap helper for matplotlib axes.
Provides add_tiles -- a single entry point that fetches XYZ web
tiles for the current axes extent, stitches them into a composite image
with Pillow, and renders the image underneath the existing data layer.
The implementation is a pure-Python port of the pyramids.basemap
module (basemap.py + tiles.py). It supports any XYZ provider listed in
xyzservices. CRS handling is done with pyproj -- there is
no GDAL dependency, so the module is safe to use in environments that
only have matplotlib + numpy installed.
Notes
For data in CRSes other than Web Mercator (EPSG:3857) the stitched tile
image is placed at the mosaic's own coverage: its Web-Mercator bounds
are reprojected (with edge densification) into the target CRS and used
as the imshow extent, while the axis limits stay at the data bounds.
This aligns the basemap with the data even when the fetched tiles cover
a tile-snapped area larger than the data. A residual Mercator-vs-linear
nonlinearity remains for very large extents (the Mercator pixels are
placed on a linear axis); if pixel-accurate warping is required,
reproject the source data to Web Mercator (EPSG:3857) before plotting.
Examples:
Add a default OpenStreetMap basemap to an axes that already has data plotted in Web Mercator coordinates:
>>> import matplotlib
>>> matplotlib.use("Agg")
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots()
>>> _ = ax.plot([1000000.0, 1200000.0], [6000000.0, 6200000.0])
>>> _ = add_tiles(ax, source=None, crs=3857)
Tile
#
Bases: NamedTuple
An XYZ web-map tile: column x, row y, at zoom level z.
The standard "slippy map" tile-coordinate triple used by every XYZ tile
provider (OpenStreetMap, CartoDB, Esri, ...): at zoom z the world is
divided into a 2**z by 2**z grid, x counted west to east and y
north to south. Hashable and immutable, so it doubles as a dict key
(see fetch_tiles's tile -> PNG bytes mapping).
Attributes:
| Name | Type | Description |
|---|---|---|
x |
int
|
Column index, |
y |
int
|
Row index, |
z |
int
|
Zoom level; the grid is |
Examples:
- The single tile covering the whole world at zoom 0:
- Two tiles compare equal by value, so one can look the other up
in a
{tile: data}mapping (asfetch_tiles's return value does): - Fields are accessible by name or by position:
Source code in src/cleopatra/basemap/tiles.py
add_tiles(ax, source=None, *, crs=None, zoom='auto', alpha=1.0, attribution=True, zorder=-1, interpolation='bilinear', timeout=10, retries=2, user_agent=None, max_tiles=MAX_TILES, min_tiles_across=2)
#
Overlay a web-tile basemap on a matplotlib axes.
Fetches XYZ web tiles that cover the axes' current extent, stitches them into a single composite image, and renders the image below the existing data layer. When the data is already in Web Mercator (EPSG:3857) the tiles are placed in-place; for any other CRS the mosaic's own Web-Mercator coverage is reprojected into the target CRS and used as the image extent (the axis limits stay at the data bounds), so the basemap aligns with the data even though the fetched tiles cover a tile-snapped area larger than it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Any
|
Matplotlib |
required |
source
|
Any | None
|
Tile provider. |
None
|
crs
|
int | str | None
|
CRS of the data on |
None
|
zoom
|
int | str
|
Tile zoom level. |
'auto'
|
alpha
|
float
|
Opacity of the basemap ( |
1.0
|
attribution
|
str | bool
|
|
True
|
zorder
|
int
|
Matplotlib zorder for the basemap ( |
-1
|
interpolation
|
str
|
Interpolation method passed to |
'bilinear'
|
timeout
|
int
|
Per-tile HTTP timeout in seconds. |
10
|
retries
|
int
|
Per-tile retry count. |
2
|
user_agent
|
str | None
|
|
None
|
max_tiles
|
int
|
Cap on how many tiles to fetch. If the chosen |
MAX_TILES
|
min_tiles_across
|
int
|
Floor for the automatic zoom, forwarded to
|
2
|
Returns:
| Type | Description |
|---|---|
Any
|
matplotlib.axes.Axes: The same axes, for chaining. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If the |
TypeError
|
If |
ValueError
|
If the axes have no data extent or |
ConnectionError
|
If tiles cannot be fetched from the provider. |
Examples:
Add a default OpenStreetMap basemap to an existing plot:
>>> import matplotlib
>>> matplotlib.use("Agg")
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots()
>>> _ = ax.plot([1000000.0, 1200000.0], [6000000.0, 6200000.0])
>>> _ = add_tiles(ax, crs=3857)
Source code in src/cleopatra/basemap/tiles.py
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 | |
auto_zoom(bounds_4326, min_tiles_across=2)
#
Compute a default zoom level for the given bounds in EPSG:4326.
Picks the smallest zoom at which the larger of the two extents spans at
least min_tiles_across tiles, i.e.
zoom = ceil(log2(min_tiles_across * 360 / max(lon_extent, lat_extent))),
clamped to 0--19. The min_tiles_across floor (default 2) stops a
mid-range regional extent from collapsing onto a single coarse tile
stretched over the whole area (a 6--11 degree window would otherwise
fetch just 2 tiles); min_tiles_across=1 reproduces the older
one-tile-across heuristic.
This is a coarse heuristic that treats degrees of longitude and
latitude as interchangeable; it does not account for Web
Mercator's latitude distortion, so the result tends to be
conservative (under-zoomed) for extents far from the equator. For
high-latitude data, pass an explicit zoom= to add_tiles
rather than relying on the auto value. The MAX_TILES cap in
add_tiles will still step the zoom back down if the chosen
level would require too many tiles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bounds_4326
|
tuple[float, float, float, float]
|
|
required |
min_tiles_across
|
int
|
Minimum number of tiles the larger extent should span; higher values pick a sharper (higher) zoom. Values below 1 are clamped to 1 (the older one-tile-across heuristic). Defaults to 2. |
2
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Zoom level between 0 and 19. |
Examples:
- Worldwide extent maps to zoom 1 (two tiles across the globe):
- A 0.6 by 0.2 degree window over Berlin yields zoom 11:
min_tiles_across=1restores the older, coarser one-tile heuristic (worldwide -> zoom 0):- Tiny extents are clamped to the maximum zoom (19):
Source code in src/cleopatra/basemap/tiles.py
fetch_single_tile(tile, provider, timeout, retries, user_agent=USER_AGENT)
#
Fetch a single tile, retrying on transient failures.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tile
|
Any
|
Tile to fetch (has |
required |
provider
|
Any
|
|
required |
timeout
|
int
|
HTTP request timeout in seconds. |
required |
retries
|
int
|
Number of retry attempts on failure. |
required |
user_agent
|
str
|
|
USER_AGENT
|
Returns:
| Type | Description |
|---|---|
tuple[Any, bytes]
|
tuple[Any, bytes]: The original tile and its PNG/JPEG bytes. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the provider's URL template is not an |
ConnectionError
|
If the tile cannot be fetched after all retries are exhausted. |
Examples:
- Fetch a single OpenStreetMap tile (network-dependent, hence
skipped under doctest):
>>> from cleopatra.basemap.tiles import Tile, fetch_single_tile, get_provider >>> tile = Tile(0, 0, 0) >>> provider = get_provider("OpenStreetMap.Mapnik") >>> tile_obj, data = fetch_single_tile( # doctest: +SKIP ... tile, provider, timeout=10, retries=2 ... ) >>> from cleopatra.basemap.tiles import _looks_like_image >>> _looks_like_image(data) # doctest: +SKIP True - Tile failures raise
ConnectionErrorafter retries are exhausted:>>> from cleopatra.basemap.tiles import Tile, fetch_single_tile >>> from xyzservices import TileProvider >>> bad = TileProvider( ... name="bad", ... url="http://127.0.0.1:1/{z}/{x}/{y}.png", ... attribution="", ... ) >>> fetch_single_tile( # doctest: +SKIP ... Tile(0, 0, 0), bad, timeout=1, retries=0 ... ) Traceback (most recent call last): ... ConnectionError: Failed to fetch tile z=0/x=0/y=0 ...
Source code in src/cleopatra/basemap/tiles.py
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 | |
fetch_tiles(tiles, provider, max_workers=8, timeout=10, retries=2, user_agent=USER_AGENT)
#
Fetch tile images in parallel over HTTP.
Uses concurrent.futures.ThreadPoolExecutor for parallel
downloads. Each tile URL is constructed via the provider's
build_url(). A User-Agent header (cleopatra/<version> (+repo-url)
by default) is sent on every request so tile providers can attribute
the traffic — OpenStreetMap's usage policy requires an identifiable
agent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tiles
|
list
|
Tiles to fetch (each has |
required |
provider
|
Any
|
|
required |
max_workers
|
int
|
Maximum concurrent HTTP connections. |
8
|
timeout
|
int
|
Per-tile HTTP request timeout in seconds. |
10
|
retries
|
int
|
Per-tile retry count on failure. |
2
|
user_agent
|
str
|
|
USER_AGENT
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
Mapping of Tile to PNG/JPEG bytes. |
Raises:
| Type | Description |
|---|---|
ConnectionError
|
If any tile cannot be fetched after all retries. |
Examples:
- Fetch a small tile grid in parallel (network-dependent, hence
skipped under doctest):
>>> from cleopatra.basemap.tiles import _tiles_for_bbox, fetch_tiles, get_provider >>> tiles = _tiles_for_bbox(13.0, 52.4, 13.6, 52.6, 10) >>> provider = get_provider("OpenStreetMap.Mapnik") >>> data = fetch_tiles(tiles, provider, max_workers=4) # doctest: +SKIP >>> len(data) == len(tiles) # doctest: +SKIP True - Pass an empty list to short-circuit and get an empty dict:
Source code in src/cleopatra/basemap/tiles.py
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 | |
get_provider(name=None)
#
Resolve an XYZ tile provider by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
Dot-separated provider name (e.g. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
xyzservices.TileProvider: The resolved tile provider with |
Any
|
|
Raises:
| Type | Description |
|---|---|
ImportError
|
If the |
ValueError
|
If the provider name cannot be resolved. |
Examples:
- Resolve the default OpenStreetMap provider and inspect its URL template:
- Resolve a named provider via dot-path syntax:
- Invalid provider names raise
ValueError:
Source code in src/cleopatra/basemap/tiles.py
stitch_tiles(tile_data, tiles, zoom)
#
Stitch tile images into a single RGBA array.
Arranges tiles in a grid based on their x, y positions. The
tile size is read from the first decoded image (typically 256 or
512 px). Computes the geographic extent of the stitched image in
EPSG:3857 using _tile_xy_bounds on the corner tiles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tile_data
|
dict
|
Mapping of Tile to PNG bytes (from
|
required |
tiles
|
list
|
All tiles in the grid, defining grid dimensions. |
required |
zoom
|
int
|
Zoom level of the tiles. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
tuple[numpy.ndarray, tuple[float, float, float, float]]: The |
tuple[float, float, float, float]
|
stitched RGBA image with shape |
tuple[ndarray, tuple[float, float, float, float]]
|
|
tuple[ndarray, tuple[float, float, float, float]]
|
meters. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any tile bytes cannot be decoded as an image. |
Examples:
- Stitch a single synthetic tile into a 256x256 RGBA image:
>>> import io >>> from PIL import Image >>> from cleopatra.basemap.tiles import Tile, stitch_tiles >>> buf = io.BytesIO() >>> Image.new("RGBA", (256, 256), (255, 0, 0, 255)).save(buf, "PNG") >>> tile = Tile(0, 0, 0) >>> image, extent = stitch_tiles({tile: buf.getvalue()}, [tile], 0) >>> image.shape (256, 256, 4) >>> image.dtype.name 'uint8' - The returned EPSG:3857 extent comes from
_tile_xy_boundson the corner tiles:>>> import io >>> from PIL import Image >>> from cleopatra.basemap.tiles import Tile, stitch_tiles >>> buf = io.BytesIO() >>> Image.new("RGBA", (256, 256), (0, 255, 0, 255)).save(buf, "PNG") >>> tile = Tile(0, 0, 0) >>> _, (w, s, e, n) = stitch_tiles({tile: buf.getvalue()}, [tile], 0) >>> w < e and s < n True - Invalid tile bytes raise
ValueError:
Source code in src/cleopatra/basemap/tiles.py
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 | |