Search code examples
pythonmatplotlibcartopy

How to add a projection to axis in matplotlib when using subplot2grid?


I am trying to plot five maps in five different subplots using cartopy. What I want to do is to plot three maps in the upper row, and the two remaining maps in the lower row, but have these two last subplots centralized. I managed to do that adding the subplot axes using:

import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = plt.subplot2grid((2, 6), (0, 0), colspan=2)
ax2 = plt.subplot2grid((2, 6), (0, 2), colspan=2)
ax3 = plt.subplot2grid((2, 6), (0, 4), colspan=2)
ax4 = plt.subplot2grid((2, 6), (1, 1), colspan=2)
ax5 = plt.subplot2grid((2, 6), (1, 3), colspan=2)

however I can't find a way to create these subplots with a cartographic projection. Normally, for an even number of subplots I would do:

import cartopy.crs as ccrs
fig, Ax = plt.subplots(nrows=2,ncols=3, subplot_kw=dict(projection=ccrs.PlateCarree()),constrained_layout=True)

But I don't know how to do that using subplot2grid. Is this possible or is there another way to create maps spaning more than one row or column in matplotlib?


Solution

  • The documentation for subplot2grid has

    **kwargs  
         Additional keyword arguments are handed to add_subplot.
    

    and add_subplot supports the projection= keyword argument. Hence

    ax1 = plt.subplot2grid((2, 6), (0, 0), colspan=2, projection=ccrs.PlateCarree())
    

    is all that you need.