Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a transparent plot with cartopy

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?

like image 549
yngwaz Avatar asked May 06 '15 12:05

yngwaz


2 Answers

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):

IGH

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

like image 177
pelson Avatar answered Nov 02 '22 05:11

pelson


I found a similar problem here. Adding

ax.background_patch.set_alpha(0)

should solve this.

like image 2
AniaG Avatar answered Nov 02 '22 07:11

AniaG