CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

Python Data Science Handbook

Views: 90742
Kernel: Python 3
*This notebook contains an excerpt from the [Python Data Science Handbook]( by Jake VanderPlas; the content is available [on GitHub](*

The text is released under the CC-BY-NC-ND license, and code is released under the MIT license. If you find this content useful, please consider supporting the work by buying the book!

Geographic Data with Basemap

One common type of visualization in data science is that of geographic data. Matplotlib's main tool for this type of visualization is the Basemap toolkit, which is one of several Matplotlib toolkits which lives under the mpl_toolkits namespace. Admittedly, Basemap feels a bit clunky to use, and often even simple visualizations take much longer to render than you might hope. More modern solutions such as leaflet or the Google Maps API may be a better choice for more intensive map visualizations. Still, Basemap is a useful tool for Python users to have in their virtual toolbelts. In this section, we'll show several examples of the type of map visualization that is possible with this toolkit.

Installation of Basemap is straightforward; if you're using conda you can type this and the package will be downloaded:

$ conda install basemap

We add just a single new import to our standard boilerplate:

%matplotlib inline import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap

Once you have the Basemap toolkit installed and imported, geographic plots are just a few lines away (the graphics in the following also requires the PIL package in Python 2, or the pillow package in Python 3):

plt.figure(figsize=(8, 8)) m = Basemap(projection='ortho', resolution=None, lat_0=50, lon_0=-100) m.bluemarble(scale=0.5);
Image in a Jupyter notebook

The meaning of the arguments to Basemap will be discussed momentarily.

The useful thing is that the globe shown here is not a mere image; it is a fully-functioning Matplotlib axes that understands spherical coordinates and which allows us to easily overplot data on the map! For example, we can use a different map projection, zoom-in to North America and plot the location of Seattle. We'll use an etopo image (which shows topographical features both on land and under the ocean) as the map background:

fig = plt.figure(figsize=(8, 8)) m = Basemap(projection='lcc', resolution=None, width=8E6, height=8E6, lat_0=45, lon_0=-100,) m.etopo(scale=0.5, alpha=0.5) # Map (long, lat) to (x, y) for plotting x, y = m(-122.3, 47.6) plt.plot(x, y, 'ok', markersize=5) plt.text(x, y, ' Seattle', fontsize=12);