Reputation: 1801
I'm trying to plot two subplots side by side. Each subplot is a variable from xarray, and the plot is a projection.
My plotting function is:
from matplotlib import pyplot as plt
import cartopy.crs as ccrs
import cartopy
def plot_avg(data, **kwargs):
ax = plt.axes(projection=ccrs.Orthographic(central_latitude=-90.0))
ax.coastlines(resolution='10m',zorder=3)
ax.gridlines(color='gray')
ax.add_feature(cartopy.feature.LAND, zorder=1,facecolor=cartopy.feature.COLORS['land_alt1'])
data.plot(ax = ax, transform=ccrs.PlateCarree(),
vmin = 34.4 , vmax=35.81 , levels=17 ,
cmap=Becki, cbar_kwargs={'shrink': 0.3})
And the main code is:
fig = plt.figure()
ax1 = fig.add_subplot(111)
plot_avg(var1)
ax2 = fig.add_subplot(122)
plot_avg(var2)
But for some reason I can't do it, i always get one plot with two colorbars:
What can I do differently? I'm having a hard time with the plot objects from the xarray.
The sample data files for plotting are here: netcdf files
Upvotes: 1
Views: 1184
Reputation: 339230
You create too many axes here. Make sure to only create the two axes you want to use.
def plot_avg(data, ax, **kwargs):
ax.coastlines(resolution='10m',zorder=3)
ax.gridlines(color='gray')
ax.add_feature(cartopy.feature.LAND, zorder=1,facecolor=cartopy.feature.COLORS['land_alt1'])
data.plot(ax = ax, transform=ccrs.PlateCarree(),
vmin = 34.4 , vmax=35.81 , levels=17 ,
cmap=Becki, cbar_kwargs={'shrink': 0.3})
fig = plt.figure()
ax1 = fig.add_subplot(121, projection=ccrs.Orthographic(central_latitude=-90.0))
plot_avg(var1, ax1)
ax2 = fig.add_subplot(122, projection=ccrs.Orthographic(central_latitude=-90.0))
plot_avg(var2, ax2)
Upvotes: 2
Reputation: 729
Try defining ax
as a parameter to your function:
def plot_avg(data, ax, **kwargs):
ax = plt.axes(projection=ccrs.Orthographic(central_latitude=-90.0))
ax.coastlines(resolution='10m',zorder=3)
ax.gridlines(color='gray')
ax.add_feature(cartopy.feature.LAND, zorder=1,facecolor=cartopy.feature.COLORS['land_alt1'])
data.plot(ax = ax, transform=ccrs.PlateCarree(),
vmin = 34.4 , vmax=35.81 , levels=17 ,
cmap=Becki, cbar_kwargs={'shrink': 0.3})
Then pass the ax
you create into the function call:
fig = plt.figure()
ax1 = fig.add_subplot(111)
plot_avg(var1, ax1)
ax2 = fig.add_subplot(122)
plot_avg(var2, ax2)
Upvotes: 0