user2100039
user2100039

Reputation: 1356

Create Subplots in For Loop Matplotlib

i'm trying to make a 3,2 subplot using matplotlib and I'm not understanding how to do this after reading the documentation as it applies to my code as follows:

import pandas as pd
from sys import exit
import numpy as np
import matplotlib.pyplot as plt
import datetime
import xarray as xr
import cartopy.crs as ccrs
import calendar

list = [0,1,2,3,4,5]
now = datetime.datetime.now()
currm = now.month
import calendar
fig, axes = plt.subplots(nrows=3,ncols=2)
fig.subplots_adjust(hspace=0.5)
fig.suptitle('Teleconnection Pos+ Phases {} 2020'.format(calendar.month_name[currm-1]))
#for x in list: 
#for ax, x in zip(axs.ravel(), list):
for x, ax in enumerate(axes.flatten()):
        dam = DS.where(DS['time.year']==rmax.iloc[x,1]).groupby('time.month').mean()#iterate by index 
of column "1" or the years
        dam = dam.sel(month=3)#current month mean 500
        dam = dam.sel(level=500)
        damc = dam.to_array()
        lats = damc['lat'].data
        lons = damc['lon'].data
#plot data
        ax = plt.axes(projection=ccrs.PlateCarree())
        ax.coastlines(lw=1)
        damc = damc.squeeze()
        ax.contour(lons,lats,damc,cmap='jet')
        ax.set_title(tindices[x])
        plt.show()
#plt.clf()

I've tried multiple options some of which are above in the comments and I cannot get the subplots to show in the 3,2 subplot i'm expecting. I only get single plots. I've included the first plot in the for loop below as you can see it's not plotted inside the 3,2 subplot region:

[![enter image description here][1]][1]

The row with "ax.contour" may be the problem but i'm not sure. Thank you very much and here below is my target subplot region:

[![enter image description here][1]][1]

Upvotes: 1

Views: 2121

Answers (1)

Parfait
Parfait

Reputation: 107587

Without a reproducible sample data, below cannot be tested. However, your loop assigns a new ax and does not use the ax being iterating on. Additionally, plt.show() is placed within the loop. Consider below adjustment

for x, ax in enumerate(axes.flatten()):
    ...
    ax = plt.axes(projection=ccrs.PlateCarree())
    ...
    plt.show()

Consider placing projection in the plt.subplots and then index axes within loop:

fig, axes = plt.subplots(nrows=3, ncols=2, subplot_kw={'projection': ccrs.PlateCarree()})
fig.subplots_adjust(hspace=0.5)
fig.suptitle('Teleconnection Pos+ Phases {} 2020'.format(calendar.month_name[currm-1]))

axes = axes.flatten()

for x, ax in enumerate(axes):
        dam = DS.where(DS['time.year']==rmax.iloc[x,1]).groupby('time.month').mean()

        dam = dam.sel(month=3)#current month mean 500
        dam = dam.sel(level=500)
        damc = dam.to_array()
        lats = damc['lat'].data
        lons = damc['lon'].data

        axes[x].coastlines(lw=1)
        damc = damc.squeeze()
        axes[x].contour(lons, lats, damc, cmap='jet')
        axes[x].set_title(tindices[x])

plt.show() 
plt.clf()

Upvotes: 2

Related Questions