cartopy icon indicating copy to clipboard operation
cartopy copied to clipboard

align a cartopy 2D map plot with a 1D line plot

Open miniufo opened this issue 5 years ago • 11 comments

I need to align a cartopy 2D map subplot with a 1D line subplot (zonal-mean or meridional mean of the 2D data), using the following code:

import xarray as xr
import cartopy.crs as ccrs
import matplotlib.pyplot as plt


air = xr.tutorial.open_dataset('air_temperature').air[0]

fig = plt.figure(figsize=(14,5))

ax1 = fig.add_subplot(121,
                 projection=ccrs.PlateCarree(central_longitude=180))
air.plot.pcolormesh(ax=ax1,
               transform=ccrs.PlateCarree(),
               cbar_kwargs={'orientation':'horizontal'})
ax1.coastlines()
ax1.set_extent((air.lon[0], air.lon[-1], air.lat[-1], air.lat[0]),
               crs=ccrs.PlateCarree())

ax2 = fig.add_subplot(122)
air.mean('lon').plot(ax=ax2, y='lat')

plt.tight_layout()

This gives the plot as this.

Both subplots have the same y- (latitude-) range and I expect the boxes of the two axes could align with each other. Is there a simple way to do this? This has been proposed on stackoverflow.

miniufo avatar Mar 27 '20 07:03 miniufo

I have not tested, but I would guess that you would have to set the aspect ratio of the plain Axes to something that would match the Cartopy Axes.

QuLogic avatar Apr 10 '20 21:04 QuLogic

This example in the Iris gallery demonstrates how Cartopy and Matplotlib can be used to achieve this.

trexfeathers avatar Jan 06 '23 12:01 trexfeathers

I would use compressed layout rather than tight layout. I added an answer on StackOverflow.

Edit: sorry I only just noticed how old this issue is. But now that compressed layout exists as a solution in mpl, perhaps this issue can be closed?

rcomer avatar Jan 06 '23 13:01 rcomer

Thanks for your suggestions. I've already got this resolved using proplot as a workaround.

However, if one uses a projection (e.g., Robin) other than PlateCarree, then the latitudes would be slightly stretched. In this case can we still have a equivalent zonal-mean plot aligned with the projection?

miniufo avatar Jan 06 '23 15:01 miniufo

Just tested with Mollweide and this is indeed a problem

trexfeathers avatar Jan 06 '23 16:01 trexfeathers