遍历绘图,然后取选定数量的绘图的总和

Looping through plots, then taking sum of a select number of plots

提问人:humanoid_physics 提问时间:11/11/2023 最后编辑:Emilio Silvahumanoid_physics 更新时间:11/11/2023 访问量:37

问:

我正在尝试创建一个函数来绘制 EOF 并循环遍历每种模式。这部分很好,我毫不费力地得到了 12 个 EOF 的图。

但是,现在我想对前三个 EOF 图、前六个 EOF 图、前九个 EOF 图以及所有 EOF 图求和,以便在每行的末尾生成一个图,以显示前三个、前六个等的累积总和。

附上我现在的EOF图的样子。我想在第四列中添加汇总。

EOFs plot from Function

我尝试创建一个新循环,它基本上是一个“if 语句”,说明如果该列是最后一个对先前的 EOF 模式求和并为这些模式添加子图(在第 4 列中)。

不幸的是,在这样做时,我没有看到我的情节有任何变化。我尝试将 i 的总和更改为 i(我会将其解释为遍历每个模式),甚至每个模式的显式调用,最终会产生错误。我很难弄清楚如何从 for 循环中对 eofs 求和。

代码如下:

def GPH_EOFs_plot(eof12):
    fig = plt.figure(figsize=(12,8))
    for i in range(0,12):
        clevs = np.linspace(-75, 75, 11)
        proj = ccrs.Orthographic(central_longitude=-90, central_latitude=90)
        ncols = 4
        nrows = 3
        ax = plt.subplot(ncols,nrows,i+1, projection = proj)
        ax.coastlines(color='grey', linewidth=1.0)
        ax.set_global()
        eofs = eof12.sel(mode=i)
        eofs_2d = eofs.squeeze()
        eofs_2d.plot.contourf(ax=ax, levels=clevs, cmap=plt.cm.RdBu_r, transform=ccrs.PlateCarree(), add_colorbar=False)
        if ncols == 3:
            eof_sum = sum(i)
            eof_sum.plot.contourf(ax=ax, levels=clevs, cmap=plt.cm.RdBu_r, transform=ccrs.PlateCarree(), add_colorbar=True)


    plt.savefig("EOFs_fromfunction.png",format='png')

蟒蛇 matplotlib 物理 python-xarray

评论


答:

0赞 Emilio Silva 11/11/2023 #1

代码存在一些问题,我无法对此进行测试,但这是一种尝试。

首先,您的索引被用于 in 和子图索引。当您只绘制模式时,这很好。现在,您有了一个新列,索引将具有不同的含义。imodeeof12.sel(mode=i)

我会打电话给他们,然后.imodeisubplt

接下来,你每次都有一个额外的子情节。这是你的标记。每次发生这种情况时,都必须增加,但不是.i % 3 == 2isubpltimode

最后,您需要通过创建一个新的 .ax

这里缺少的是计算总和的代码。从你所说的,你想初始化为零,然后把每个零相加。您必须填写此代码。eof_sumeof_2d

def GPH_EOFs_plot(eof12):
    fig = plt.figure(figsize=(12,8))
    eof_sum = ### TODO: initialize eof_sum to all zeros ###
    isubplt = 1 # subplots start at 1
    for imode in range(0,12):
        clevs = np.linspace(-75, 75, 11)
        proj = ccrs.Orthographic(central_longitude=-90, central_latitude=90)
        ncols = 4
        nrows = 4 # now you will have four lines
        ax = plt.subplot(ncols, nrows, isubplt, projection = proj)
        isubplt += 1 # skip to the next subplot
        ax.coastlines(color='grey', linewidth=1.0)
        ax.set_global()
        eofs = eof12.sel(mode=imode)
        eofs_2d = eofs.squeeze()
        eof_sum = ### TODO: accumulate this plot ###
        eofs_2d.plot.contourf(ax=ax, levels=clevs, cmap=plt.cm.RdBu_r, transform=ccrs.PlateCarree(), add_colorbar=False)
        if imode % 3 == 2:
            # create the fourth subplot
            ax = plt.subplot(ncols, nrows, isubplt, projection = proj)
            isubplt += 1 # skip to the next subplot
            ax.coastlines(color='grey', linewidth=1.0)
            ax.set_global()
            eof_sum.plot.contourf(ax=ax, levels=clevs, cmap=plt.cm.RdBu_r, transform=ccrs.PlateCarree(), add_colorbar=True)

    plt.savefig("EOFs_fromfunction.png",format='png')