How to draw a map using Python (Cartopy)

cartopy

There’s a useful Python module called “Cartopy”.  Cartopy is a mapping module which allows a person to not only draw pretty maps; it also allows you to plot locations using coordinates.  Something which is useful for Archaeologists.

In this tutorial, I am going to show you how to draw a basic map and plot some lat long coordinates using Cartopy (for later use in the MySQLdb tutorial series).

N.B I am using Ubuntu 64bit desktop v14.04 LTS, and Python2.7.  We will also need a series of dependencies installing.

Step 1 – Install Dependencies

1. In a terminal type the following:

sudo apt-get install python-numpy python-six python-matplotlib python-shapely python-pyshp cython libgeos-dev libproj-dev

Step 2 – Install Cartopy

1. In a terminal type the following:

sudo git clone https://github.com/SciTools/cartopy.git

cd cartopy

sudo python setup.py install

Step 3 – Write the mapping script

In the following example, the variables ox-lon, ox-lat are simply the longitude and latitude values for the City of Oxford UK, you may use whichever you like.  Remember that if a latitude variable is for West, it is a negative “floating point” number, East is positive.  A negative longitude variable is for South and positive for North.

#import cartopy and matplotlib modules
import cartopy.crs as ccrs 
import matplotlib.pyplot as plt

#define the variables to hold longitude and latitude values 
ox_lon, ox_lat = 51.7519, -1.2578

#select the projection you want, plot the resolution you wish to use, define a background image 
ax = plt.axes(projection=ccrs.PlateCarree()) 
ax.coastlines()
ax.stock_img()

#plot the variables as a point marker on the map 
plt.plot(ox_lat, ox_lon, color='blue', marker='o',transform=ccrs.PlateCarree())

#add a legend to the point offset so it's readable reading 'Oxford' of whatever 
plt.text(ox_lat - 5, ox_lon - 3, 'Oxford', horizontalalignment='right',transform=ccrs.PlateCarree())

#display the plot in a window 
plt.show()

This is what the plotted map should look like using the above code!
oxford_map

In a future tutorial I am going to combine this with another tutorial to show you how to grab map coordinate data from a MySQL database and plot it on a map at the appropriate scale!

3 thoughts on “How to draw a map using Python (Cartopy)”

  1. Could you please suggest
    1. to install the Cython from zip file as i was getting error at import setuptools.
    2. to install basemap in python .

    1. Sorry you’re having problems. This tutorial is only a basic guide and not meant to cover all options i.e. Ubuntu 14.04 and Python2.7. As for setuptools issues. Could be you don’t have correct version installed. “Try sudo apt-get install python-setuptools” after “sudo update” and “sudo upgrade”. My example doesn’t seem to need the basemap module on my computer. Are you getting an error message?

Comments are closed.