| 1 |
"""Tools to plot basemaps""" |
| 2 |
|
| 3 |
import warnings |
| 4 |
import numpy as np |
| 5 |
from . import providers |
| 6 |
from xyzservices import TileProvider |
| 7 |
from .tile import bounds2img, _sm2ll, warp_tiles, _warper |
| 8 |
from rasterio.enums import Resampling |
| 9 |
from rasterio.warp import transform_bounds |
| 10 |
from matplotlib import patheffects |
| 11 |
from matplotlib.pyplot import draw |
| 12 |
|
| 13 |
INTERPOLATION = "bilinear" |
| 14 |
ZOOM = "auto" |
| 15 |
ATTRIBUTION_SIZE = 8 |
| 16 |
|
| 17 |
|
| 18 |
def add_basemap( |
| 19 |
ax, |
| 20 |
zoom=ZOOM, |
| 21 |
source=None, |
| 22 |
interpolation=INTERPOLATION, |
| 23 |
attribution=None, |
| 24 |
attribution_size=ATTRIBUTION_SIZE, |
| 25 |
reset_extent=True, |
| 26 |
crs=None, |
| 27 |
resampling=Resampling.bilinear, |
| 28 |
zoom_adjust=None, |
| 29 |
**extra_imshow_args |
| 30 |
): |
| 31 |
""" |
| 32 |
Add a (web/local) basemap to `ax`. |
| 33 |
|
| 34 |
Parameters |
| 35 |
---------- |
| 36 |
ax : AxesSubplot |
| 37 |
Matplotlib axes object on which to add the basemap. The extent of the |
| 38 |
axes is assumed to be in Spherical Mercator (EPSG:3857), unless the `crs` |
| 39 |
keyword is specified. |
| 40 |
zoom : int or 'auto' |
| 41 |
[Optional. Default='auto'] Level of detail for the basemap. If 'auto', |
| 42 |
it is calculated automatically. Ignored if `source` is a local file. |
| 43 |
source : xyzservices.TileProvider object or str |
| 44 |
[Optional. Default: OpenStreetMap Humanitarian web tiles] |
| 45 |
The tile source: web tile provider, a valid input for a query of a |
| 46 |
:class:`xyzservices.TileProvider` by a name from ``xyzservices.providers`` or |
| 47 |
path to local file. The web tile provider can be in the form of a |
| 48 |
:class:`xyzservices.TileProvider` object or a URL. The placeholders for the XYZ |
| 49 |
in the URL need to be `{x}`, `{y}`, `{z}`, respectively. For local file paths, |
| 50 |
the file is read with `rasterio` and all bands are loaded into the basemap. |
| 51 |
IMPORTANT: tiles are assumed to be in the Spherical Mercator projection |
| 52 |
(EPSG:3857), unless the `crs` keyword is specified. |
| 53 |
interpolation : str |
| 54 |
[Optional. Default='bilinear'] Interpolation algorithm to be passed |
| 55 |
to `imshow`. See `matplotlib.pyplot.imshow` for further details. |
| 56 |
attribution : str |
| 57 |
[Optional. Defaults to attribution specified by the source] |
| 58 |
Text to be added at the bottom of the axis. This |
| 59 |
defaults to the attribution of the provider specified |
| 60 |
in `source` if available. Specify False to not |
| 61 |
automatically add an attribution, or a string to pass |
| 62 |
a custom attribution. |
| 63 |
attribution_size : int |
| 64 |
[Optional. Defaults to `ATTRIBUTION_SIZE`]. |
| 65 |
Font size to render attribution text with. |
| 66 |
reset_extent : bool |
| 67 |
[Optional. Default=True] If True, the extent of the |
| 68 |
basemap added is reset to the original extent (xlim, |
| 69 |
ylim) of `ax` |
| 70 |
crs : None or str or CRS |
| 71 |
[Optional. Default=None] coordinate reference system (CRS), |
| 72 |
expressed in any format permitted by rasterio, to use for the |
| 73 |
resulting basemap. If None (default), no warping is performed |
| 74 |
and the original Spherical Mercator (EPSG:3857) is used. |
| 75 |
resampling : <enum 'Resampling'> |
| 76 |
[Optional. Default=Resampling.bilinear] Resampling |
| 77 |
method for executing warping, expressed as a |
| 78 |
`rasterio.enums.Resampling` method |
| 79 |
zoom_adjust : int or None |
| 80 |
[Optional. Default: None] |
| 81 |
The amount to adjust a chosen zoom level if it is chosen automatically. |
| 82 |
Values outside of -1 to 1 are not recommended as they can lead to slow execution. |
| 83 |
**extra_imshow_args : |
| 84 |
Other parameters to be passed to `imshow`. |
| 85 |
|
| 86 |
Examples |
| 87 |
-------- |
| 88 |
|
| 89 |
>>> import geopandas |
| 90 |
>>> import contextily as cx |
| 91 |
>>> db = geopandas.read_file(ps.examples.get_path('virginia.shp')) |
| 92 |
|
| 93 |
Ensure the data is in Spherical Mercator: |
| 94 |
|
| 95 |
>>> db = db.to_crs(epsg=3857) |
| 96 |
|
| 97 |
Add a web basemap: |
| 98 |
|
| 99 |
>>> ax = db.plot(alpha=0.5, color='k', figsize=(6, 6)) |
| 100 |
>>> cx.add_basemap(ax, source=url) |
| 101 |
>>> plt.show() |
| 102 |
|
| 103 |
Or download a basemap to a local file and then plot it: |
| 104 |
|
| 105 |
>>> source = 'virginia.tiff' |
| 106 |
>>> _ = cx.bounds2raster(*db.total_bounds, zoom=6, source=source) |
| 107 |
>>> ax = db.plot(alpha=0.5, color='k', figsize=(6, 6)) |
| 108 |
>>> cx.add_basemap(ax, source=source) |
| 109 |
>>> plt.show() |
| 110 |
|
| 111 |
""" |
| 112 |
xmin, xmax, ymin, ymax = ax.axis() |
| 113 |
|
| 114 |
if isinstance(source, str): |
| 115 |
try: |
| 116 |
source = providers.query_name(source) |
| 117 |
except ValueError: |
| 118 |
pass |
| 119 |
|
| 120 |
|
| 121 |
if ( |
| 122 |
source is None |
| 123 |
or isinstance(source, (dict, TileProvider)) |
| 124 |
or (isinstance(source, str) and source[:4] == "http") |
| 125 |
): |
| 126 |
|
| 127 |
left, right, bottom, top = xmin, xmax, ymin, ymax |
| 128 |
|
| 129 |
if crs is not None: |
| 130 |
left, right, bottom, top = _reproj_bb( |
| 131 |
left, right, bottom, top, crs, "epsg:3857" |
| 132 |
) |
| 133 |
|
| 134 |
image, extent = bounds2img( |
| 135 |
left, bottom, right, top, zoom=zoom, source=source, ll=False, zoom_adjust=zoom_adjust |
| 136 |
) |
| 137 |
|
| 138 |
if crs is not None: |
| 139 |
image, extent = warp_tiles(image, extent, t_crs=crs, resampling=resampling) |
| 140 |
|
| 141 |
if _is_overlay(source) and "zorder" not in extra_imshow_args: |
| 142 |
|
| 143 |
extra_imshow_args["zorder"] = 9 |
| 144 |
|
| 145 |
else: |
| 146 |
import rasterio as rio |
| 147 |
|
| 148 |
|
| 149 |
with rio.open(source) as raster: |
| 150 |
if reset_extent: |
| 151 |
from rasterio.mask import mask as riomask |
| 152 |
|
| 153 |
|
| 154 |
if crs: |
| 155 |
left, bottom, right, top = rio.warp.transform_bounds( |
| 156 |
crs, raster.crs, xmin, ymin, xmax, ymax |
| 157 |
) |
| 158 |
else: |
| 159 |
left, bottom, right, top = xmin, ymin, xmax, ymax |
| 160 |
window = [ |
| 161 |
{ |
| 162 |
"type": "Polygon", |
| 163 |
"coordinates": ( |
| 164 |
( |
| 165 |
(left, bottom), |
| 166 |
(right, bottom), |
| 167 |
(right, top), |
| 168 |
(left, top), |
| 169 |
(left, bottom), |
| 170 |
), |
| 171 |
), |
| 172 |
} |
| 173 |
] |
| 174 |
image, img_transform = riomask(raster, window, crop=True) |
| 175 |
extent = left, right, bottom, top |
| 176 |
else: |
| 177 |
|
| 178 |
image = np.array([band for band in raster.read()]) |
| 179 |
img_transform = raster.transform |
| 180 |
bb = raster.bounds |
| 181 |
extent = bb.left, bb.right, bb.bottom, bb.top |
| 182 |
|
| 183 |
if (crs is not None) and (raster.crs != crs): |
| 184 |
image, bounds, _ = _warper( |
| 185 |
image, img_transform, raster.crs, crs, resampling |
| 186 |
) |
| 187 |
extent = bounds.left, bounds.right, bounds.bottom, bounds.top |
| 188 |
image = image.transpose(1, 2, 0) |
| 189 |
|
| 190 |
|
| 191 |
if image.shape[2] == 1: |
| 192 |
image = image[:, :, 0] |
| 193 |
img = ax.imshow( |
| 194 |
image, extent=extent, interpolation=interpolation, **extra_imshow_args |
| 195 |
) |
| 196 |
|
| 197 |
if reset_extent: |
| 198 |
ax.axis((xmin, xmax, ymin, ymax)) |
| 199 |
else: |
| 200 |
max_bounds = ( |
| 201 |
min(xmin, extent[0]), |
| 202 |
max(xmax, extent[1]), |
| 203 |
min(ymin, extent[2]), |
| 204 |
max(ymax, extent[3]), |
| 205 |
) |
| 206 |
ax.axis(max_bounds) |
| 207 |
|
| 208 |
|
| 209 |
if source is None: |
| 210 |
source = providers.OpenStreetMap.HOT |
| 211 |
if isinstance(source, (dict, TileProvider)) and attribution is None: |
| 212 |
attribution = source.get("attribution") |
| 213 |
if attribution: |
| 214 |
add_attribution(ax, attribution, font_size=attribution_size) |
| 215 |
|
| 216 |
return |
| 217 |
|
| 218 |
|
| 219 |
def _reproj_bb(left, right, bottom, top, s_crs, t_crs): |
| 220 |
n_l, n_b, n_r, n_t = transform_bounds(s_crs, t_crs, left, bottom, right, top) |
| 221 |
return n_l, n_r, n_b, n_t |
| 222 |
|
| 223 |
|
| 224 |
def _is_overlay(source): |
| 225 |
""" |
| 226 |
Check if the identified source is an overlay (partially transparent) layer. |
| 227 |
|
| 228 |
Parameters |
| 229 |
---------- |
| 230 |
source : dict |
| 231 |
The tile source: web tile provider. Must be preprocessed as |
| 232 |
into a dictionary, not just a string. |
| 233 |
|
| 234 |
Returns |
| 235 |
------- |
| 236 |
bool |
| 237 |
|
| 238 |
Notes |
| 239 |
----- |
| 240 |
This function is based on a very similar javascript version found in leaflet: |
| 241 |
https://github.com/leaflet-extras/leaflet-providers/blob/9eb968f8442ea492626c9c8f0dac8ede484e6905/preview/preview.js#L56-L70 |
| 242 |
""" |
| 243 |
if not isinstance(source, dict): |
| 244 |
return False |
| 245 |
if source.get("opacity", 1.0) < 1.0: |
| 246 |
return True |
| 247 |
overlayPatterns = [ |
| 248 |
"^(OpenWeatherMap|OpenSeaMap)", |
| 249 |
"OpenMapSurfer.(Hybrid|AdminBounds|ContourLines|Hillshade|ElementsAtRisk)", |
| 250 |
"Stamen.Toner(Hybrid|Lines|Labels)", |
| 251 |
"CartoDB.(Positron|DarkMatter|Voyager)OnlyLabels", |
| 252 |
"Hydda.RoadsAndLabels", |
| 253 |
"^JusticeMap", |
| 254 |
"OpenPtMap", |
| 255 |
"OpenRailwayMap", |
| 256 |
"OpenFireMap", |
| 257 |
"SafeCast", |
| 258 |
] |
| 259 |
import re |
| 260 |
|
| 261 |
return bool(re.match("(" + "|".join(overlayPatterns) + ")", source.get("name", ""))) |
| 262 |
|
| 263 |
|
| 264 |
def add_attribution(ax, text, font_size=ATTRIBUTION_SIZE, **kwargs): |
| 265 |
""" |
| 266 |
Utility to add attribution text. |
| 267 |
|
| 268 |
Parameters |
| 269 |
---------- |
| 270 |
ax : AxesSubplot |
| 271 |
Matplotlib axes object on which to add the attribution text. |
| 272 |
text : str |
| 273 |
Text to be added at the bottom of the axis. |
| 274 |
font_size : int |
| 275 |
[Optional. Defaults to 8] Font size in which to render |
| 276 |
the attribution text. |
| 277 |
**kwargs : Additional keywords to pass to the matplotlib `text` method. |
| 278 |
|
| 279 |
Returns |
| 280 |
------- |
| 281 |
matplotlib.text.Text |
| 282 |
Matplotlib Text object added to the plot. |
| 283 |
""" |
| 284 |
|
| 285 |
|
| 286 |
|
| 287 |
draw() |
| 288 |
|
| 289 |
text_artist = ax.text( |
| 290 |
0.005, |
| 291 |
0.005, |
| 292 |
text, |
| 293 |
transform=ax.transAxes, |
| 294 |
size=font_size, |
| 295 |
path_effects=[patheffects.withStroke(linewidth=2, foreground="w")], |
| 296 |
wrap=True, |
| 297 |
**kwargs, |
| 298 |
) |
| 299 |
|
| 300 |
|
| 301 |
wrap_width = ax.get_window_extent().width * 0.99 |
| 302 |
text_artist._get_wrap_line_width = lambda: wrap_width |
| 303 |
return text_artist |