geopandas / contextily

Context geo-tiles in Python
https://contextily.readthedocs.io/en/latest/
BSD 3-Clause "New" or "Revised" License
493 stars 81 forks source link

How to clip background image to circle? #232

Closed zxdawn closed 5 months ago

zxdawn commented 5 months ago

Hi, I'm trying to plot a circle shape background using contextily. I see it is easy to clip the pcolormesh result like below.

I'm curious if there's any similar method of clip_path for contextily?

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import numpy as np
import matplotlib
import contextily as cx

fig, ax = plt.subplots(figsize=(5, 5),
                       subplot_kw={'projection':ccrs.PlateCarree()}
                       )

dx, dy = 0.05, 0.05

# generate 2 2d grids for the x & y bounds
y, x = np.mgrid[slice(1, 5 + dy, dy),
                slice(1, 5 + dx, dx)]
z = np.sin(x)**10 + np.cos(10 + y*x) * np.cos(x)

theta = np.linspace(0, 2*np.pi, 400)
center, radius = [0.5, 0.5], 0.5
verts = np.vstack([np.sin(theta), np.cos(theta)]).T
circle = matplotlib.path.Path(verts * radius + center)

im = ax.pcolormesh(x, y, z, cmap='viridis', clip_path=(circle, ax.transAxes))
ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
                  linewidth=2, color='gray', alpha=0.5, linestyle='--')

image

zxdawn commented 5 months ago

I figured out how to do that and posted it on stackoverflow.