Replacing Cartopy’s Background Image

metadata
  • keywords:
    • software
    • python
    • cartopy
  • published:

Whilst discussing a friend’s summary of 2017 I found it difficult to place parts of Michigan that I had visited as The Great Lakes were missing from the state boundaries. My friend then countered that my own maps did not feature The Great Lakes either. Disbelieving, I went away and checked; he was correct - Cartopy’s default background image does not show The Great Lakes (shown below).

Cartopy’s default background image
Cartopy’s default background image

If you would like to check for yourself then the following Python code will show you where the default image is located for your installation of Cartopy.

As of January 2018, that folder only contains one image, called 50-natural-earth-1-downsampled.png, which has dimensions 720x360 and size 327K. The sidecar JSON file (shown below) describes the contents of the folder.

I decided to create my own folder of background images, using the same specification that Cartopy uses, so that I could have both higher resolution background images and ones that contained large inland bodies of water. The script that I wrote to download the ZIP archives from Natural Earth, extract the TIFFs, create the PNGs and create the JSON is shown below. It runs both convert and optipng during its execution.

The JSON file that it creates is shown below for comparison with the original one.

The PNG files that it creates are shown below for comparison with the original one too. Note that The Great Lakes and Lake Victoria are easily visible (to name a few).

Download:
  1. 512x256
  2. 1024x512
  3. 2048x1024
  4. 4096x2048
  5. 21600x10800

Great - but how am I going to use this new folder that has the same organisation as Cartopy’s folder? I have written a replacement function, called pyguymer.add_map_background(), that I can use so that my scripts use this new folder. Now all that I need to do is set the environment variable $CARTOPY_USER_BACKGROUNDS to the path that my new images are in and then replace all instances of ax.stock_img() in all of my Python scripts with either pyguymer.add_map_background(ax) (for a low-resolution background image for testing purposes) or pyguymer.add_map_background(ax, resolution = "large4096px") (for a high-resolution background image for publishing purposes).

You can see the fruits of this work by looking at the example image in my Flight Map Creator project on GitHub. The following web pages have been useful during this project: