用cartopy制作透明图

Make a transparent plot with cartopy

我想用 Cartopy 创建一个透明地图(然后可以用作网络应用程序的叠加层)。

尝试过多种设置、投影、绘图类型等,但从未设法获得透明的 Cartopy 贴图。

这是一个简单的例子,说明透明度如何不适用于 Cartopy,以及它如何在不使用 Cartopy 的情况下工作。

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

#some data:
shape=(20, 30)
scale = 30
x = np.linspace(-scale, scale, shape[1])
y = np.linspace(-scale, scale, shape[0])

x2d, y2d = np.meshgrid(x, y)
u = 10 * np.cos(2 * x2d / scale + 3 * y2d / scale)
v = 20 * np.cos(6 * x2d / scale)

#cartopy
ef, ax = plt.subplots(1,1,figsize=(10,8), subplot_kw={'projection': ccrs.GOOGLE_MERCATOR})    
ef.subplots_adjust(hspace=0.0,wspace=0,bottom=0,top=1,left=0,right=1)

ax.quiver(x2d,y2d, u, v, transform=ccrs.GOOGLE_MERCATOR)

plt.savefig('cartopy_opaque.png',transparent=True)
plt.close()

#pure matplotlib:
ef, ax = plt.subplots(1,1,figsize=(10,8))    
ef.subplots_adjust(hspace=0.0,wspace=0,bottom=0,top=1,left=0,right=1)

ax.quiver(x2d,y2d, u, v)
plt.savefig('noncartopy_transparent.png',transparent=True)
plt.close()

我是不是遗漏了什么,或者透明度对 Cartopy 不起作用?

我发现了一个类似的问题here。添加

ax.background_patch.set_alpha(0)

应该可以解决这个问题。

Am I missing something here, or is transparency not working for Cartopy?

是和否。Cartopy 的透明度与 matplotlib 的透明度不同。造成这种情况的原因有很多,但主要原因是 cartopy 具有高度 non-rectangular 轴(例如 Interrupted Goode Homolosine):

因此,有两个补丁需要控制透明度:ax.background_patchax.outline_patch

以下应该足够了:

ax.outline_patch.set_visible(False)
ax.background_patch.set_visible(False)

github 问题跟踪器上提出了类似的问题: https://github.com/SciTools/cartopy/issues/465

我还整理了一个生成地图瓦片的例子,这在很大程度上依赖于制作透明地图:https://gist.github.com/pelson/9738051

HTH