1

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]
user2100039
  • 1,280
  • 2
  • 16
  • 31
  • 1
    Please include all `import` lines at top of code and ideally sample data for [reproducible example](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples). Also, your description of issue is not quite clear. If six plots render on one column, what is the issue? – Parfait Apr 10 '20 at 20:24
  • Sorry, my code is quite long so my focus is on the for loop and i've added a few lines at the top now. I've edited the question to drive home the point that I'm not getting subplots at all - i just get 6 plots total, generated one at a time in the loop. Hope this is more clear. Thank you – user2100039 Apr 10 '20 at 20:39

1 Answers1

2

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()
Parfait
  • 104,375
  • 17
  • 94
  • 125
  • Thanks for this - i get the 3,2 subplot grid in blank rectangles right away but this error immediately in the first loop iteration: AttributeError: 'numpy.ndarray' object has no attribute 'coastlines' – user2100039 Apr 10 '20 at 21:23
  • Try replacing all `axes[x]` with `ax` in loop. – Parfait Apr 10 '20 at 21:31
  • i had to change this first line to this for the projection--> fig, axes = plt.subplots(nrows=3,ncols=2,subplot_kw={'projection': ccrs.PlateCarree()})....it's working or attempting but i just have the 1st plot in the upper left or position 1,1 and all the other spaces are completely empty/white. There are no errors as it completes. i replaced the axes[x] as you suggstd in the loop. – user2100039 Apr 10 '20 at 21:48
  • See update. We need to `flatten` *axes* before not during loop. – Parfait Apr 10 '20 at 22:25
  • it works! moving the plt.show() and plt.clf() outside the loop did the trick- thank you!! – user2100039 Apr 10 '20 at 23:17