Search code examples
pythonmatplotlibcartopy

Looping a script to produce multiple images


I have a Netcdf dataset with dimensions [time, height, latitude, longitude] that I've opened with xarray. I've written a code that projects the all the data for a specific timestamp onto a cartopy map and saves the image to my directory. I'd like to create an image for each timestamp, but at the moment the only way I know how to do it is to manually change the timestamp entry and run the code again. Since there are 360 timestamps this would obviously take some time. I know Python is handy for loops, but I'm very unfamiliar with them, so is there a way of embedding this code within a loop so that I can save multiple images in one go?

pv=data1.pv*10000
pv850=pv[:,0,:,:]
lons=pv850.longitude
lats=pv850.latitude

Fig = plt.figure(figsize=[10,8])
ax = plt.axes(projection=ccrs.NorthPolarStereo())
normi = mpl.Normalize(vmin=-1.5, vmax=12)
cs = ax.contourf(lons, lats, pv850[0,:,:], 50, 
                 transform=ccrs.RotatedPole(), extend='both',
                 cmap='jet')
plt.colorbar(cs)
ax.coastlines()
ax.gridlines(crs=ccrs.Geodetic(), linestyle='--')

theta = np.linspace(0, 2*np.pi, 100)
center, radius = [0.5, 0.5], 0.5
verts = np.vstack([np.sin(theta), np.cos(theta)]).T
circle = mpath.Path(verts * radius + center)
ax.set_boundary(circle, transform=ax.transAxes)

plt.title('Polar Plot 01-01-2018 00:00')
plt.savefig('image1.png')

The line ax.contourf(lons, lats, pv850[0,:,:] controls the timestamp, where '0' corresponds to the timestamp entry (ranging from 0-359). I'd also like to have the timestamp in the title change with each plot if possible. Finally, here's a picture of the final plot.

enter image description here


Solution

  • It seems straightforward to put this in a loop so I am not sure why this is so difficult. Nevertheless, you can try the following. Here I have moved some definitions outside the for loop because you don't need to define them 360 times again and again.

    theta = np.linspace(0, 2*np.pi, 100)
    center, radius = [0.5, 0.5], 0.5
    verts = np.vstack([np.sin(theta), np.cos(theta)]).T
    circle = mpath.Path(verts * radius + center)
    
    for i in range(360):
        Fig = plt.figure(figsize=[10,8])
        ax = plt.axes(projection=ccrs.NorthPolarStereo())
        normi = mpl.Normalize(vmin=-1.5, vmax=12)
        cs = ax.contourf(lons, lats, pv850[i,:,:], 50, 
                         transform=ccrs.RotatedPole(), extend='both',
                         cmap='jet')
        plt.colorbar(cs)
        ax.coastlines()
        ax.gridlines(crs=ccrs.Geodetic(), linestyle='--')
        ax.set_boundary(circle, transform=ax.transAxes)
    
        plt.title('Polar Plot 01-01-2018 00:{:02d}'.format(i))
        plt.savefig('image%s.png' %i)