并排绘制两个数组中的两个图形

Plotting two figures from two xarrays side by side

我正在尝试并排绘制两个子图。 每个子图都是来自 xarray 的变量,图是一个投影。

我的绘图函数是:

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})

主要代码是:

fig = plt.figure()

ax1 = fig.add_subplot(111)
plot_avg(var1)
ax2 = fig.add_subplot(122)
plot_avg(var2)

但出于某种原因我做不到,我总是得到一个带有两个颜色条的图:

我能做些什么不同的事情?我很难处理 xarray 中的绘图对象。

用于绘图的样本数据文件在这里: netcdf files

尝试将 ax 定义为函数的参数:

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})

然后将你创建的ax传入函数调用:

fig = plt.figure()

ax1 = fig.add_subplot(111)
plot_avg(var1, ax1)
ax2 = fig.add_subplot(122)
plot_avg(var2, ax2)

您在此处创建的轴过多。确保只创建您要使用的两个轴。

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)