I'd like to create a transparent map with Cartopy (which could then be used as an overlay for a web application).
Have tried to play with several settings, projections, type of plots etc., but never managed to get a transparent Cartopy map.
Here is a simple example of how transparency does not work with Cartopy, and how it works without using 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()
Am I missing something here, or is transparency not working for Cartopy?
Am I missing something here, or is transparency not working for Cartopy?
Yes and No. Cartopy's transparency is not the same as matplotlib's. There were a number of reasons for this, but the primary one is that cartopy has highly non-rectangular axes (such as Interrupted Goode Homolosine):
For this reason there are two patches which need to be controlled for transparency: ax.background_patch
and ax.outline_patch
The following should be sufficient:
ax.outline_patch.set_visible(False)
ax.background_patch.set_visible(False)
There was a similar question asked on the github issue tracker: https://github.com/SciTools/cartopy/issues/465
I also put together an example of generating map tiles, which is heavily dependent upon making transparent maps: https://gist.github.com/pelson/9738051
HTH
I found a similar problem here. Adding
ax.background_patch.set_alpha(0)
should solve this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With