Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom shapefile to map using cartopy

Tags:

cartopy

Using basemap I used to add my custom boundary shapefile like this:

map = Basemap(..)
map.readshapefile(file.shp, 'attribute', drawbounds=True)

How can I do the same using cartopy?

I tried this:

ax.add_feature(cfeature.shapereader.Polygon('file.shp'))

but that's not working..

like image 837
Mattijn Avatar asked Jan 08 '14 08:01

Mattijn


1 Answers

There is currently no ShapefileFeature class (though that would be easy enough to create, and would probably make a lot of sense) so if you really want to use the feature interface then there is a hoop to jump through:

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.io.shapereader import Reader
from cartopy.feature import ShapelyFeature

fname = '50m_glaciated_areas.shp'

ax = plt.axes(projection=ccrs.Robinson())
shape_feature = ShapelyFeature(Reader(fname).geometries(),
                                ccrs.PlateCarree(), facecolor='none')
ax.add_feature(shape_feature)
plt.show()

Alternatively, you could just use the add_geometries method, which is not making use of the feature interface (and so, in the future, will not be optimised to read from disk only the geometries which are actually being drawn as would be the case with a ShapefileFeature class):

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.io.shapereader import Reader

fname = '50m_glaciated_areas.shp'

ax = plt.axes(projection=ccrs.Robinson())
ax.add_geometries(Reader(fname).geometries(),
                  ccrs.PlateCarree(),
                  facecolor='white', hatch='xxxx')
plt.show()

hatched glaciated areas

HTH

like image 129
pelson Avatar answered Oct 21 '22 06:10

pelson