yvard yvard - 4 months ago 23
Python Question

python: Plotting data from multiple netCDF files

long story short, I am plotting climate data from a netCDF file. My only problem, I have to plot data from tens of these files, each having over a hundred data points. Luckily, they are all identically formatted, and their names are in rising order (for example: file1.nc, file2.nc...). This is my code (unfinished as I have to change the markers and colors of the markers):

import numpy as np
from scipy.io import netcdf_file
import math
import matplotlib.pyplot as plt
from scipy.stats.stats import nanmean
from mpl_toolkits.basemap import Basemap
from mpl_toolkits.axes_grid1 import make_axes_locatable
# OPEN FILES
fname = '/Users/epsuser/Dropbox/Argo/Data/20160701_prof.nc'
ncfile = netcdf_file(fname,'r');
# READ DATA
temp = np.array(ncfile.variables['TEMP'][:])
lon = np.array(ncfile.variables['LONGITUDE'][:])
lat = np.array(ncfile.variables['LATITUDE'][:])
# SET UP MAP
map = Basemap(projection='robin',lon_0=0,resolution='l')
map.drawcoastlines(linewidth=0.25)
map.drawcountries(linewidth=0.25)
map.fillcontinents(color='coral',lake_color='grey')
map.drawmapboundary(fill_color='grey')
map.drawmeridians(np.arange(0,360,60),labels=[True,False,False,True],fontsize=8)
map.drawparallels(np.arange(-90,90,30),labels=[True,False,False,True],fontsize=8)
# COORDINATES
LON, LAT = np.meshgrid(lon,lat)
x, y = map(LON,LAT)
# SET UP DATA
data = temp[...,0]
#print(data)
# GRAPH
cs = map.scatter(x,y,data)
# COLORING BY TEMPERATURE
# EXECUTE
plt.plot()
plt.show(block=False)


Anyways, I want to plot more than that one file (about 20 to begin with). Is there a way to do that? Also, if you guys have an idea how how to set up the colorbar based on variable 'data' that would be great.

Thanks!

Answer

at the least, plt.savefig("some unique name") means you can generate them in a loop without having to save the plots/close them individually.

I also suggest getting comfortable with the object oriented interface:

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
map = Basemap(projection='robin',lon_0=0,resolution='l',ax=ax)
#keep all your code
cs = map.scatter(x,y,data)
fig.savefig("{}".format(some unique identifier))

Eta: And you can find all the files using glob if they're in the same folder:

import glob
filelist = glob.glob('/Users/epsuser/Dropbox/Argo/Data/*.nc')
for fl in filelist:
    ncfile = netcdf_file(fname,'r')
    #the rest of your reading code
    fig = plt.figure()
    #etc...
Comments