Using Cartopy to draw maps and plot points

Let's do something simple but useful for geographical data science: drawing a map in Python. I will assume you are using the Anaconda distribution.

Unfortunately, there are many mapping libraries for different programming ecosystems and it's a little hard to find out which you should use. For a long time in Python, Basemap was the standard, but that project will soon be no longer maintained in favour of a newer library, Cartopy. That is what we will be using today, along with matplotlib. To install these in Anaconda, use:

Once you install these, here is minimal Python code to draw a map:

The class is the coordinate reference system and contains a bunch of different projects of maps and an system to translate the usual latitude and longitude coordinates to whatever internal coordinates are needed to plot stuff on a computer screen.

Once you create a plt.axes object, you can add stuff to it. The most basic is the actual outline of the continents, given by the coastlines function. There are three possibilities for resolution: 110m, 50m, and 10m, going from coarsest to finest. There are other ways to get more detail, country borders, etc. that I will cover another time.

From then, you use matplotlib to save and show your map. You end up with an interactive map on the screen and that same map saved to a file. This is what it looks like:

I need to show you two more things so you can at least do basic stuff with this map. The first is drawing a region other than the world. In this case you have to use the set_extent function in the plt.axes class. Here is the new full example:

The region you want to plot is given by four numbers: the first two represent the longitude interval, the second two the latitude interval. To get these numbers, just use the interactive map you get when you run the first example. Hovering your mouse over the map will show the coordinates of points. Now we get:

The final thing you just have to know is how to plot points. If you already know matplotlib then this should come as no surprise: we use plt.plot. Since we already are using an axis system from Cartopy, we specify the coordinates of the points in terms of (longitude, latitude). Here is the complete example:

We get:

This is a spot in the Yarra Bend Park in Melbourne, Australia, by the way. At any rate, now you have all you need to start creating basic maps with some plotted points. There's of course a whole lot more you'll probably want to do with maps such as fancier graphics, and that will be covered in future tutorials!

Leave a comment

Fields marked with * are required. LaTeX snippets may be entered by surrounding them with single dollar signs. Use double dollar signs for display equations.