user1871528
user1871528

Reputation: 1785

python subplot for loop

I'm trying to use a for lop to populate a subplot but I can't do so. here is a summary of my code: Edit 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_)

It only plots an image on the 3rd row and 3rd column the rest of the plot is blank. How can I change that?

Upvotes: 2

Views: 10044

Answers (1)

Julien Spronck
Julien Spronck

Reputation: 15433

You forgot to create the sub plots. You can use add_subplot() (http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.add_subplot). For example,

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

In your example, it could be something like:

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

Upvotes: 2

Related Questions