python循环子块

2024-06-16 11:09:03 发布

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

我试图使用for lop来填充子批次,但我不能这样做。以下是我的代码摘要: 编辑1:

for idx in range(8):
  img = f[img_set[ind[idx]][0]]
  patch = img[:,col1+1:col2, row1+1:row2]
  if idx < 3:
        axarr[0,idx] = plt.imshow(patch)
    elif idx <6:
        axarr[1,idx-3] = plt.imshow(patch)
    else:
        axarr[2,idx-6] = plt.imshow(patch)
path_ = 'plots/test' + str(k) + '.pdf'
fig.savefig(path_)

它只在第三行和第三列打印图像,其余部分为空白。我怎样才能改变?


Tags: path代码in编辑imgforrangeplt
1条回答
网友
1楼 · 发布于 2024-06-16 11:09:03

你忘记创建子图了。您可以使用add_subplot()http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.add_subplot)。例如

import matplotlib.pyplot as plt

fig = plt.figure()

for idx in xrange(9):
    ax = fig.add_subplot(3, 3, idx+1) # this line adds sub-axes
    ...
    ax.imshow(patch) # this line creates the image using the pre-defined sub axes

fig.savefig('test.png')

在你的例子中,可能是这样的:

import matplotlib.pyplot as plt

fig = plt.figure()

for idx in xrange(8):
    ax = fig.add_subplot(3, 3, idx+1)
    img = f[img_set[ind[idx]][0]]
    patch = img[:,col1+1:col2, row1+1:row2]
    ax.imshow(patch)

path_ = 'plots/test' + str(k) + '.pdf'        
fig.savefig(path_)

相关问题 更多 >