我如何使用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循环,但它也产生了相同的结果。
1条答案
按热度按时间pbwdgjma1#
您的代码中存在以下几个问题:
1.您在每次循环迭代中创建一个新的图形对象(包含子图网格),因此不同迭代的图形将在不同的图形中结束。将
plt.subplots
命令移到循环之前。1.为了在每次循环迭代中绘制到不同行的轴上,需要一个从零开始(即索引第一行)并在每次迭代中递增的轴索引。
通过这些更改,您的代码变为:
注意,你也可以通过使用for循环来简化你的代码,我也强烈推荐使用
xarray
的基于标签的索引功能,在这个例子中是isel
,这使得代码有点冗长,但是更容易理解。