0
votes

I have two plots; a geographic map and a line plot

I want the height of the line plot to match the height of the geographic map. Is there a way to get the aspect ratio from the cartopy geoaxes? If I do ax1.get_aspect(), it returns 'equal'.

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

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

plt.figure(figsize=(15, 10))
ax1 = plt.subplot(121, projection=ccrs.PlateCarree())
ds.plot(transform=ccrs.PlateCarree(), ax=ax1, add_colorbar=False)

ax2 = plt.subplot(122)
ax2.plot([1, 2, 3], [5, 6, 7])

Final Edit: I misread; there's a difference between a divider and ax. I didn't know you could spawn multiple axes from dividers.

import xarray as xr
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

fig = plt.figure(figsize=(13, 8))
ax1 = fig.add_subplot(111, projection=ccrs.PlateCarree())
img = xr.tutorial.open_dataset('air_temperature')['air'].isel(time=0).plot(
    x='lon', y='lat', ax=ax1, transform=ccrs.PlateCarree(), add_colorbar=False)
ax1.coastlines()
ax1.set_title('ax1')

divider = make_axes_locatable(ax1)
ax2 = divider.new_horizontal(size="10%", pad=0.1, axes_class=plt.Axes)
fig.add_axes(ax2)
plt.colorbar(img, cax=ax2)

ax3 = divider.new_horizontal(size="100%", pad=1, axes_class=plt.Axes)
fig.add_axes(ax3)
ax3.plot([1, 2, 3], [5, 6, 7])

enter image description here

1
Easiest would be to use smth like figsize=(15, 4) and play with the last number until it fits. - ImportanceOfBeingErnest
Unfortunately, I need to it be all automated; so I want to find the actual aspect ratio of the map and readjust the aspect ratio of the line. - Andrew

1 Answers

2
votes

I would use mpl_toolkits.axes_grid1.make_axes_locatable similar to how it's done in Correct placement of colorbar relative to geo axes (cartopy) for a colorbar. The difference is that you would create the axes for your plot instead of an axes for a colorbar.

import cartopy.crs as ccrs
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable


fig = plt.figure(figsize=(13, 8))
ax1 = fig.add_subplot(111, projection=ccrs.PlateCarree())
ax1.coastlines()

divider = make_axes_locatable(ax1)
ax2 = divider.new_horizontal(size="100%", pad=0.4, axes_class=plt.Axes)
fig.add_axes(ax2)
ax2.plot([1, 2, 3], [5, 6, 7])

plt.show()

enter image description here