Python:循环中的子块:第一个面板出现在错误的位置

2024-05-16 20:57:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python还不太熟悉,从一个更类似于Matlab的角度来看。 我正在尝试制作一系列的2 x 5面板轮廓子批次。到目前为止我的方法 已经将我的Matlab代码(在一定程度上)转换为Python,并在循环中绘制我的子块。代码的相关部分如下所示:

fig=plt.figure(figsize=(15, 6),facecolor='w', edgecolor='k')
for i in range(10):

    #this part is just arranging the data for contourf 
    ind2 = py.find(zz==i+1)
    sfr_mass_mat = np.reshape(sfr_mass[ind2],(pixmax_x,pixmax_y))
    sfr_mass_sub = sfr_mass[ind2]
    zi = griddata(massloclist, sfrloclist, sfr_mass_sub,xi,yi,interp='nn')


    temp = 250+i  # this is to index the position of the subplot
    ax=plt.subplot(temp)
    ax.contourf(xi,yi,zi,5,cmap=plt.cm.Oranges)
    plt.subplots_adjust(hspace = .5,wspace=.001)

    #just annotating where each contour plot is being placed
    ax.set_title(str(temp))

作为一个新手,这个论坛,我似乎不允许附上结果图像。然而,根据我在代码中的索引“temp”,2 x 5面板的最终布局是:

251 - 252 - 253 - 254 - 255
256 - 257 - 258 - 259 - 250

但是,我想要的是

250 - 251 - 252 - 253 - 254
255 - 256 - 257 - 258 - 259 

也就是说,第一个面板(250)出现在我认为应该是259的最后一个位置。251似乎是我想要250的位置。它们似乎都在正确的顺序,只是循环移动了一个。

我知道这会是件很愚蠢的事,但感谢你能给我任何帮助。

提前谢谢你。


Tags: the代码面板forispltaxthis
3条回答

将代码与一些随机数据一起使用,这将起作用:

fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)

axs = axs.ravel()

for i in range(10):

    axs[i].contourf(np.random.rand(10,10),5,cmap=plt.cm.Oranges)
    axs[i].set_title(str(250+i))

布局有点混乱,但这是因为您当前的设置(figsize、wspace等)。

enter image description here

问题是索引subplot正在使用。从1开始计算子块! 因此,您的代码需要阅读

fig=plt.figure(figsize=(15, 6),facecolor='w', edgecolor='k')
for i in range(10):

    #this part is just arranging the data for contourf 
    ind2 = py.find(zz==i+1)
    sfr_mass_mat = np.reshape(sfr_mass[ind2],(pixmax_x,pixmax_y))
    sfr_mass_sub = sfr_mass[ind2]
    zi = griddata(massloclist, sfrloclist, sfr_mass_sub,xi,yi,interp='nn')


    temp = 251+i  # this is to index the position of the subplot
    ax=plt.subplot(temp)
    ax.contourf(xi,yi,zi,5,cmap=plt.cm.Oranges)
    plt.subplots_adjust(hspace = .5,wspace=.001)

    #just annotating where each contour plot is being placed
    ax.set_title(str(temp))

注意计算temp的行中的变化

基本上与Rutger Kassies提供的解决方案相同,但使用了更为python的语法:

fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)

data = np.arange(250, 260)

for ax, d in zip(axs.ravel(), data):
    ax.contourf(np.random.rand(10,10), 5, cmap=plt.cm.Oranges)
    ax.set_title(str(d))

相关问题 更多 >