Saturday 24 October 2020

Flexible map ticklables with cartopy

Quite regularly I find myself in the need of plotting (a lot of) maps of a variety of regions and region sizes. I would like these maps to have ticklabels indicating longitude and latitude (similar to this example: https://scitools.org.uk/cartopy/docs/v0.15/examples/tick_labels.html).

However, the solution suggested there does not work for me since it requires a priori knowledge about the region extend. I've written several way too complicated functions over the years in order to try and make this work in a flexible way. So what I'm wondering at this point: is there a simple solution to put latitude & longitude ticklabels to a map of variable extend?

This here comes somewhat close but is still quite unreliable:

import numpy as np
import cartopy.crs as ccrs 
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
import matplotlib.pyplot as plt


def auto_labeling(lon=np.linspace(-10, 40, 10), lat=np.linspace(30, 70, 10), filename='test1.png'):
    proj = ccrs.PlateCarree(central_longitude=0)
    data = np.ones((len(lon), len(lat)))
    ax = plt.subplot(projection=proj)
    ax.pcolormesh(lon, lat, data, transform=ccrs.PlateCarree(), alpha=.5)
    ax.coastlines()
    ax.set_xticks(ax.get_xticks(), crs=ccrs.PlateCarree())
    ax.set_yticks(ax.get_yticks(), crs=ccrs.PlateCarree())
    lon_formatter = LongitudeFormatter()
    lat_formatter = LatitudeFormatter()
    ax.xaxis.set_major_formatter(lon_formatter)
    ax.yaxis.set_major_formatter(lat_formatter)
    plt.savefig(filename, dpi=300)
    plt.close()


if __name__ == '__main__':
    auto_labeling(filename='test3.png')  # nice
    auto_labeling(np.linspace(-120, 120, 10), filename='test4.png')  # not nice but somewhat okay
    auto_labeling(np.linspace(-120, 120, 10), np.linspace(-70, 70, 10), filename='test5.png')  # nice
    # auto_labeling(np.linspace(-180, 180, 10), np.linspace(-90, 90, 10), filename='test6.png')  # fails


from Flexible map ticklables with cartopy

No comments:

Post a Comment