循环绘图,然后对选定数量的绘图进行求和

问题描述 投票:0回答:1

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

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

附件是我的 EOF 图现在的样子。我想在第四列中添加求和。

EOFs plot from Function

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

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

这是代码:

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

python matplotlib physics python-xarray
1个回答
0
投票

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

首先,您的索引

i
用于
mode
中的
eof12.sel(mode=i)
以及子图索引。当您仅绘制模式时,这很好。现在,您有了一个新列,索引将具有不同的含义。

我会称他们为

imode
isubplt

接下来,每次都会有一个额外的次要情节

i % 3 == 2
。这是你的标记。每次发生这种情况时,
isubplt
都会增加,但
imode
不会增加。

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

ax
来设置第四列。

这里缺少的是计算总和的代码。根据您的说法,您希望将

eof_sum
初始化为零并将每个
eof_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')
© www.soinside.com 2019 - 2024. All rights reserved.