matplotlib 如何在while循环中循环子情节的轴?

mspsb9vt  于 2023-01-21  发布在  其他
关注(0)|答案(1)|浏览(122)

我如何使用while循环条件来循环子图的轴。我对python很陌生。我写了一个代码,在其中我根据while循环中的一些条件来绘制数据。这个代码对于绘制单个图来说工作得很好,但是当我不得不像子图那样在一个图中绘制所有的时候,我不知道我如何索引,每次一轮绘图完成时,轴索引应该改变,下一次绘图在不同的索引上完成。如图所示,绘制第一行,其余所有内容都重新绘制,因为循环没有条件进行轴索引。我如何实现的是,每次代码中的i、j、l、m值增加时,图应移动到子图中的下一行。[

]

import matplotlib.pyplot as plt
import xarray as xr
file="/home/arjun2516/hlrn/JOBS/cy_topo_ref4hr2/OUTPUT/cy_topo_ref4hr2_av_3d.002.nc"
Data=xr.open_dataset(file)

l=150
m=300
i = 75
j = 175
while i and j < 700 and l and m < 800 :
    fig,axs = plt.subplots(ncols=3, nrows=3,figsize=(20,20))
    Data.zusi[i:j,75:175].plot.contourf(ax=axs[0,0])
    print(i,j)
    # plt.show()
    Data.zusi[l:m,250:400].plot.contourf(ax=axs[0,1])
    #  plt.show()
    Data.zusi[l:m,450:600].plot.contourf(ax=axs[0,2])
    # plt.show()
    i += 200
    j += 200
    l += 200
    m += 200
    print(i,j)
print('ok')

我尝试在while循环中引入一个for循环,但它也产生了相同的结果。

pbwdgjma

pbwdgjma1#

您的代码中存在以下几个问题:
1.您在每次循环迭代中创建一个新的图形对象(包含子图网格),因此不同迭代的图形将在不同的图形中结束。将plt.subplots命令移到循环之前。
1.为了在每次循环迭代中绘制到不同行的轴上,需要一个从零开始(即索引第一行)并在每次迭代中递增的轴索引。
通过这些更改,您的代码变为:

l=150
m=300
i = 75
j = 175

fig,axs = plt.subplots(ncols=3, nrows=3,figsize=(20,20))
ax_idx = 0

while i and j < 700 and l and m < 800 :
    # Select axis based on the axis index
    Data.zusi[i:j,75:175].plot.contourf(ax=axs[ax_idx,0])
    print(i,j)
    # plt.show()
    Data.zusi[l:m,250:400].plot.contourf(ax=axs[ax_idx,1])
    #  plt.show()
    Data.zusi[l:m,450:600].plot.contourf(ax=axs[ax_idx,2])
    # plt.show()
    i += 200
    j += 200
    l += 200
    m += 200
    # Increase the axis index
    ax_idx += 1
    print(i,j)

注意,你也可以通过使用for循环来简化你的代码,我也强烈推荐使用xarray的基于标签的索引功能,在这个例子中是isel,这使得代码有点冗长,但是更容易理解。

n_rows = 3
fig,axs = plt.subplots(ncols=3, nrows=n_rows, figsize=(20,20))
ax_idx = 0

for ax_idx in range(n_rows):
    # Compute the index values
    l = 150 + ax_idx * 200
    m = 300 + ax_idx * 200
    i = 75 + ax_idx * 200
    j = 175 + ax_idx * 200
    # Index array based on named dimensions and plot it
    Data.zusi.isel(x=slice(i, j), y=slice(75, 175)).plot.contourf(ax=axs[ax_idx, 0])
    Data.zusi.isel(x=slice(l, m), y=slice(250, 400)).plot.contourf(ax=axs[ax_idx, 1])
    Data.zusi.isel(x=slice(l, m), y=slice(450, 600)).plot.contourf(ax=axs[ax_idx, 2])
    print(i,j)

相关问题