Krishna Santos
Krishna Santos

Reputation: 85

Generating a plot for all the time steps of netcdf file into a map

I was wondering if it's possible to plot all the steps from this single netcdf file into a separate plots.

Step 113 means that the current accessed data is for the date of October 22,2019. The Step 0 is July 1,2019. There are 135 time steps overall. Which means I need to produce 135 maps for each and single day.

#x,y,u,v for the maps
X=Data.longitude; Y=Data.latitude;
U=Data.u10[113]; V=Data.v10[113];
pm2p5=Data.pm2p5[113];

This is my code so far.

import xarray as xr
import cartopy.crs as ccrs
from cartopy import feature as cf
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm


Data=xr.open_dataset('PMs ECMWF2.nc')

#x,y,u,v for the maps
X=Data.longitude; Y=Data.latitude;
U=Data.u10[113]; V=Data.v10[113];
pm2p5=Data.pm2p5[113];


nlon, nlat = np.meshgrid(X,Y)


fig, ax = plt.subplots(figsize=(12, 12), dpi=300)

# Add Plotting the plot
ax=plt.subplot(111,projection=ccrs.PlateCarree())

# Add Plot features
ax.add_feature(cf.BORDERS, linewidth=.5, edgecolor="yellow")
ax.coastlines('50m', linewidth=0.8)
ax.add_feature(cf.LAKES)
ax.add_feature(cf.OCEAN)
ax.add_feature(cf.BORDERS, edgecolor="yellow")
ax.add_feature(cf.COASTLINE, edgecolor="yellow")
ax.add_feature(cf.RIVERS)
ax.gridlines()

#changing the location of the map
ax.set_extent([90, 141, 24, -10])

# Add gridlines, and set their font size
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
                  linewidth=1, color='black', alpha=0.05, linestyle='-')
gl.top_labels = False
gl.left_labels = True
gl.right_labels = False
gl.xlines = True
gl.ylines = True

#colorbar
cmap = cm.get_cmap('jet') # Colour map coolwarm,hsv,bwr, seismic

# plotting the variables
pm2p5.plot(transform=ccrs.PlateCarree(), cbar_kwargs={'shrink': 0.5}, cmap=cmap)
plt.contour(nlon, nlat, pm2p5, fontsize=10,cmap=cmap) #plotting the contours


#plotting the quiver
ax.quiver(X[::3],Y[::3],U[::3,::3],V[::3,::3], color='white')


#plot title 
#plt.title('Carbon Monoxide on October 22, 2019')

plt.show()

As of right now this code only produce one image. I have to do this over and over again. enter image description here

Upvotes: 2

Views: 1940

Answers (1)

msi_gerva
msi_gerva

Reputation: 2078

One example of making a loop over time variable and maps of variable inside the loop, is here:

#!/usr/bin/env ipython
# ---------------------------
import numpy as np
from netCDF4 import Dataset,num2date
# ---------------------------
# let us generate data, preferably to the netcdf:
nx=50;ny=50;ntime=10;
A=np.random.random((ntime,ny,nx));
lon = np.linspace(0,360,nx);
lat = np.linspace(-90,90,ny);
time = np.linspace(0,366,ntime);timeunit = 'days since 2020-01-01 00:00:00'
fout = 'test.nc'
with Dataset(fout,'w') as f:
    f.createDimension('longitude',nx);
    f.createDimension('latitude',ny);
    f.createDimension('time',);
    xv = f.createVariable('longitude','float32',('longitude'));xv[:]=lon
    yv = f.createVariable('latitude','float32',('latitude'));yv[:]=lat;
    tv = f.createVariable('time','float32',('time'));tv[:]=time;tv.setncattr('units',timeunit);
    u10 = f.createVariable('u10','float32',('time','latitude','longitude'));u10[:]=A;
    v10 = f.createVariable('v10','float32',('time','latitude','longitude'));v10[:]=-A;
    pm2 = f.createVariable('pm2p5','float32',('time','latitude','longitude'));pm2[:]=A;
    
# -----------------------------------------------
# let us now make some maps:
import xarray as xr
import cartopy.crs as ccrs
from cartopy import feature as cf
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm


Data=xr.open_dataset(fout)

#x,y,u,v for the maps
X=Data.longitude; Y=Data.latitude;

time = Data.time;

for itime in range(len(time)):
    U=Data.u10[itime]; V=Data.v10[itime];
    pm2p5=Data.pm2p5[itime];

    nlon, nlat = np.meshgrid(X,Y)


    fig, ax = plt.subplots(figsize=(12, 12), dpi=300)

    # Add Plotting the plot
    ax=plt.subplot(111,projection=ccrs.PlateCarree())

    # Add Plot features
    ax.add_feature(cf.BORDERS, linewidth=.5, edgecolor="yellow")
    ax.coastlines('50m', linewidth=0.8)
    ax.add_feature(cf.LAKES)
    ax.add_feature(cf.OCEAN)
    ax.add_feature(cf.BORDERS, edgecolor="yellow")
    ax.add_feature(cf.COASTLINE, edgecolor="yellow")
    ax.add_feature(cf.RIVERS)
    ax.gridlines()

    #changing the location of the map
    ax.set_extent([90, 141, 24, -10])

    # Add gridlines, and set their font size
    gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
                  linewidth=1, color='black', alpha=0.05, linestyle='-')
    gl.top_labels = False
    gl.left_labels = True
    gl.right_labels = False
    gl.xlines = True
    gl.ylines = True

    #colorbar
    cmap = cm.get_cmap('jet') # Colour map coolwarm,hsv,bwr, seismic

    # plotting the variables
    pm2p5.plot(transform=ccrs.PlateCarree(), cbar_kwargs={'shrink': 0.5}, cmap=cmap)
    plt.contour(nlon, nlat, pm2p5, fontsize=10,cmap=cmap) #plotting the contours


    #plotting the quiver
    ax.quiver(X[::3],Y[::3],U[::3,::3],V[::3,::3], color='white')


   #plot title 
   #plt.title('Carbon Monoxide on October 22, 2019')
    plt.savefig('fig_'+str(itime).rjust(3,'0')+'.png',bbox_inches='tight');
    plt.show();
    # ----------------------------

I first generated a netCDF with random values and then plotted the variables for each time moment.

Upvotes: 2

Related Questions