Replacing Cartopy’s Background Image

  • keywords:
    • software
    • python
    • cartopy
    • requests
  • published:
  • updated:
  • Atom Feed

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).

  1. 512x256 (171.8 KiB)
  2. 720x360 (320.5 KiB)

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).

  1. 512x256 (167.3 KiB)
  2. 1,024x512 (650.4 KiB)
  3. 2,048x1,024 (2.6 MiB)
  4. 4,096x2,048 (11.0 MiB)
  5. 8,192x4,096 (41.3 MiB)
  6. 21,600x10,800 (222.6 MiB)

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: