Basemap inset

This example is a modified version of the inset example from the geophysique blog.

In [2]:
import numpy as np
import numpy.ma as ma
import matplotlib.pyplot as plt
from oceans.datasets import etopo_subset


We need to import Basemap, Polygon and inset_axes:

In [3]:
from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Polygon
from mpl_toolkits.axes_grid1.inset_locator import inset_axes


Now we can define functions to generate the plot:

In [4]:
def map_limits(m):
llcrnrlon = min(m.boundarylons)
urcrnrlon = max(m.boundarylons)
llcrnrlat = min(m.boundarylats)
urcrnrlat = max(m.boundarylats)
return llcrnrlon, urcrnrlon, llcrnrlat, urcrnrlat

def make_map(llcrnrlon=-49, urcrnrlon=-39, llcrnrlat=-30, urcrnrlat=-21,
projection='merc', resolution='i', figsize=(6, 6), inset=True):
m = Basemap(llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon,
llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat,
projection=projection, resolution=resolution)
fig, ax = plt.subplots(figsize=figsize)
m.drawstates()
m.drawcoastlines()
m.fillcontinents(color='0.85')
meridians = np.arange(llcrnrlon, urcrnrlon + 2, 2)
parallels = np.arange(llcrnrlat, urcrnrlat + 1, 1)
m.drawparallels(parallels, linewidth=0, labels=[1, 0, 0, 0])
m.drawmeridians(meridians, linewidth=0, labels=[0, 0, 0, 1])
m.llcrnrlon = llcrnrlon
m.urcrnrlon = urcrnrlon
m.llcrnrlat = llcrnrlat
m.urcrnrlat = urcrnrlat
m.ax = ax

if inset:
axin = inset_axes(m.ax, width="40%", height="40%", loc=4)
# Global inset map.
inmap = Basemap(projection='ortho', lon_0=-44.5, lat_0=-25.5,
ax=axin, anchor='NE')
inmap.drawcountries(color='white')
inmap.fillcontinents(color='gray')
bx, by = inmap(m.boundarylons, m.boundarylats)
xy = list(zip(bx, by))
mapboundary = Polygon(xy, edgecolor='k', linewidth=1, fill=False)
return fig, m


And here the result:

In [5]:
fig, m = make_map(llcrnrlon=-48, urcrnrlon=-41.5, llcrnrlat=-27,
urcrnrlat=-22.5, figsize=(5, 6))

# Topography.
lon, lat, topo = etopo_subset(*map_limits(m), smoo=True, tfile='dap')
topo = np.where(topo > -1., 1.e10, topo)
topo = ma.masked_values(topo, 1.e10)
cs = m.contour(lon, lat, -topo, (100, 200, 500, 1000), colors='k',
latlon=True, alpha=0.5)
_ = m.ax.clabel(cs, fmt='%1.0f m', fontsize=8, inline=1)

In [6]:
HTML(html)

Out[6]:

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