def plot_section(file_handle, record, xq, j=0, variable='salt',eta='e',clim=(33.8,34.55), plot_grid=True, rep='pcm', xlim=(320,800), ylim=(-720,0), cmap=plt.cm.jet, ax=None, show_stats=True): """Plots a section of by reading vertical grid and scalar variable and super-sampling both in order to plot vertical and horizontal reconstructions. Optional arguments have defaults for plotting salinity and overlaying the grid. """ e = file_handle.variables[eta][record,:,j,:] # Vertical grid positions s = file_handle.variables[variable][record,:,j,:] # Scalar field to color if variable == 'u': # we need u at h pts s = 0.5 * (s[:,0:-1]+s[:,1::]) x,z,q = m6toolbox.section2quadmesh(xq, e, s, representation=rep) # This yields three areas at twice the model resolution if ax is None: fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8,6)) cs = ax.pcolormesh(x, z, q, cmap=cmap, vmin=clim[0], vmax=clim[1]); cb =plt.colorbar(cs,ax=ax) if plot_grid: ax.plot(x, z.T, 'k'); ax.set_ylim(ylim) ax.set_xlim(xlim) if show_stats > 0: sMin = s.min(); sMax = s.max() ax.annotate('max=%.5g\nmin=%.5g'%(sMax,sMin), xy=(0.0,1.01), xycoords='axes fraction', verticalalignment='bottom', fontsize=10)
def plot_section(file_handle, record, variable, y=358, vmin=None, vmax=None, plot_grid=True, rep='linear'): """Plots a section of by reading vertical grid and scalar variable and super-sampling both in order to plot vertical and horizontal reconstructions. Optional arguments have defaults for plotting salinity and overlaying the grid. """ e = file_handle.variables['e'][record, :, 426, 370:391] # Vertical grid positions s = file_handle.variables[variable][record, :, y, 370:391] # Scalar field to color x, z, q = m6toolbox.section2quadmesh( xq[426, 369:391], e, s, representation=rep ) # This yields three areas at twice the model resolution cs = plt.pcolormesh(x, z, q, vmin=vmin, vmax=vmax, cmap=cmap) if plot_grid: plt.plot(x, z.T, 'k') # if plot_grid: plt.plot(x, z.T, 'k', hold=True); # plt.ylim(-700,1) plt.ylim(-60, 3) cbar = plt.colorbar(cs, orientation='horizontal') cbar.ax.tick_params(labelsize=15)
def plot_section(file_handle, xq, ax, data1, data2, im=250, eta='e', yvar='yh', rep='pcm', xlim=(0, 650), ylim=(-2000, 0), cmap=plt.cm.bwr, hidex=False, hidey=False, m1=-2, m2=2): """Plots a section of by reading vertical grid and scalar variable and super-sampling both in order to plot vertical and horizontal reconstructions. Optional arguments have defaults for plotting salinity and overlaying the grid. """ font = { 'family': 'serif', 'color': 'darkred', 'weight': 'normal', 'size': 18, } e = file_handle.variables[eta][-24::, :, :, im].mean(axis=0) # Vertical grid positions y = file_handle.variables[yvar][:] x, z, q = m6toolbox.section2quadmesh( xq, e, data1, representation=rep ) # This yields three areas at twice the model resolution #cs = ax.pcolormesh(x, z, q,norm=LogNorm(vmin=1, vmax=110), cmap=cmap) cs = ax.pcolormesh(x, z, q, vmin=m1, vmax=m2, cmap=cmap) if (len(data2.shape) > 1): z = 0.5 * (e[0:-1, :] + e[1:, :]) [Y, TMP] = np.meshgrid(y, z[:, 0]) s = ax.contour(Y, z, data2 - 1000, [37.12], colors='gray', lw=10) ax.clabel(s, inline=1, fontsize=16, fmt='%4.2f', manual=[(500, -500)]) else: print 'This wont be plotted' #ax.plot(y,data2,'gray',lw=2); ax.set_ylim(ylim) ax.set_xlim(xlim) if not hidex: #ax.axes.get_xaxis().set_ticks([]) ax.set_xlabel('y [km]') if not hidey: #ax.axes.get_yaxis().set_ticks([]) ax.set_ylabel('Depth [m]') return cs
def plot_section(file_handle, record, xq, i=0, variable='salt',eta='e',clim=(33.8,34.55), plot_grid=True, rep='pcm', xlim=(320,800), ylim=(-720,0), cmap=plt.cm.jet): """Plots a section of by reading vertical grid and scalar variable and super-sampling both in order to plot vertical and horizontal reconstructions. Optional arguments have defaults for plotting salinity and overlaying the grid. """ e = file_handle.variables[eta][record,:,:,i] # Vertical grid positions s = file_handle.variables[variable][record,:,:,i] # Scalar field to color x,z,q = m6toolbox.section2quadmesh(xq, e, s, representation=rep) # This yields three areas at twice the model resolution plt.pcolormesh(x, z, q, cmap=cmap); plt.colorbar() plt.clim(clim) if plot_grid: plt.plot(x, z.T, 'k', hold=True); plt.ylim(ylim) plt.xlim(xlim)
def plot_section(file_handle, record, xq, ax, i=250, variable='temp',eta='e',yvar='yh',clim=(0,30), plot_grid=True, rep='pcm', xlim=(0,1000), ylim=(-4000,0), cmap=plt.cm.jet, hide_ticks=False, cb=False): """Plots a section of by reading vertical grid and scalar variable and super-sampling both in order to plot vertical and horizontal reconstructions. Optional arguments have defaults for plotting salinity and overlaying the grid. """ font = {'family': 'serif', 'color': 'darkred', 'weight': 'normal', 'size': 16, } import matplotlib matplotlib.rcParams.update({'font.size': 16}) e = file_handle.variables[eta][record,:,:,i] # Vertical grid positions s = file_handle.variables[variable][record,:,:,i] # Scalar field to color y = file_handle.variables[yvar][:] x = file_handle.variables['xh'][:] x,z,q = m6toolbox.section2quadmesh(xq, e, s, representation=rep) # This yields three areas at twice the model resolution cs = ax.pcolormesh(x, z, q,norm=LogNorm(vmin=1, vmax=110), cmap=cmap) if cb: cbar=plt.colorbar(cs,orientation='horizontal') cbar.ax.set_xlabel(r'$\Delta z$ [m]') ##cs.set_clim(clim) [Y,TMP] = np.meshgrid(y,e[:,0]) print e.shape, Y.shape if plot_grid: #ax.plot(Y.T, e.T, 'k', lw=0.5, hold=True) ax.plot(Y.T, e.T, 'k', lw=0.5) ax.plot(y,e[0,:],'k',lw=1); plt.plot(y,e[-1,:],'k',lw=1); if variable == 'v': ax.text(5,-500, r'max$(|v|)$:'+str(np.max(np.abs(s))), fontdict=font) ax.set_ylim(ylim) ax.set_xlim(xlim) if hide_ticks: ax.axes.get_xaxis().set_ticks([]) ax.axes.get_yaxis().set_ticks([]) return #cs
def render(var, args, elevation=None, frame=0): var.getData() # Actually read data from file # Optionally mask out a specific value if args.ignore: var.data = np.ma.masked_array(var.data, mask=[var.data == args.ignore]) if args.ignorelt: var.data = np.ma.masked_array(var.data, mask=[var.data <= args.ignorelt]) if args.ignoregt: var.data = np.ma.masked_array(var.data, mask=[var.data >= args.ignoregt]) if args.scale: var.data = args.scale * var.data if args.list: print('createUI: Data =\n', var.data) if args.stats: dMin = np.min(var.data) dMax = np.max(var.data) if dMin == 0 and dMax > 0: dMin = np.min(var.data[var.data != 0]) print('Mininum=', dMin, '(ignoring zeros) Maximum=', dMax) elif dMax == 0 and dMin < 0: dMax = np.max(var.data[var.data != 0]) print('Mininum=', dMin, 'Maximum=', dMax, '(ignoring zeros)') else: print('Mininum=', dMin, 'Maximum=', dMax) if args.offset: var.data = var.data + args.offset if args.log10: var.data = np.ma.log10(var.data) # Now plot if var.rank == 0: for d in var.allDims: print('%s = %g %s' % (d.name, d.values[0], d.units)) print(var.vname + ' = ', var.data, ' ' + var.units) exit(0) elif var.rank == 1: # Line plot if var.dims[0].isZaxis: # Transpose 1d plot xCoord = var.data yData = var.dims[0].values plt.plot(xCoord, yData) plt.xlabel(var.label) plt.ylabel(var.dims[0].label) if var.dims[0].values[0] > var.dims[0].values[-1]: plt.gca().invert_yaxis() if var.dims[0].positiveDown: plt.gca().invert_yaxis() else: # Normal 1d plot xCoord = var.dims[0].values yData = var.data plt.plot(xCoord, yData) plt.xlabel(var.dims[0].label) plt.xlim(var.dims[0].limits[0], var.dims[0].limits[-1]) plt.ylabel(var.label) elif var.rank == 2: # Pseudo color plot # Add an extra element to coordinate to force pcolormesh to draw all cells if var.dims[1].isZaxis: # Happens for S(t,z) xCoord = extrapCoord(var.dims[0].values) yCoord = extrapCoord(var.dims[1].values) zData = np.transpose(var.data) xLabel = var.dims[0].label xLims = var.dims[0].limits yLabel = var.dims[1].label yLims = var.dims[1].limits yDim = var.dims[1] else: xLabel = var.dims[1].label xLims = var.dims[1].limits yLabel = var.dims[0].label yLims = var.dims[0].limits if args.supergrid is None: if args.oceanstatic is None: xCoord = extrapCoord(var.dims[1].values) yCoord = extrapCoord(var.dims[0].values) else: xCoord, xLims = readOSvar(args.oceanstatic, 'geolon_c', var.dims) yCoord, yLims = readOSvar(args.oceanstatic, 'geolat_c', var.dims) xLabel = 'Longitude (\u00B0E)' yLabel = 'Latitude (\u00B0N)' else: xCoord, xLims = readSGvar(args.supergrid, 'x', var.dims) yCoord, yLims = readSGvar(args.supergrid, 'y', var.dims) xLabel = 'Longitude (\u00B0E)' yLabel = 'Latitude (\u00B0N)' zData = var.data yDim = var.dims[0] if yDim.isZaxis and not elevation is None: # Z on y axis ? if elevation.refreshable: elevation.getData() #yCoord = elevation.data xCoord, yCoord, zData = m6toolbox.section2quadmesh( xCoord, elevation.data, zData, representation='pcm') yLims = (np.amin(yCoord[-1, :]), np.amax(yCoord[0, :])) #yCoord = extrapElevation( yCoord ) yLabel = 'Elevation (m)' plt.pcolormesh(xCoord, yCoord, zData) if args.coordlines: plt.plot(xCoord, yCoord.T, 'k') if yDim.isZaxis and elevation is None: # Z on y axis ? if yCoord[0] > yCoord[-1]: plt.gca().invert_yaxis() yLims = reversed(yLims) if yDim.positiveDown: plt.gca().invert_yaxis() yLims = reversed(yLims) if len(var.label) > 50: fontsize = 10 elif len(var.label) > 30: fontsize = 12 else: fontsize = 14 if args.scale: plt.title(var.label + ' x%e' % (args.scale[0]), fontsize=fontsize) else: plt.title(var.label, fontsize=fontsize) plt.xlim(xLims) plt.ylim(yLims) plt.xlabel(xLabel) plt.ylabel(yLabel) makeGuessAboutCmap(clim=args.clim, colormap=args.colormap) plt.tight_layout() plt.colorbar(fraction=.08) axis = plt.gca() if var.singleDims: text = '' for d in var.singleDims: if len(text): text = text + ' ' text = text + d.name + ' = ' + str(d.values[0]) if d.units: text = text + ' (' + d.units + ')' axis.annotate(text, xy=(0.005, .995), xycoords='figure fraction', verticalalignment='top', fontsize=8) if args.output: if args.animate: dt = time.time() - start_time nf = var.singleDims[0].initialLen print('Writing file "%s" (%i/%i)'%(args.output%(frame),frame,nf), \ 'Elapsed %.1fs, %.2f FPS, total %.1fs, remaining %.1fs'%(dt, frame/dt, 1.*nf/frame*dt, (1.*nf/frame-1.)*dt)) try: plt.savefig(args.output % (frame), pad_inches=0.) except: raise MyError( 'output filename must contain %D.Di when animating') else: plt.savefig(args.output, pad_inches=0.) elif not args.animate: # Interactive and static def keyPress(event): if event.key == 'q': exit(0) if var.rank == 1: def statusMesg(x, y): # -1 needed because of extension for pcolormesh i = min(list(range(len(xCoord) - 1)), key=lambda l: abs(xCoord[l] - x)) if not i is None: val = yData[i] if val is np.ma.masked: return 'x=%.3f %s(%i)=NaN' % (x, var.vname, i + 1) else: return 'x=%.3f %s(%i)=%g' % (x, var.vname, i + 1, val) else: return 'x=%.3f y=%.3f' % (x, y) elif var.rank == 2: def statusMesg(x, y): if len(xCoord.shape) == 1: # -2 needed because of coords are for vertices and need to be averaged to centers i = min(list(range(len(xCoord) - 2)), key=lambda l: abs( (xCoord[l] + xCoord[l + 1]) / 2. - x)) j = min(list(range(len(yCoord) - 2)), key=lambda l: abs( (yCoord[l] + yCoord[l + 1]) / 2. - y)) else: idx = np.abs( np.fabs(xCoord[0:-1, 0:-1] + xCoord[1:, 1:] + xCoord[0:-1, 1:] + xCoord[1:, 0:-1] - 4 * x) + np.fabs(yCoord[0:-1, 0:-1] + yCoord[1:, 1:] + yCoord[0:-1, 1:] + yCoord[1:, 0:-1] - 4 * y)).argmin() j, i = np.unravel_index(idx, zData.shape) if not i is None: val = zData[j, i] if val is np.ma.masked: return 'x,y=%.3f,%.3f %s(%i,%i)=NaN' % ( x, y, var.vname, i + 1, j + 1) else: return 'x,y=%.3f,%.3f %s(%i,%i)=%g' % ( x, y, var.vname, i + 1, j + 1, val) else: return 'x,y=%.3f,%.3f' % (x, y) xmin, xmax = axis.get_xlim() ymin, ymax = axis.get_ylim() def zoom(event): # Scroll wheel up/down if event.button == 'up': scaleFactor = 1 / 1.5 # deal with zoom in elif event.button == 'down': scaleFactor = 1.5 # deal with zoom out elif event.button == 2: scaleFactor = 1.0 else: return axmin, axmax = axis.get_xlim() aymin, aymax = axis.get_ylim() (axmin, axmax), (aymin, aymax) = newLims( (axmin, axmax), (aymin, aymax), (event.xdata, event.ydata), (xmin, xmax), (ymin, ymax), scaleFactor) if axmin is None: return axis.set_xlim(axmin, axmax) axis.set_ylim(aymin, aymax) plt.draw() # force re-draw plt.gcf().canvas.mpl_connect('scroll_event', zoom) def zoom2(event): zoom(event) plt.gcf().canvas.mpl_connect('button_press_event', zoom2) plt.gca().format_coord = statusMesg plt.gcf().canvas.mpl_connect('key_press_event', keyPress)
def plot_vertical_section(lon,lat,data_mean,difference_on,title,p_values,cscale,field,layer_interface,axes_direction,lat_lon_bounds,file_type,colorbar_on=True,return_data_map=False): if axes_direction=='yz': x=lat upper_bound=lat_lon_bounds[0]; lower_bound=lat_lon_bounds[1]; if axes_direction=='xz': x=lon upper_bound=lat_lon_bounds[2]; lower_bound=lat_lon_bounds[3]; if file_type=='ocean_month': representation='linear' #'pcm' #representation='pcm' M=layer_interface.shape layers=range(0,M[0]-1) q=data_mean[range(0,M[0]-1),:] ;q=q[:,range(0,len(x)-1) ] layer_interface=layer_interface[:,range(0,len(x)-1)] (X, Z, Q)=section2quadmesh(x, layer_interface, q, representation) if file_type=='ocean_month_z': X=x Z=layer_interface Q=data_mean #Plotting if difference_on==1: #cmap = plt.set_cmap('bwr') cmap = 'bwr' if cscale==None: if field=='temp': cscale=0.5 if field=='salt': cscale=0.1 if field=='u': cscale=0.005 if field=='rho': cscale=0.05 #cNorm = MidpointNormalize(vmin=-cscale, vmax=cscale,midpoint=0) cNorm = mpl.colors.Normalize(vmin=-cscale, vmax=cscale) if difference_on==0: #cmap = plt.set_cmap('jet') cmap = 'jet' if field=='temp': cscale_min=-3 ; cscale_max=10 if field=='rho': cscale_min=1026 ; cscale_max=1029 if field=='salt': cscale_min=33 ; cscale_max=35 #cmap = plt.set_cmap('jet') if field=='u': cscale_min=-.05 ; cscale_max=.05 #cmap = plt.set_cmap('bwr') cmap = 'bwr' #cNorm = MidpointNormalize(vmin=cscale_min, vmax=cscale_max,midpoint=0) cNorm = mpl.colors.Normalize(vmin=cscale_min, vmax=cscale_max) #cmap = plt.set_cmap('jet') print X.shape print Z.shape print Q.shape datamap=pcolormesh(X,Z,Q,cmap=cmap,norm=cNorm,facecolor='white') #datamap=pcolormesh(X,-Z[::-1],Q[:,:],cmap=cmap,norm=cNorm,facecolor='white') #datamap=pcolormesh(X,-Z[::-1],Q[:,:],cmap=cmap,norm=cNorm,facecolor='white') #Overlaying significance Z2=Z[:-1] #if p_values!=None: if p_values is not None: #print 'plotting p_values' p_values[np.where(Q.mask)]=0.001 levels1=np.array([0.05,999.]) #levels1=np.array([0.01,0.02,0.03,0.04,0.05,999.]) cNorm2=mpl.colors.Normalize(vmin=400, vmax=1000) CS = contourf(X, Z2, p_values,levels=levels1, hatches=[' '], fill=False,cmap='Greys',norm=cNorm2 ) # hatches=['+'] also an option, hatches=['//'] #CS = contourf(X, Z2, p_values,levels=levels1, hatches=['//'], fill=False,cmap='bwr' ) # hatches=['+'] ,hatches=['///] also an option #CS = contour(X, Z2, p_values,levels=levels1,linewidth=5.,color='black' ) # hatches=['+'] also an option #datamap=pcolormesh(X,Z,p_values,cmap=cmap,norm=cNorm,facecolor='white') #CS = m.contourf(x, y, p_values,levels=levels1, fill=False,cmap='bwr' ) # hatches=['+'] also an option axis = plt.gca() landcolor=[.5,.5,.5] axis.set_axis_bgcolor(landcolor) plt.xlim( (lower_bound,upper_bound)) #plt.ylim((-1500,0) ) plt.ylim((0 ,1500)) #plt.ylim((-1500 ,1500)) axis.invert_yaxis() #plt.gca.invert_yaxis() #plt.ylim((-5000,0) ) if title!=None: plt.title(title) if colorbar_on==True: plt.colorbar() if return_data_map==True: return datamap
def render(var, args, elevation=None, frame=0): var.getData() # Actually read data from file # Optionally mask out a specific value if args.ignore: var.data = np.ma.masked_array(var.data, mask=[var.data==args.ignore]) if args.ignorelt: var.data = np.ma.masked_array(var.data, mask=[var.data<=args.ignorelt]) if args.ignoregt: var.data = np.ma.masked_array(var.data, mask=[var.data>=args.ignoregt]) if args.scale: var.data = args.scale * var.data if args.list: print('createUI: Data =\n',var.data) if args.stats: dMin = np.min(var.data); dMax = np.max(var.data) if dMin==0 and dMax>0: dMin = np.min(var.data[var.data!=0]) print('Mininum=',dMin,'(ignoring zeros) Maximum=',dMax) elif dMax==0 and dMin<0: dMax = np.max(var.data[var.data!=0]) print('Mininum=',dMin,'Maximum=',dMax,'(ignoring zeros)') else: print('Mininum=',dMin,'Maximum=',dMax) if args.offset: var.data = var.data + args.offset if args.log10: var.data = np.ma.log10(var.data) # Now plot if var.rank==0: for d in var.allDims: print('%s = %g %s'%(d.name,d.values[0],d.units)) print(var.vname+' = ',var.data,' '+var.units) exit(0) elif var.rank==1: # Line plot if var.dims[0].isZaxis: # Transpose 1d plot xCoord = var.data ; yData = var.dims[0].values plt.plot(xCoord, yData) plt.xlabel(var.label) plt.ylabel(var.dims[0].label); if var.dims[0].values[0]>var.dims[0].values[-1]: plt.gca().invert_yaxis() if var.dims[0].positiveDown: plt.gca().invert_yaxis() else: # Normal 1d plot xCoord = var.dims[0].values; yData = var.data plt.plot(xCoord, yData) plt.xlabel(var.dims[0].label); plt.xlim(var.dims[0].limits[0], var.dims[0].limits[-1]) plt.ylabel(var.label) elif var.rank==2: # Pseudo color plot # Add an extra element to coordinate to force pcolormesh to draw all cells if var.dims[1].isZaxis: # Happens for S(t,z) xCoord = extrapCoord( var.dims[0].values); yCoord = extrapCoord( var.dims[1].values) zData = np.transpose(var.data) xLabel = var.dims[0].label; xLims = var.dims[0].limits yLabel = var.dims[1].label; yLims = var.dims[1].limits yDim = var.dims[1] else: xLabel = var.dims[1].label; xLims = var.dims[1].limits yLabel = var.dims[0].label; yLims = var.dims[0].limits if args.supergrid is None: if args.oceanstatic is None: xCoord = extrapCoord( var.dims[1].values); yCoord = extrapCoord( var.dims[0].values) else: xCoord, xLims = readOSvar(args.oceanstatic, 'geolon_c', var.dims) yCoord, yLims = readOSvar(args.oceanstatic, 'geolat_c', var.dims) xLabel = 'Longitude (\u00B0E)' ; yLabel = 'Latitude (\u00B0N)' else: xCoord, xLims = readSGvar(args.supergrid, 'x', var.dims) yCoord, yLims = readSGvar(args.supergrid, 'y', var.dims) xLabel = 'Longitude (\u00B0E)' ; yLabel = 'Latitude (\u00B0N)' zData = var.data yDim = var.dims[0] if yDim.isZaxis and not elevation is None: # Z on y axis ? if elevation.refreshable: elevation.getData() #yCoord = elevation.data xCoord, yCoord, zData = m6toolbox.section2quadmesh(xCoord, elevation.data, zData, representation='pcm') yLims = (np.amin(yCoord[-1,:]), np.amax(yCoord[0,:])) #yCoord = extrapElevation( yCoord ) yLabel = 'Elevation (m)' plt.pcolormesh(xCoord,yCoord,zData) if yDim.isZaxis and elevation is None: # Z on y axis ? if yCoord[0]>yCoord[-1]: plt.gca().invert_yaxis(); yLims = reversed(yLims) if yDim.positiveDown: plt.gca().invert_yaxis(); yLims = reversed(yLims) if len(var.label)>50: fontsize=10 elif len(var.label)>30: fontsize=12 else: fontsize=14; if args.scale: plt.title(var.label+' x%e'%(args.scale[0]),fontsize=fontsize) else: plt.title(var.label,fontsize=fontsize) plt.xlim(xLims); plt.ylim(yLims) plt.xlabel(xLabel) ; plt.ylabel(yLabel) makeGuessAboutCmap(clim=args.clim, colormap=args.colormap) plt.tight_layout() plt.colorbar(fraction=.08) axis=plt.gca() if var.singleDims: text = '' for d in var.singleDims: if len(text): text = text+' ' text = text + d.name + ' = ' + str(d.values[0]) if d.units: text = text + ' (' + d.units + ')' axis.annotate(text, xy=(0.005,.995), xycoords='figure fraction', verticalalignment='top', fontsize=8) if args.output: if args.animate: dt = time.time() - start_time nf = var.singleDims[0].initialLen print('Writing file "%s" (%i/%i)'%(args.output%(frame),frame,nf), \ 'Elapsed %.1fs, %.2f FPS, total %.1fs, remaining %.1fs'%(dt, frame/dt, 1.*nf/frame*dt, (1.*nf/frame-1.)*dt)) try: plt.savefig(args.output%(frame),pad_inches=0.) except: raise MyError('output filename must contain %D.Di when animating') else: plt.savefig(args.output,pad_inches=0.) elif not args.animate: # Interactive and static def keyPress(event): if event.key=='q': exit(0) if var.rank==1: def statusMesg(x,y): # -1 needed because of extension for pcolormesh i = min(list(range(len(xCoord)-1)), key=lambda l: abs(xCoord[l]-x)) if not i is None: val = yData[i] if val is np.ma.masked: return 'x=%.3f %s(%i)=NaN'%(x,var.vname,i+1) else: return 'x=%.3f %s(%i)=%g'%(x,var.vname,i+1,val) else: return 'x=%.3f y=%.3f'%(x,y) elif var.rank==2: def statusMesg(x,y): if len(xCoord.shape)==1: # -2 needed because of coords are for vertices and need to be averaged to centers i = min(list(range(len(xCoord)-2)), key=lambda l: abs((xCoord[l]+xCoord[l+1])/2.-x)) j = min(list(range(len(yCoord)-2)), key=lambda l: abs((yCoord[l]+yCoord[l+1])/2.-y)) else: idx = np.abs( np.fabs( xCoord[0:-1,0:-1]+xCoord[1:,1:]+xCoord[0:-1,1:]+xCoord[1:,0:-1]-4*x) +np.fabs( yCoord[0:-1,0:-1]+yCoord[1:,1:]+yCoord[0:-1,1:]+yCoord[1:,0:-1]-4*y) ).argmin() j,i = np.unravel_index(idx,zData.shape) if not i is None: val = zData[j,i] if val is np.ma.masked: return 'x,y=%.3f,%.3f %s(%i,%i)=NaN'%(x,y,var.vname,i+1,j+1) else: return 'x,y=%.3f,%.3f %s(%i,%i)=%g'%(x,y,var.vname,i+1,j+1,val) else: return 'x,y=%.3f,%.3f'%(x,y) xmin,xmax=axis.get_xlim(); ymin,ymax=axis.get_ylim(); def zoom(event): # Scroll wheel up/down if event.button == 'up': scaleFactor = 1/1.5 # deal with zoom in elif event.button == 'down': scaleFactor = 1.5 # deal with zoom out elif event.button == 2: scaleFactor = 1.0 else: return axmin,axmax=axis.get_xlim(); aymin,aymax=axis.get_ylim(); (axmin,axmax),(aymin,aymax) = newLims( (axmin,axmax), (aymin,aymax), (event.xdata, event.ydata), (xmin,xmax), (ymin,ymax), scaleFactor) if axmin is None: return axis.set_xlim(axmin, axmax); axis.set_ylim(aymin, aymax) plt.draw() # force re-draw plt.gcf().canvas.mpl_connect('scroll_event', zoom) def zoom2(event): zoom(event) plt.gcf().canvas.mpl_connect('button_press_event', zoom2) plt.gca().format_coord = statusMesg plt.gcf().canvas.mpl_connect('key_press_event', keyPress)
''' if __name__ == "__main__": # we could add some optional command-line argument here but so far none... parser = OptionParser() options, args = parser.parse_args() if(len(args) < 2): print "usage: plt_overtuningStreamfunction.py <ncfile.nc> 10" exit(1) # file name fname = args[0] # time indice t = int(args[1]) x=Dataset(fname).variables['nx'][:] nx=np.zeros(len(x)+1); nx[0:-1]=x; nx[-1]=x[-1] e=Dataset(fname).variables['e'][t,:] var=Dataset(fname).variables['overturningStreamfunction'][t,:] xCoord, yCoord, zData = m6toolbox.section2quadmesh(nx, e, var, representation='linear') plt.figure() plt.pcolormesh(xCoord, yCoord, zData) plt.colorbar() plt.xlabel('x (km)') plt.ylabel('Elevation (m)') plt.ylim((-720,0)) #plt.savefig(diags[d]+'.png',bbox_inches='tight') plt.show()
def yzcompare(field1, field2, y=None, z=None, ylabel=None, yunits=None, zlabel=None, zunits=None, splitscale=None, title1='', title2='', title3='A - B', addplabel=True, suptitle='', clim=None, colormap=None, extend=None, centerlabels=False, dlim=None, dcolormap=None, dextend=None, centerdlabels=False, nbins=None, landcolor=[.5,.5,.5], aspect=None, resolution=None, axis=None, npanels=3, ignore=None, save=None, debug=False, show=False, interactive=False): """ Renders n-panel plot of two scalar fields, field1(x,y) and field2(x,y). Arguments: field1 Scalar 2D array to be plotted and compared to field2. field2 Scalar 2D array to be plotted and compared to field1. y y coordinate (1D array). If y is the same size as field then y is treated as the cell center coordinates. z z coordinate (1D or 2D array). If z is the same size as field then z is treated as the cell center coordinates. ylabel The label for the y axis. Default 'Latitude'. yunits The units for the y axis. Default 'degrees N'. zlabel The label for the z axis. Default 'Elevation'. zunits The units for the z axis. Default 'm'. splitscale A list of depths to define equal regions of projection in the vertical, e.g. [0.,-1000,-6500] title1 The title to place at the top of panel 1. Default ''. title2 The title to place at the top of panel 1. Default ''. title3 The title to place at the top of panel 1. Default 'A-B'. addplabel Adds a 'A:' or 'B:' to the title1 and title2. Default True. suptitle The super-title to place at the top of the figure. Default ''. clim A tuple of (min,max) color range OR a list of contour levels for the field plots. Default None. colormap The name of the colormap to use for the field plots. Default None. extend Can be one of 'both', 'neither', 'max', 'min'. Default None. centerlabels If True, will move the colorbar labels to the middle of the interval. Default False. dlim A tuple of (min,max) color range OR a list of contour levels for the difference plot. Default None. dcolormap The name of the colormap to use for the differece plot. Default None. dextend For the difference colorbar. Can be one of 'both', 'neither', 'max', 'min'. Default None. centerdlabels If True, will move the difference colorbar labels to the middle of the interval. Default False. nbins The number of colors levels (used is clim is missing or only specifies the color range). landcolor An rgb tuple to use for the color of land (no data). Default [.5,.5,.5]. aspect The aspect ratio of the figure, given as a tuple (W,H). Default [16,9]. resolution The vertical resolution of the figure given in pixels. Default 1280. axis The axis handle to plot to. Default None. npanels Number of panels to display (1, 2 or 3). Default 3. ignore A value to use as no-data (NaN). Default None. save Name of file to save figure in. Default None. debug If true, report stuff for debugging. Default False. show If true, causes the figure to appear on screen. Used for testing. Default False. interactive If true, adds interactive features such as zoom, close and cursor. Default False. """ if (field1.shape)!=(field2.shape): raise Exception('field1 and field2 must be the same shape') # Create coordinates if not provided ylabel, yunits, zlabel, zunits = createYZlabels(y, z, ylabel, yunits, zlabel, zunits) if debug: print('y,z label/units=',ylabel,yunits,zlabel,zunits) if len(y)==z.shape[-1]: y= expand(y) elif len(y)==z.shape[-1]+1: y= y else: raise Exception('Length of y coordinate should be equal or 1 longer than horizontal length of z') if ignore is not None: maskedField1 = numpy.ma.masked_array(field1, mask=[field1==ignore]) else: maskedField1 = field1.copy() yCoord, zCoord, field1 = m6toolbox.section2quadmesh(y, z, maskedField1) # Diagnose statistics yzWeighting = yzWeight(y, z) s1Min, s1Max, s1Mean, s1Std, s1RMS = myStats(maskedField1, yzWeighting, debug=debug) if ignore is not None: maskedField2 = numpy.ma.masked_array(field2, mask=[field2==ignore]) else: maskedField2 = field2.copy() yCoord, zCoord, field2 = m6toolbox.section2quadmesh(y, z, maskedField2) s2Min, s2Max, s2Mean, s2Std, s2RMS = myStats(maskedField2, yzWeighting, debug=debug) dMin, dMax, dMean, dStd, dRMS = myStats(maskedField1 - maskedField2, yzWeighting, debug=debug) dRxy = corr(maskedField1 - s1Mean, maskedField2 - s2Mean, yzWeighting) s12Min = min(s1Min, s2Min); s12Max = max(s1Max, s2Max) xLims = numpy.amin(yCoord), numpy.amax(yCoord); yLims = boundaryStats(zCoord) if debug: print('s1: min, max, mean =', s1Min, s1Max, s1Mean) print('s2: min, max, mean =', s2Min, s2Max, s2Mean) print('s12: min, max =', s12Min, s12Max) # Choose colormap if nbins is None and (clim is None or len(clim)==2): cBins=35 else: cBins=nbins if nbins is None and (dlim is None or len(dlim)==2): nbins=35 if colormap is None: colormap = chooseColorMap(s12Min, s12Max) cmap, norm, extend = chooseColorLevels(s12Min, s12Max, colormap, clim=clim, nbins=cBins, extend=extend) def annotateStats(axis, sMin, sMax, sMean, sStd, sRMS): axis.annotate('max=%.5g\nmin=%.5g'%(sMax,sMin), xy=(0.0,1.025), xycoords='axes fraction', verticalalignment='bottom', fontsize=10) if sMean is not None: axis.annotate('mean=%.5g\nrms=%.5g'%(sMean,sRMS), xy=(1.0,1.025), xycoords='axes fraction', verticalalignment='bottom', horizontalalignment='right', fontsize=10) axis.annotate(' sd=%.5g\n'%(sStd), xy=(1.0,1.025), xycoords='axes fraction', verticalalignment='bottom', horizontalalignment='left', fontsize=10) if addplabel: preTitleA = 'A: '; preTitleB = 'B: ' else: preTitleA = ''; preTitleB = '' if axis is None: setFigureSize(aspect, resolution, npanels=npanels, debug=debug) #plt.gcf().subplots_adjust(left=.13, right=.94, wspace=0, bottom=.05, top=.94, hspace=0.15) if npanels in [2, 3]: axis = plt.subplot(npanels,1,1) plt.pcolormesh(yCoord, zCoord, field1, cmap=cmap, norm=norm) if interactive: addStatusBar(yCoord, zCoord, field1) cb1 = plt.colorbar(fraction=.08, pad=0.02, extend=extend) if centerlabels and len(clim)>2: cb1.set_ticks( 0.5*(clim[:-1]+clim[1:]) ) axis.set_axis_bgcolor(landcolor) plt.xlim( xLims ); plt.ylim( yLims ) if splitscale is not None: for zzz in splitscale[1:-1]: plt.axhline(zzz,color='k',linestyle='--') axis.set_yscale('splitscale', zval=splitscale) annotateStats(axis, s1Min, s1Max, s1Mean, s1Std, s1RMS) axis.set_xticklabels(['']) if len(zlabel+zunits)>0: plt.ylabel(label(zlabel, zunits)) if len(title1)>0: plt.title(preTitleA+title1) axis = plt.subplot(npanels,1,2) plt.pcolormesh(yCoord, zCoord, field2, cmap=cmap, norm=norm) if interactive: addStatusBar(yCoord, zCoord, field2) cb2 = plt.colorbar(fraction=.08, pad=0.02, extend=extend) if centerlabels and len(clim)>2: cb2.set_ticks( 0.5*(clim[:-1]+clim[1:]) ) axis.set_axis_bgcolor(landcolor) plt.xlim( xLims ); plt.ylim( yLims ) if splitscale is not None: for zzz in splitscale[1:-1]: plt.axhline(zzz,color='k',linestyle='--') axis.set_yscale('splitscale', zval=splitscale) annotateStats(axis, s2Min, s2Max, s2Mean, s2Std, s2RMS) if npanels>2: axis.set_xticklabels(['']) if len(zlabel+zunits)>0: plt.ylabel(label(zlabel, zunits)) if len(title2)>0: plt.title(preTitleB+title2) if npanels in [1, 3]: axis = plt.subplot(npanels,1,npanels) if dcolormap is None: dcolormap = chooseColorMap(dMin, dMax) if dlim is None and dStd>0: cmap, norm, dextend = chooseColorLevels(dMean-2.*dStd, dMean+2.*dStd, dcolormap, clim=dlim, nbins=nbins, extend='both', autocenter=True) else: cmap, norm, dextend = chooseColorLevels(dMin, dMax, dcolormap, clim=dlim, nbins=nbins, extend=dextend, autocenter=True) plt.pcolormesh(yCoord, zCoord, field1 - field2, cmap=cmap, norm=norm) if interactive: addStatusBar(yCoord, zCoord, field1 - field2) cb3 = plt.colorbar(fraction=.08, pad=0.02, extend=dextend) if centerdlabels and len(dlim)>2: cb3.set_ticks( 0.5*(dlim[:-1]+dlim[1:]) ) axis.set_axis_bgcolor(landcolor) plt.xlim( xLims ); plt.ylim( yLims ) if splitscale is not None: for zzz in splitscale[1:-1]: plt.axhline(zzz,color='k',linestyle='--') axis.set_yscale('splitscale', zval=splitscale) annotateStats(axis, dMin, dMax, dMean, dStd, dRMS) if len(zlabel+zunits)>0: plt.ylabel(label(zlabel, zunits)) axis.annotate(' r(A,B)=%.5g\n'%(dRxy), xy=(1.0,-1.07), xycoords='axes fraction', verticalalignment='top', horizontalalignment='center', fontsize=10) if len(ylabel+yunits)>0: plt.xlabel(label(ylabel, yunits)) if len(title3)>0: plt.title(title3) if len(suptitle)>0: plt.suptitle(suptitle) if save is not None: plt.savefig(save) if interactive: addInteractiveCallbacks() if show: plt.show(block=False)
def yzplot(field, y=None, z=None, ylabel=None, yunits=None, zlabel=None, zunits=None, splitscale=None, title='', suptitle='', clim=None, colormap=None, extend=None, centerlabels=False, nbins=None, landcolor=[.5,.5,.5], aspect=[16,9], resolution=576, axis=None, ignore=None, save=None, debug=False, show=False, interactive=False): """ Renders section plot of scalar field, field(x,z). Arguments: field Scalar 2D array to be plotted. y y (or x) coordinate (1D array). If y is the same size as field then x is treated as the cell center coordinates. z z coordinate (1D or 2D array). If z is the same size as field then y is treated as the cell center coordinates. ylabel The label for the x axis. Default 'Latitude'. yunits The units for the x axis. Default 'degrees N'. zlabel The label for the z axis. Default 'Elevation'. zunits The units for the z axis. Default 'm'. splitscale A list of depths to define equal regions of projection in the vertical, e.g. [0.,-1000,-6500] title The title to place at the top of the panel. Default ''. suptitle The super-title to place at the top of the figure. Default ''. clim A tuple of (min,max) color range OR a list of contour levels. Default None. colormap The name of the colormap to use. Default None. extend Can be one of 'both', 'neither', 'max', 'min'. Default None. centerlabels If True, will move the colorbar labels to the middle of the interval. Default False. nbins The number of colors levels (used is clim is missing or only specifies the color range). landcolor An rgb tuple to use for the color of land (no data). Default [.5,.5,.5]. aspect The aspect ratio of the figure, given as a tuple (W,H). Default [16,9]. resolution The vertical resolution of the figure given in pixels. Default 720. axis The axis handle to plot to. Default None. ignore A value to use as no-data (NaN). Default None. save Name of file to save figure in. Default None. debug If true, report stuff for debugging. Default False. show If true, causes the figure to appear on screen. Used for testing. Default False. interactive If true, adds interactive features such as zoom, close and cursor. Default False. """ # Create coordinates if not provided ylabel, yunits, zlabel, zunits = createYZlabels(y, z, ylabel, yunits, zlabel, zunits) if debug: print('y,z label/units=',ylabel,yunits,zlabel,zunits) if len(y)==z.shape[-1]: y = expand(y) elif len(y)==z.shape[-1]+1: y = y else: raise Exception('Length of y coordinate should be equal or 1 longer than horizontal length of z') if ignore is not None: maskedField = numpy.ma.masked_array(field, mask=[field==ignore]) else: maskedField = field.copy() yCoord, zCoord, field2 = m6toolbox.section2quadmesh(y, z, maskedField) # Diagnose statistics sMin, sMax, sMean, sStd, sRMS = myStats(maskedField, yzWeight(y, z), debug=debug) yLims = numpy.amin(yCoord), numpy.amax(yCoord) zLims = boundaryStats(zCoord) # Choose colormap if nbins is None and (clim is None or len(clim)==2): nbins=35 if colormap is None: colormap = chooseColorMap(sMin, sMax) cmap, norm, extend = chooseColorLevels(sMin, sMax, colormap, clim=clim, nbins=nbins, extend=extend) if axis is None: setFigureSize(aspect, resolution, debug=debug) #plt.gcf().subplots_adjust(left=.10, right=.99, wspace=0, bottom=.09, top=.9, hspace=0) axis = plt.gca() plt.pcolormesh(yCoord, zCoord, field2, cmap=cmap, norm=norm) if interactive: addStatusBar(yCoord, zCoord, field2) cb = plt.colorbar(fraction=.08, pad=0.02, extend=extend) if centerlabels and len(clim)>2: cb.set_ticks( 0.5*(clim[:-1]+clim[1:]) ) axis.set_axis_bgcolor(landcolor) if splitscale is not None: for zzz in splitscale[1:-1]: plt.axhline(zzz,color='k',linestyle='--') axis.set_yscale('splitscale', zval=splitscale) plt.xlim( yLims ); plt.ylim( zLims ) axis.annotate('max=%.5g\nmin=%.5g'%(sMax,sMin), xy=(0.0,1.01), xycoords='axes fraction', verticalalignment='bottom', fontsize=10) if sMean is not None: axis.annotate('mean=%.5g\nrms=%.5g'%(sMean,sRMS), xy=(1.0,1.01), xycoords='axes fraction', verticalalignment='bottom', horizontalalignment='right', fontsize=10) axis.annotate(' sd=%.5g\n'%(sStd), xy=(1.0,1.01), xycoords='axes fraction', verticalalignment='bottom', horizontalalignment='left', fontsize=10) if len(ylabel+yunits)>0: plt.xlabel(label(ylabel, yunits)) if len(zlabel+zunits)>0: plt.ylabel(label(zlabel, zunits)) if len(title)>0: plt.title(title) if len(suptitle)>0: plt.suptitle(suptitle) if save is not None: plt.savefig(save) if interactive: addInteractiveCallbacks() if show: plt.show(block=False)
def yzcompare(field1, field2, y=None, z=None, ylabel=None, yunits=None, zlabel=None, zunits=None, splitscale=None, title1='', title2='', title3='A - B', addplabel=True, suptitle='', clim=None, colormap=None, extend=None, centerlabels=False, dlim=None, dcolormap=None, dextend=None, centerdlabels=False, nbins=None, landcolor=[.5,.5,.5], aspect=None, resolution=None, axis=None, npanels=3, ignore=None, save=None, debug=False, show=False, interactive=False): """ Renders n-panel plot of two scalar fields, field1(x,y) and field2(x,y). Arguments: field1 Scalar 2D array to be plotted and compared to field2. field2 Scalar 2D array to be plotted and compared to field1. y y coordinate (1D array). If y is the same size as field then y is treated as the cell center coordinates. z z coordinate (1D or 2D array). If z is the same size as field then z is treated as the cell center coordinates. ylabel The label for the y axis. Default 'Latitude'. yunits The units for the y axis. Default 'degrees N'. zlabel The label for the z axis. Default 'Elevation'. zunits The units for the z axis. Default 'm'. splitscale A list of depths to define equal regions of projection in the vertical, e.g. [0.,-1000,-6500] title1 The title to place at the top of panel 1. Default ''. title2 The title to place at the top of panel 1. Default ''. title3 The title to place at the top of panel 1. Default 'A-B'. addplabel Adds a 'A:' or 'B:' to the title1 and title2. Default True. suptitle The super-title to place at the top of the figure. Default ''. clim A tuple of (min,max) color range OR a list of contour levels for the field plots. Default None. colormap The name of the colormap to use for the field plots. Default None. extend Can be one of 'both', 'neither', 'max', 'min'. Default None. centerlabels If True, will move the colorbar labels to the middle of the interval. Default False. dlim A tuple of (min,max) color range OR a list of contour levels for the difference plot. Default None. dcolormap The name of the colormap to use for the differece plot. Default None. dextend For the difference colorbar. Can be one of 'both', 'neither', 'max', 'min'. Default None. centerdlabels If True, will move the difference colorbar labels to the middle of the interval. Default False. nbins The number of colors levels (used is clim is missing or only specifies the color range). landcolor An rgb tuple to use for the color of land (no data). Default [.5,.5,.5]. aspect The aspect ratio of the figure, given as a tuple (W,H). Default [16,9]. resolution The vertical resolution of the figure given in pixels. Default 1280. axis The axis handle to plot to. Default None. npanels Number of panels to display (1, 2 or 3). Default 3. ignore A value to use as no-data (NaN). Default None. save Name of file to save figure in. Default None. debug If true, report stuff for debugging. Default False. show If true, causes the figure to appear on screen. Used for testing. Default False. interactive If true, adds interactive features such as zoom, close and cursor. Default False. """ if (field1.shape)!=(field2.shape): raise Exception('field1 and field2 must be the same shape') # Create coordinates if not provided ylabel, yunits, zlabel, zunits = createYZlabels(y, z, ylabel, yunits, zlabel, zunits) if debug: print 'y,z label/units=',ylabel,yunits,zlabel,zunits if len(y)==z.shape[-1]: y= expand(y) elif len(y)==z.shape[-1]+1: y= y else: raise Exception('Length of y coordinate should be equal or 1 longer than horizontal length of z') if ignore!=None: maskedField1 = numpy.ma.masked_array(field1, mask=[field1==ignore]) else: maskedField1 = field1.copy() yCoord, zCoord, field1 = m6toolbox.section2quadmesh(y, z, maskedField1) # Diagnose statistics yzWeighting = yzWeight(y, z) s1Min, s1Max, s1Mean, s1Std, s1RMS = myStats(maskedField1, yzWeighting, debug=debug) if ignore!=None: maskedField2 = numpy.ma.masked_array(field2, mask=[field2==ignore]) else: maskedField2 = field2.copy() yCoord, zCoord, field2 = m6toolbox.section2quadmesh(y, z, maskedField2) s2Min, s2Max, s2Mean, s2Std, s2RMS = myStats(maskedField2, yzWeighting, debug=debug) dMin, dMax, dMean, dStd, dRMS = myStats(maskedField1 - maskedField2, yzWeighting, debug=debug) dRxy = corr(maskedField1 - s1Mean, maskedField2 - s2Mean, yzWeighting) s12Min = min(s1Min, s2Min); s12Max = max(s1Max, s2Max) xLims = numpy.amin(yCoord), numpy.amax(yCoord); yLims = boundaryStats(zCoord) if debug: print 's1: min, max, mean =', s1Min, s1Max, s1Mean print 's2: min, max, mean =', s2Min, s2Max, s2Mean print 's12: min, max =', s12Min, s12Max # Choose colormap if nbins==None and (clim==None or len(clim)==2): cBins=35 else: cBins=nbins if nbins==None and (dlim==None or len(dlim)==2): nbins=35 if colormap==None: colormap = chooseColorMap(s12Min, s12Max) cmap, norm, extend = chooseColorLevels(s12Min, s12Max, colormap, clim=clim, nbins=cBins, extend=extend) def annotateStats(axis, sMin, sMax, sMean, sStd, sRMS): axis.annotate('max=%.5g\nmin=%.5g'%(sMax,sMin), xy=(0.0,1.025), xycoords='axes fraction', verticalalignment='bottom', fontsize=10) if sMean!=None: axis.annotate('mean=%.5g\nrms=%.5g'%(sMean,sRMS), xy=(1.0,1.025), xycoords='axes fraction', verticalalignment='bottom', horizontalalignment='right', fontsize=10) axis.annotate(' sd=%.5g\n'%(sStd), xy=(1.0,1.025), xycoords='axes fraction', verticalalignment='bottom', horizontalalignment='left', fontsize=10) if addplabel: preTitleA = 'A: '; preTitleB = 'B: ' else: preTitleA = ''; preTitleB = '' if axis==None: setFigureSize(aspect, resolution, npanels=npanels, debug=debug) #plt.gcf().subplots_adjust(left=.13, right=.94, wspace=0, bottom=.05, top=.94, hspace=0.15) if npanels in [2, 3]: axis = plt.subplot(npanels,1,1) plt.pcolormesh(yCoord, zCoord, field1, cmap=cmap, norm=norm) if interactive: addStatusBar(yCoord, zCoord, field1) cb1 = plt.colorbar(fraction=.08, pad=0.02, extend=extend) if centerlabels and len(clim)>2: cb1.set_ticks( 0.5*(clim[:-1]+clim[1:]) ) axis.set_axis_bgcolor(landcolor) plt.xlim( xLims ); plt.ylim( yLims ) if splitscale!=None: for zzz in splitscale[1:-1]: plt.axhline(zzz,color='k',linestyle='--') axis.set_yscale('splitscale', zval=splitscale) annotateStats(axis, s1Min, s1Max, s1Mean, s1Std, s1RMS) axis.set_xticklabels(['']) if len(zlabel+zunits)>0: plt.ylabel(label(zlabel, zunits)) if len(title1)>0: plt.title(preTitleA+title1) axis = plt.subplot(npanels,1,2) plt.pcolormesh(yCoord, zCoord, field2, cmap=cmap, norm=norm) if interactive: addStatusBar(yCoord, zCoord, field2) cb2 = plt.colorbar(fraction=.08, pad=0.02, extend=extend) if centerlabels and len(clim)>2: cb2.set_ticks( 0.5*(clim[:-1]+clim[1:]) ) axis.set_axis_bgcolor(landcolor) plt.xlim( xLims ); plt.ylim( yLims ) if splitscale!=None: for zzz in splitscale[1:-1]: plt.axhline(zzz,color='k',linestyle='--') axis.set_yscale('splitscale', zval=splitscale) annotateStats(axis, s2Min, s2Max, s2Mean, s2Std, s2RMS) if npanels>2: axis.set_xticklabels(['']) if len(zlabel+zunits)>0: plt.ylabel(label(zlabel, zunits)) if len(title2)>0: plt.title(preTitleB+title2) if npanels in [1, 3]: axis = plt.subplot(npanels,1,npanels) if dcolormap==None: dcolormap = chooseColorMap(dMin, dMax) cmap, norm, extend = chooseColorLevels(dMin, dMax, dcolormap, clim=dlim, nbins=nbins, extend=dextend) plt.pcolormesh(yCoord, zCoord, field1 - field2, cmap=cmap, norm=norm) if interactive: addStatusBar(yCoord, zCoord, field1 - field2) cb3 = plt.colorbar(fraction=.08, pad=0.02, extend=dextend) if centerdlabels and len(dlim)>2: cb3.set_ticks( 0.5*(dlim[:-1]+dlim[1:]) ) axis.set_axis_bgcolor(landcolor) plt.xlim( xLims ); plt.ylim( yLims ) if splitscale!=None: for zzz in splitscale[1:-1]: plt.axhline(zzz,color='k',linestyle='--') axis.set_yscale('splitscale', zval=splitscale) annotateStats(axis, dMin, dMax, dMean, dStd, dRMS) if len(zlabel+zunits)>0: plt.ylabel(label(zlabel, zunits)) axis.annotate(' r(A,B)=%.5g\n'%(dRxy), xy=(1.0,-0.20), xycoords='axes fraction', verticalalignment='bottom', horizontalalignment='center', fontsize=10) if len(ylabel+yunits)>0: plt.xlabel(label(ylabel, yunits)) if len(title3)>0: plt.title(title3) if len(suptitle)>0: plt.suptitle(suptitle) if save!=None: plt.savefig(save) if interactive: addInteractiveCallbacks() if show: plt.show(block=False)
def yzplot(field, y=None, z=None, ylabel=None, yunits=None, zlabel=None, zunits=None, splitscale=None, title='', suptitle='', clim=None, colormap=None, extend=None, centerlabels=False, nbins=None, landcolor=[.5,.5,.5], aspect=[16,9], resolution=576, axis=None, ignore=None, save=None, debug=False, show=False, interactive=False): """ Renders section plot of scalar field, field(x,z). Arguments: field Scalar 2D array to be plotted. y y (or x) coordinate (1D array). If y is the same size as field then x is treated as the cell center coordinates. z z coordinate (1D or 2D array). If z is the same size as field then y is treated as the cell center coordinates. ylabel The label for the x axis. Default 'Latitude'. yunits The units for the x axis. Default 'degrees N'. zlabel The label for the z axis. Default 'Elevation'. zunits The units for the z axis. Default 'm'. splitscale A list of depths to define equal regions of projection in the vertical, e.g. [0.,-1000,-6500] title The title to place at the top of the panel. Default ''. suptitle The super-title to place at the top of the figure. Default ''. clim A tuple of (min,max) color range OR a list of contour levels. Default None. colormap The name of the colormap to use. Default None. extend Can be one of 'both', 'neither', 'max', 'min'. Default None. centerlabels If True, will move the colorbar labels to the middle of the interval. Default False. nbins The number of colors levels (used is clim is missing or only specifies the color range). landcolor An rgb tuple to use for the color of land (no data). Default [.5,.5,.5]. aspect The aspect ratio of the figure, given as a tuple (W,H). Default [16,9]. resolution The vertical resolution of the figure given in pixels. Default 720. axis The axis handle to plot to. Default None. ignore A value to use as no-data (NaN). Default None. save Name of file to save figure in. Default None. debug If true, report stuff for debugging. Default False. show If true, causes the figure to appear on screen. Used for testing. Default False. interactive If true, adds interactive features such as zoom, close and cursor. Default False. """ # Create coordinates if not provided ylabel, yunits, zlabel, zunits = createYZlabels(y, z, ylabel, yunits, zlabel, zunits) if debug: print 'y,z label/units=',ylabel,yunits,zlabel,zunits if len(y)==z.shape[-1]: y = expand(y) elif len(y)==z.shape[-1]+1: y = y else: raise Exception('Length of y coordinate should be equal or 1 longer than horizontal length of z') if ignore!=None: maskedField = numpy.ma.masked_array(field, mask=[field==ignore]) else: maskedField = field.copy() yCoord, zCoord, field2 = m6toolbox.section2quadmesh(y, z, maskedField) # Diagnose statistics sMin, sMax, sMean, sStd, sRMS = myStats(maskedField, yzWeight(y, z), debug=debug) yLims = numpy.amin(yCoord), numpy.amax(yCoord) zLims = boundaryStats(zCoord) # Choose colormap if nbins==None and (clim==None or len(clim)==2): nbins=35 if colormap==None: colormap = chooseColorMap(sMin, sMax) cmap, norm, extend = chooseColorLevels(sMin, sMax, colormap, clim=clim, nbins=nbins, extend=extend) if axis==None: setFigureSize(aspect, resolution, debug=debug) #plt.gcf().subplots_adjust(left=.10, right=.99, wspace=0, bottom=.09, top=.9, hspace=0) axis = plt.gca() plt.pcolormesh(yCoord, zCoord, field2, cmap=cmap, norm=norm) if interactive: addStatusBar(yCoord, zCoord, field2) cb = plt.colorbar(fraction=.08, pad=0.02, extend=extend) if centerlabels and len(clim)>2: cb.set_ticks( 0.5*(clim[:-1]+clim[1:]) ) axis.set_axis_bgcolor(landcolor) if splitscale!=None: for zzz in splitscale[1:-1]: plt.axhline(zzz,color='k',linestyle='--') axis.set_yscale('splitscale', zval=splitscale) plt.xlim( yLims ); plt.ylim( zLims ) axis.annotate('max=%.5g\nmin=%.5g'%(sMax,sMin), xy=(0.0,1.01), xycoords='axes fraction', verticalalignment='bottom', fontsize=10) if sMean!=None: axis.annotate('mean=%.5g\nrms=%.5g'%(sMean,sRMS), xy=(1.0,1.01), xycoords='axes fraction', verticalalignment='bottom', horizontalalignment='right', fontsize=10) axis.annotate(' sd=%.5g\n'%(sStd), xy=(1.0,1.01), xycoords='axes fraction', verticalalignment='bottom', horizontalalignment='left', fontsize=10) if len(ylabel+yunits)>0: plt.xlabel(label(ylabel, yunits)) if len(zlabel+zunits)>0: plt.ylabel(label(zlabel, zunits)) if len(title)>0: plt.title(title) if len(suptitle)>0: plt.suptitle(suptitle) if save!=None: plt.savefig(save) if interactive: addInteractiveCallbacks() if show: plt.show(block=False)
options, args = parser.parse_args() if (len(args) < 2): print "usage: plt_overtuningStreamfunction.py <ncfile.nc> 10" exit(1) # file name fname = args[0] # time indice t = int(args[1]) x = Dataset(fname).variables['nx'][:] nx = np.zeros(len(x) + 1) nx[0:-1] = x nx[-1] = x[-1] e = Dataset(fname).variables['e'][t, :] var = Dataset(fname).variables['overturningStreamfunction'][t, :] xCoord, yCoord, zData = m6toolbox.section2quadmesh(nx, e, var, representation='linear') plt.figure() plt.pcolormesh(xCoord, yCoord, zData) plt.colorbar() plt.xlabel('x (km)') plt.ylabel('Elevation (m)') plt.ylim((-720, 0)) #plt.savefig(diags[d]+'.png',bbox_inches='tight') plt.show()