Python: subplot within a loop: first panel appears in wrong position Python: subplot within a loop: first panel appears in wrong position python python

Python: subplot within a loop: first panel appears in wrong position


Using your code with some random data, this would work:

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

The layout is off course a bit messy, but that's because of your current settings (the figsize, wspace etc).

enter image description here


The problem is the indexing subplot is using. Subplots are counted starting with 1!Your code thus needs to read

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

Note the change in the line where you calculate temp


Basically the same solution as provided by Rutger Kassies, but using a more pythonic syntax:

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