Search code examples
pythonloopsfor-loopsubplot

Subplots within for loops


I want to put four file plots into 1 subplot figure from a loop.

I've looped some files (four data files) to extract certain data from it (e.g. latitude, longitude and aerosol optical depth), which is correctly printed, suggesting it has successfully looped over the files and extracted what I need. When I continue the loop and just plot the results, it plots four individual figures as I haven't done subplot.

When I implement some subplot code, it does a lot of things but not what I want. I want 1 subplot figure with 2 rows and 2 columns showing each file, not 4 subplot figures repeating just that 1 file for each subplot.

This is my condensed code:

for lim in mlims:
   fil= ilfil + innm +'kd00' + jad +'nam'
   ln= Dataset(ilfil)
   longit = vn.variables['longitude'][:]
   latitud = vn.variables['latitude'][:] 
   ## etc .....
   aode       = var1+var2
   aod=np.squeeze(aode[:,2,:,:])

   lons, lats = np.meshgrid(lonitud, latatit)
   x, y = map(lons, lats)

   ii=[0,1,2,3]
   fig, axes = plt.subplots(nrows=4, ncols=4, figsize=(2,5))
   for ax,mon_index,lname in zip(axes.flatten(),ii, mnames):


       axis=np.arange(0+0.025,0.5+0.025,0.025)

       cs = ax.contourf(x,y,aod,axis,cmap='seismic',linewidths=1.)
       cbar = map.colorbar(cs)

       plt.title(AOD)

plt.show()

The code outputs this: 1 is a plot of the file but I don't want the same file to repeat in one subplot figure, and 2+ is a plot

I want it to output:

1 1 1 2 - for the first file

1 1 1 3 - second file

1 1 1 4 - third

1 1 1 5

What I'm trying to get is just: 2 3 4 5


Solution

  • Make the figure and subplots first; iterate over the files and axes; plot the data from the file on the current axes. Here is a toy example that shows the process.

    files = [range(3),range(4),range(5),range(6)]
    fig, axarr = plt.subplots(2,2)
    for data, ax in zip(files, axarr.flat):
        # if you are looping over filenames
        # process/extract the data from the file here
        ax.plot(data)
    

    subplots demo from Matplotlib docs

    .subplots() returns a Figure and an array of subplot Axes.

    >>> axarr
    array([[<matplotlib.axes._subplots.AxesSubplot object at 0x000000000D2BA358>,
            <matplotlib.axes._subplots.AxesSubplot object at 0x000000000F3F29B0>],
           [<matplotlib.axes._subplots.AxesSubplot object at 0x000000000F429080>,
            <matplotlib.axes._subplots.AxesSubplot object at 0x000000000F44F710>]],
          dtype=object)
    

    Instead of iterating over the Axes' in sequence you can choose them by indexing into(?) the array.

    >>> axarr[0,1]
    
    <matplotlib.axes._subplots.AxesSubplot object at 0x000000000F3F29B0>
    >>>
    

    pyplot has a concept of current axes. Calling the .subplot() method will make an axes current then subsequent statements will act on that axes. This is another way to operate on individual subplots out of sequence.

    plt.subplot(rows,cols,1)
    plt.plot(range(10),'r')
    plt.subplot(rows,cols,3)
    plt.plot(range(100),'b')
    plt.subplot(rows,cols,2)
    plt.plot(range(5),'o')
    plt.subplot(rows,cols,4)
    plt.plot(range(5),'g')