python4oceanographers

Turning ripples into waves

Cartopy and the Natural Earth Dataset

Alternative dataset to plot the Brazilian political boundaries.

We already saw some of the advantages of cartopy over other mapping tools. However, as a Brazilian, I really miss a more up-to-date political boundary than those present in tools like GMT, m_map, and basemap.

Luckily cartopy can talk easily with the Natural Earth dataset. Natural Earth has tons of updated data all in available in a public domain license.

Let's try it:

In [2]:
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
from cartopy.feature import NaturalEarthFeature, LAND, COASTLINE
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER

def brazil_states(projection=ccrs.PlateCarree()):
    fig, ax = plt.subplots(figsize=(8, 6), subplot_kw=dict(projection=projection))
    ax.set_extent([-82, -32, -45, 10])
    ax.stock_img()
    ax.add_feature(LAND)
    ax.add_feature(COASTLINE)
    gl = ax.gridlines(draw_labels=True)
    gl.xlabels_top = False
    gl.ylabels_right = False
    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER
    return fig, ax

Natural Earth is has a collection of shapefiles designated by category and name. I find it interesting that the states/provinces category is called cultural instead of political. Now look at the final figure.

In [3]:
fig, ax = brazil_states()
states = NaturalEarthFeature(category='cultural', scale='50m', facecolor='none',
                             name='admin_1_states_provinces_shp')
_ = ax.add_feature(states, edgecolor='gray')
/home/filipe/miniconda3/envs/Blog/lib/python2.7/site-packages/matplotlib/artist.py:221: MatplotlibDeprecationWarning: This has been deprecated in mpl 1.5, please use the
axes property.  A removal date has not been set.
  warnings.warn(_get_axes_msg, mplDeprecation, stacklevel=1)

No more jumping through hoops to get an external updated shapefile, loading and plotting it. There is also an interesting alternative plotting option that draws the states without the country line, so you can add a thicker country line later.

In [4]:
fig, ax = brazil_states()
states = NaturalEarthFeature(category='cultural', scale='50m', facecolor='none',
                             name='admin_1_states_provinces_lines')
_ = ax.add_feature(states, edgecolor='gray')
In [5]:
HTML(html)
Out[5]:

This post was written as an IPython notebook. It is available for download or as a static html.

Creative Commons License
python4oceanographers by Filipe Fernandes is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Based on a work at https://ocefpaf.github.io/.

Comments