def draw_sea_polyline(endLon, plot, wks): # 海岸线- 图1 绘制(海岸线和等高线有区别吗) shpf3 = Nio.open_file("/home/xulh/mnt/python/python_script/orl/quanqiu/HAX.shp", "r") # 4海岸线 lon3 = np.ravel(shpf3.variables["x"][:]) lat3 = np.ravel(shpf3.variables["y"][:]) segments3 = shpf3.variables["segments"][:, 0] dqres = Ngl.Resources() # -- resources for polylines dqres.gsLineColor = "black" dqres.gsLineThicknessF = 1.0 dqres.gsSegments = segments3 Ngl.add_polyline(wks, plot, lon3, lat3, dqres) # 5.海岸线-图2 绘制 shpf4 = Nio.open_file("/home/xulh/mnt/python/python_script/orl/quanqiu/DYAX.shp", "r") lon4 = np.ravel(shpf4.variables["x"][:]) lat4 = np.ravel(shpf4.variables["y"][:]) segments4 = shpf4.variables["segments"][:, 0] dqres = Ngl.Resources() dqres.gsLineColor = "black" dqres.gsLineThicknessF = 1.0 dqres.gsSegments = segments4 Ngl.add_polyline(wks, plot, lon4, lat4, dqres) if endLon == 360: resp = Ngl.Resources() resp.gsLineColor = "black" resp.gsLineThicknessF = 1 resp.gsLineDashPattern = 2 Ngl.add_polyline(wks, plot, [0, 180], [0, 0], resp) Ngl.add_polyline(wks, plot, [180, 360], [0, 0], resp) Ngl.add_polyline(wks, plot, [180, 180], [-90, 90], resp)
def add_highlights(wks,plot,xmin,xmax,ymin,ymax,title): nboxes = 10 xbox = Ngl.fspan(xmin,xmax,nboxes) ybox = [ymin,ymin,ymax,ymax,ymin] nboxes = xbox.shape[0]-1 #---Resources for filled purple boxes. gnres = Ngl.Resources() gnres.gsFillColor = "goldenrod" # "MediumPurple1" gnres.gsFillOpacityF = 0.15 id = [] for n in range(0,nboxes-1,2): id.append(Ngl.add_polygon(wks,plot,\ [xbox[n],xbox[n+1],xbox[n+1],xbox[n],xbox[n]],\ ybox,gnres)) #---Resources to outline box of interest lnres = Ngl.Resources() lnres.gsLineThicknessF = 3.0 border = Ngl.add_polyline(wks,plot,[xmin,xmax,xmax,xmin,xmin],\ [ymin,ymin,ymax,ymax,ymin],lnres) txres = Ngl.Resources() txres.txFontHeightF = 0.022 txres.txFont = "Helvetica-Bold" txres.txJust = "TopCenter" text = Ngl.add_text(wks,plot,title,(xmin+xmax)/2.,ymax-0.05,txres) return([id,border,text])
def add_mpas_edges(wks,map,mfile): lonVertex = mfile.variables["lonVertex"][:] latVertex = mfile.variables["latVertex"][:] latVertex = latVertex * RAD2DEG lonVertex = lonVertex * RAD2DEG verticesOnEdge = mfile.variables["verticesOnEdge"][:] nedges = verticesOnEdge.shape[0] ecx = numpy.ndarray((nedges,2),'d') ecy = numpy.ndarray((nedges,2),'d') ecx[:,0] = lonVertex[verticesOnEdge[:,0]-1] ecx[:,1] = lonVertex[verticesOnEdge[:,1]-1] ecy[:,0] = latVertex[verticesOnEdge[:,0]-1] ecy[:,1] = latVertex[verticesOnEdge[:,1]-1] ii = numpy.where((abs(ecx[:,0]-ecx[:,1]) > 180)) iigt = numpy.where((ecx[ii,0] > ecx[ii,1])) iilt = numpy.where((ecx[ii,0] < ecx[ii,1])) ecx[iigt,0] = ecx[iigt,0] - 360.0 ecx[iilt,1] = ecx[iilt,1] - 360.0 # # Attach the polylines using special "gsSegments" resource. This # is *much* faster than attaching every line individually. # lnres = Ngl.Resources() lnres.gsLineThicknessF = 0.50 # default is 1 lnres.gsLineColor = "Navy" # default is black. lnres.gsSegments = range(0,nedges * 2,2) map.poly = Ngl.add_polyline(wks,map,numpy.ravel(ecx),numpy.ravel(ecy),lnres)
def add_mrb_lines(wks,plot,lat,lon): #---Resources for polyline lnres = Ngl.Resources() lnres.gsLineColor = "black" lnres.gsLineThicknessF = 3.0 # 3x as thick return Ngl.add_polyline(wks, plot, lon, lat, lnres)
def plot_cc(wks,cont,x='lh',y='dse'): """ """ ## if (x == 'lh' and y == 'dse'): vy = np.linspace(240,360,101) press = 101300. vx,es = cclap(vy*1000/1004.,press) vx = 2.5 * 10**3 * vx ccstring = 'C-C, RH=100%' ## Line of constant moist static energy vy2 = 345. - vx lres = Ngl.Resources() lres.gsLineDashPattern = 1 lres.gsLineLabelFontHeightF = 0.009 lres.gsLineLabelString = 'MSE = 345 kJ/kg' lres.gsLineDashSegLenF = 0.09 line = Ngl.add_polyline(wks,cont,vx,vy2,lres) if (x == 'lh' and y == 'mse'): vy = np.linspace(240,360,101) press = 101300. vx,es = 2.5 * 10**3 * cclap(vy*1000/1004.,press) vy = vy + vx ccstring = 'C-C, RH=100%' ## Line of constant moist static energy vy2 = 345. * np.ones(vx.shape[0]) lres = Ngl.Resources() lres.gsLineDashPattern = 1 lres.gsLineLabelFontHeightF = 0.009 lres.gsLineLabelString = 'MSE = 345 kJ/kg' lres.gsLineDashSegLenF = 0.09 line = Ngl.add_polyline(wks,cont,vx,vy2,lres) lres = Ngl.Resources() lres.gsLineDashPattern = 15 lres.gsLineLabelFontHeightF = 0.009 lres.gsLineLabelString = ccstring line = Ngl.add_polyline(wks,cont,vx,vy,lres) return wks,cont
def contour_map(self): params_dict = self.params_dict color_levels = self.color_levels cn_fill_colors = np.arange(0, len(color_levels), 1) # 1.绘制南海底板 south_sea_baseboard = params_dict.pop('south_sea_baseboard') south_sea_baseboard['cnLevels'] = color_levels south_sea_baseboard['cnFillColors'] = cn_fill_colors resource = create_or_update_resource(params_dict=south_sea_baseboard) south_sea_plot = Ngl.contour_map(self.workstation, self.input_data, resource) # 2.绘制南海相关地理线 south_sea_geoline = params_dict.pop('south_sea_geoline') # 多级 for key, params_dict in south_sea_geoline.items(): file_name = params_dict.pop('file_name') type = params_dict.pop('type') shape = Nio.open_file(shape_file_path + file_name, "r") lon = np.ravel(shape.variables["x"][:]) lat = np.ravel(shape.variables["y"][:]) params_dict['gsSegments'] = shape.variables["segments"][:, 0] resource = create_or_update_resource(params_dict=params_dict) # 2.绘制曲线图 if type == 'polyline': Ngl.add_polyline(self.workstation, south_sea_plot, lon, lat, resource) else: pass #polygon/point 处理待定 # 3. 南海加比例尺 south_sea_scale = params_dict.pop('south_sea_scale') scala_figure = south_sea_scale.pop('scala_figure') x, y = south_sea_scale.pop('location').split('x') resource = create_or_update_resource(params_dict=south_sea_scale) Ngl.add_text(self.workstation, south_sea_plot, scala_figure, x, y, resource) # 4.南海放在中国的位置 south_sea_location = params_dict.pop('south_sea_location') resource = create_or_update_resource(params_dict=south_sea_location) Ngl.add_annotation(self.plot, south_sea_plot, resource)
def add_map_gridlines(wks,map,lat_spc,lon_spc): #---Set some resources for the polyline lnres = Ngl.Resources() lnres.gsLineColor = "Gray25" lnres.gsLineThicknessF = 1.0 # 1.0 is the default lnres.gsLineDashPattern = 2 # 0 (solid) is the default lon_values = np.arange(-180,181,lon_spc) lat_values = np.arange(-90,91,lat_spc) #---Add the line to existing plot lines = [] for lat in lat_values: lines.append(Ngl.add_polyline(wks,map,[-180,0,180],[lat,lat,lat],lnres)) for lon in lon_values: lines.append(Ngl.add_polyline(wks,map,[lon,lon],[-90,90],lnres)) lnres.gsLineColor = "red" return lines
def add_shapefile_outlines(wks, plot, filename): #---Read data off shapefile f = Nio.open_file(filename, "r") lon = np.ravel(f.variables["x"][:]) lat = np.ravel(f.variables["y"][:]) plres = Ngl.Resources() # resources for polylines plres.gsLineColor = "navyblue" plres.gsLineThicknessF = 2.0 # default is 1.0 plres.gsSegments = f.variables["segments"][:, 0] return Ngl.add_polyline(wks, plot, lon, lat, plres)
def add_shapefile_polylines(input_shapefile, wks, plot, color="black", thick=10.0): """ Attach shapefile polylines to map """ f_shap = Nio.open_file(input_shapefile, "r") lon = f_shap.variables["x"][:] #np.ravel() lat = f_shap.variables["y"][:] lnres = Ngl.Resources() lnres.gsLineColor = color lnres.gsLineThicknessF = thick lnres.gsSegments = f_shap.variables["segments"][:, 0] return Ngl.add_polyline(wks, plot, lon, lat, lnres)
def add_trajectories(wks,map,filename,cmap): #---Open the netCDF file containing the salinity data for the trajectories. ncfile = Nio.open_file(filename) traj = [1,10,53,67,80] # choose which trajectories to plot pres = Ngl.Resources() # polyline resources pres.gsLineThicknessF = 5.0 # line thickness mres = Ngl.Resources() # marker resources mres.gsMarkerSizeF = 17.0 # marker size mres.gsMarkerColor = "black" # marker color mres.gsMarkerIndex = 15 # circle with an X mres.gsMarkerThicknessF = 2.0 # thicker marker outlines # # Loop through the chosen trajectories. # sdata = ncfile.variables["sdata"] sid = [] for i in range(len(traj)): lat = sdata[2,:,traj[i]] # extract lat from whole array lon = sdata[1,:,traj[i]] # extract lon from whole array sst = sdata[8,:,traj[i]] # # Map the salinity values between 34.55 and 34.85 into color # indices between 0 and 9 and draw polylines, with those # colors, between adjacent lat/lon values. # for j in range(len(lat)-2): sval = 0.5*(sst[j]+sst[j+1]) cindex = nint(30.*(sval-34.55)) pres.gsLineColor = cmap[cindex] sid.append(Ngl.add_polyline(wks,map,[lon[j],lon[j+1]],[lat[j],lat[j+1]],pres)) #---Draw a polymarker at the beginning of each trajectory. sid.append(Ngl.add_polymarker(wks,map,[lon[0]],[lat[0]],mres)) return
def add_labelbar(wks,map,cmap): gsres = Ngl.Resources() # Line resources. delta_lon = 4.0 delta_lat = 2.1 start_lon = -68. start_lat = -58. txres = Ngl.Resources() # For labeling the label bar. txres.txFontHeightF = 0.015 gid = [] lid = [] tid = [] for i in range(4,14,1): lon0 = start_lon+(i-4)*delta_lon lon1 = lon0+delta_lon lat0 = start_lat lat1 = start_lat+delta_lat lons = [lon0,lon1,lon1,lon0,lon0] lats = [lat0,lat0,lat1,lat1,lat0] gsres.gsFillColor = cmap[i-4] # Change fill color. gid.append(Ngl.add_polygon(wks,map,lons,lats,gsres)) lid.append(Ngl.add_polyline(wks,map,lons,lats,gsres)) if (i == 4): tid.append(Ngl.add_text(wks,map,"34.55",lon0,lat0-delta_lat,txres)) elif(i == 6): tid.append(Ngl.add_text(wks,map,"34.61",lon0,lat0-delta_lat,txres)) elif(i == 8): tid.append(Ngl.add_text(wks,map,"34.67",lon0,lat0-delta_lat,txres)) elif(i == 10): tid.append(Ngl.add_text(wks,map,"34.73",lon0,lat0-delta_lat,txres)) elif(i == 12): tid.append(Ngl.add_text(wks,map,"34.79",lon0,lat0-delta_lat,txres)) else: tid.append(Ngl.add_text(wks,map,"34.85",start_lon+10*delta_lon,lat0-delta_lat,txres)) return
config.nglDraw = False config.mpProjection = "Orthographic" config.mpLimitMode = "LatLon" config.mpMinLonF = 0 config.mpMaxLonF = 18 config.mpMinLatF = 43 config.mpMaxLatF = 50 map = Ngl.map(wks,config) ecx = numpy.ravel( vlon[ edge_vertices-1 ], order='F' ) ecy = numpy.ravel( vlat[ edge_vertices-1 ], order='F' ) lines_cfg = Ngl.Resources() lines_cfg.gsSegments = numpy.arange(0, edge_vertices.size, 2) poly = Ngl.add_polyline(wks, map, ecx, ecy, lines_cfg) Ngl.draw(map) Ngl.frame(wks) Ngl.end() sys.exit() # regular plot print('Plot regular') datafile = Nio.open_file(args.data) clon = numpy.rad2deg( gridfile.variables["clon"][:] ) clat = numpy.rad2deg( gridfile.variables["clat"][:] ) clonv = numpy.rad2deg( gridfile.variables["clon_vertices"][:] ) clatv = numpy.rad2deg( gridfile.variables["clat_vertices"][:] )
def plot_dots(vpx=0.2,vpy=0.8,hei=0.3,wth=0.4,xlab='',ylab='',legend=True, yrev=False, lab=''): res = Ngl.Resources() res.nglFrame = False res.nglPaperOrientation = 'Portrait' res.nglMaximize = False res.nglDraw = False res.xyMarkLineMode = 'Markers' res.xyMonoMarkerColor = True res.xyMarkerColor = 'black' res.xyMarkerThicknessF = 2 res.xyMarkerSizeF = 0.01 res.tiYAxisString = ylab res.tiXAxisString = xlab res.tiMainString = lab res.tiMainFontHeightF = 0.015 res.tiMainOffsetYF = -hei/4.7 res.tiMainOffsetXF = -wth * 2./5. res.trXMinF = xmin res.trXMaxF = xmax res.trYMinF = ymin res.trYMaxF = ymax res.trYReverse = yrev res.vpXF = vpx res.vpYF = vpy res.vpHeightF = hei res.vpWidthF = wth xy = Ngl.xy(wks,np.transpose(np.vstack((vx,vx))),np.transpose(np.vstack((vy,vy))),res) if(1): ## Fit line k,m,cor,sig,err = stats.linregress(vx,vy) vx2 = np.linspace(xmin,xmax,10) vy2 = vx2 * k + m # Plot line lres = Ngl.Resources() lres.gsLineColor = 'black' lres.gsLineDashPattern = 1 lres.gsLineThicknessF = 2 line = Ngl.add_polyline(wks,xy,vx2,vy2,lres) # Print correlations text = 'k = %.2f R = %4.2f' % (k,cor) if (sig*100. < 1.): text = text + ' (99% sign.)' elif (sig*100. < 5.): text = text + ' (95% sign.)' else: text = text + ' (not sign.)' tres = Ngl.Resources() tres.txFontHeightF = 0.012 tres.txJust = 'CenterLeft' tres.txFontColor = 'black' Ngl.text_ndc(wks,text,vpx,vpy+0.02,tres) Ngl.draw(xy)
def plot_xy(vpx=0.2,vpy=0.8,hei=0.3,wth=0.4,xlab='',ylab='',legend=True, yrev=False, lab=''): nprof = len(vy) res = Ngl.Resources() res.nglFrame = False res.nglPaperOrientation = 'Portrait' res.nglMaximize = False res.nglDraw = False res.xyLineColors = colors res.xyLineThicknesses = thicknesses res.tiYAxisString = ylab res.tiXAxisString = xlab res.tiMainString = lab res.tiMainFontHeightF = 0.015 res.tiMainOffsetYF = -hei/4.7 res.tiMainOffsetXF = -wth * 2./5. res.trXMinF = xmin res.trXMaxF = xmax res.trYMinF = ymin res.trYMaxF = ymax res.trYReverse = yrev res.vpXF = vpx res.vpYF = vpy res.vpHeightF = hei res.vpWidthF = wth xy = Ngl.xy(wks,vx[0],vy[0],res) for jn in range(1,nprof): res = Ngl.Resources() res.gsLineColor = colors[jn] res.gsLineDashPattern = patterns[jn] res.gsLineThicknessF = thicknesses[jn] if ( isinstance(vx,list) and len(vx) >= len(vy) ): tmpx = vx[jn] elif (isinstance(vx,list) and len(vx)-1 < jn ): tmpx = vx[0] else: tmpx = vx line = Ngl.add_polyline(wks,xy,tmpx,vy[jn],res) Ngl.draw(xy) wth2 = 0.08 hei2 = 0.08 for jn in range(0,2): if (jn == 0): x0 = vpx+wth-(wth2) y0 = vpy+hei2 st = 0 sp = 4 elif (jn == 1 and nprof > 4): x0 = vpx+wth-(2*wth2+0.05) y0 = vpy+hei2 st = 4 sp = nprof lres = Ngl.Resources() lres.vpWidthF = wth2 lres.vpHeightF = hei2 lres.lgLineColors = colors[st:sp] lres.lgLineThicknesses = thicknesses[st:sp] lres.lgDashIndexes = patterns[st:sp] lres.lgLineLabelsOn = False lres.lgLabelFontHeightF = 0.008 if(legend): lg = Ngl.legend_ndc(wks,sp-st,titles1[st:sp],x0,y0,lres)
def plot_psirr_lines(vpx=0.2, vpy=0.8, hei=0.4, xlab=1,ylab=1): psi_levels = np.array([-500,-50]) if(1): if(1): res = Ngl.Resources() res.nglMaximize = False res.nglPaperOrientation = 'Portrait' res.nglFrame = False res.nglDraw = False res.cnFillOn = False res.cnLinesOn = True res.cnLineLabelsOn = True res.cnLineLabelDensityF = 2 res.cnLineLabelBackgroundColor = -1 res.cnLevelSelectionMode = 'ExplicitLevels' res.cnLevels = psi_levels res.cnMonoLineColor = True res.cnLineColor = 'blue' res.cnLineThicknessF = 2 res.cnInfoLabelOn = False res.sfXArray = vx res.sfYArray = vy res.trXMinF = -3 res.trXMaxF = 55 res.trYMinF = 250 res.trYMaxF = 360 res.tiXAxisString = 'Latent heat [kJ/kg]' res.tiYAxisString = 'Dry static energy [kJ/kg]' res.tiMainString = title if (xlab == 1): res.tiXAxisOn = True res.tmXBLabelsOn = True res.tiXAxisSide = 'Bottom' elif (xlab == -1): res.tiXAxisOn = True res.tmXBLabelsOn = False res.tmXTLabelsOn = True res.tiXAxisSide = 'Top' elif (xlab == 0): res.tiXAxisOn = False res.tmXBLabelsOn = False res.tmXTLabelsOn = False if (ylab == 1): res.tiYAxisOn = True res.tmYLLabelsOn = True res.tmYRLabelsOn = False res.tiYAxisSide = 'Left' elif (ylab == -1): res.tiYAxisOn = True res.tmYLLabelsOn = False res.tmYRLabelsOn = True res.tiYAxisSide = 'Right' elif (ylab == 0): res.tiYAxisOn = False res.tmYLLabelsOn = False res.tmYRLabelsOn = False res.vpWidthF = hei res.vpHeightF = hei res.vpYF = vpy res.vpXF = vpx lsmooth = False if (lsmooth): sigma = 2 order = 0 for ji in range(0,2): ndimage.filters.gaussian_filter(zplot1[:,:],sigma,order=order,\ output=zplot[:,:],\ mode='reflect', cval=0.0) cont1 = Ngl.contour(wks,zplot1[:,:],res) ## Clausius-Clapeyron line vy_cc = np.linspace(240,360,101) press = 101300. vx_cc,es = cclap(vy_cc*1000/1004.,press) vx_cc = 2.5 * 10**3 * vx_cc #ccstring = 'C-C, RH=100%' lres = Ngl.Resources() lres.gsLineDashPattern = 15 lres.gsLineLabelFontHeightF = 0.009 lres.gsLineThicknessF = 3 #lres.gsLineLabelString = ccstring line = Ngl.add_polyline(wks,cont1,vx_cc,vy_cc,lres) ## MSE profiles lres = Ngl.Resources() lres.gsLineDashPattern = 1 lres.gsLineThicknessF = 7 lres.gsLineColor = 'blue' line = Ngl.add_polyline(wks,cont1,vlh1,vdse1,lres) res.cnLineColor = 'red' cont2 = Ngl.contour(wks,zplot2[:,:],res) ## MSE profiles lres = Ngl.Resources() lres.gsLineDashPattern = 1 lres.gsLineThicknessF = 7 lres.gsLineColor = 'red' line = Ngl.add_polyline(wks,cont2,vlh2,vdse2,lres) Ngl.overlay(cont2,cont1) Ngl.draw(cont2)
[res.trXMinF,res.trXMaxF,res.trXMaxF,res.trXMinF,res.trXMinF], [0.,0.,res.trYMaxF,res.trYMaxF,0.],fillres)) fillres.gsFillColor = "LightBlue" fillbox.append(Ngl.add_polygon(wks,plot, \ [res.trXMinF,res.trXMaxF,res.trXMaxF,res.trXMinF,res.trXMinF], [0.,0.,res.trYMinF,res.trYMinF,0.],fillres)) # # Draw some boxes and bars on the XY plot using calls to Ngl.add_polyline. # # First draw a thick line at Y = 0. # lineres = Ngl.Resources() lineres.gsLineThicknessF = 3. zero_line = Ngl.add_polyline(wks, plot, [res.trXMinF, res.trXMaxF], [0., 0.], lineres) # # Add the vertical green "error" bars. # time = Ngl.fspan(1, 5, 5) lineres.gsLineThicknessF = 2.5 lineres.gsLineColor = "DarkGreen" vlines = [] for ii in range(5): ii1 = ii + 1 vlines.append( Ngl.add_polyline(wks, plot, [ii1, ii1], [minval[ii], maxval[ii]], lineres)) vlines.append(Ngl.add_polyline(wks,plot,[ii1-.08,ii1+.08], \ [maxval[ii],maxval[ii]],lineres))
#---Create dummy data for additional curve. npts2 = 40 y2 = numpy.zeros([npts2], 'f') for i in range(npts2): y2[i] = 3.0 - 6. * random.random() #---Force some of the y2 points be missing y2 = ma.array(y2,mask=[0,0,0,0,0,0,1,1,0,0,0,0,0,1,1,0,0,0,0,0,\ 1,1,0,0,0,0,1,1,1,0,1,0,0,0,1,0,0,1,1,1]) #---Set some resources for the polyline gsres = Ngl.Resources() gsres.gsLineColor = "Blue" gsres.gsLineThicknessF = 3. #---Add the line to existing plot x = Ngl.fspan(min(years), max(years), npts2) prim1 = Ngl.add_polyline(wks, plot, x, y2, gsres) #---Change the main title of original plot. srlist = Ngl.Resources() srlist.tiMainString = "Adding a blue curve with missing values" Ngl.set_values(plot, srlist) #---Draw plot (and its attached line) Ngl.draw(plot) Ngl.frame(wks) Ngl.end()
res.mpMinLonF = -90 res.mpMaxLonF = -30 res.mpFillOn = True res.mpLandFillColor = "NavajoWhite" res.mpOceanFillColor = "SlateGray2" res.tiMainString = "Stream network data for South America" res.tiMainFontHeightF = 0.015 # Make font slightly smaller. plot = Ngl.map(wks, res) # Draw map, but don't advance frame. #************************************************* # Section to add polylines to map. #************************************************* f = Nio.open_file(filename, "r") # Open shapefile lon = numpy.ravel(f.variables["x"][:]) lat = numpy.ravel(f.variables["y"][:]) segments = f.variables["segments"][:, 0] plres = Ngl.Resources() # resources for polylines plres.gsLineColor = "blue" plres.gsSegments = segments id = Ngl.add_polyline(wks, plot, lon, lat, plres) Ngl.draw(plot) Ngl.frame(wks) Ngl.end()
def plot_xy(wks,vx,data_vy,vpx=0.2,vpy=0.8,hei=0.3,xlab='',ylab='',\ prof=False,yrev=True,\ linecolors = ['red','blue','black','green','yellow'],\ linethicknesses=[1,1,1,1,1], linepatterns=[0,0,0,0,0],\ titles=[''],\ xmin=0.,xmax=1000.,ymin=0.,ymax=100.,\ frame=True): """ """ if ( isinstance(data_vy,list) ): nprof = len(data_vy) else: data_vy = [data_vy] nprof = 1 vx = fill_blanks(vx,nprof) linecolors = fill_blanks(linecolors,nprof) linepatterns = fill_blanks(linepatterns,nprof) linethicknesses = fill_blanks(linethicknesses,nprof) if (prof): tmp = vx vx = data_vy data_vy = tmp res = Ngl.Resources() res.nglFrame = False res.nglPaperOrientation = 'Portrait' res.nglMaximize = False res.nglDraw = False res.xyLineColors = linecolors res.tiYAxisString = ylab res.tiXAxisString = xlab res.trYReverse = yrev res.trXMinF = xmin res.trXMaxF = xmax res.trYMinF = ymin res.trYMaxF = ymax if(prof): wth = hei * 1./np.sqrt(2.) else: wth = hei * np.sqrt(2.) res.vpXF = vpx res.vpYF = vpy res.vpHeightF = hei res.vpWidthF = wth xy = Ngl.xy(wks,vx[0],data_vy[0],res) for jn in range(1,nprof): res = Ngl.Resources() res.gsLineColor = linecolors[jn] res.gsLineDashPattern = linepatterns[jn] res.gsLineThicknessF = linethicknesses[jn] line = Ngl.add_polyline(wks,xy,vx[jn],data_vy[jn],res) Ngl.draw(xy) wth2 = 0.15 hei2 = 0.08 for jn in range(0,2): if (jn == 0): x0 = vpx+wth-(wth2) y0 = vpy+hei2 st = 0 sp = 4 elif (jn == 1): x0 = vpx+wth-(2*wth2+0.05) y0 = vpy+hei2 st = 4 sp = 7 lres = Ngl.Resources() lres.vpWidthF = wth2 lres.vpHeightF = hei2 lres.lgLineColors = linecolors[st:sp] lres.lgLineThicknesses = linethicknesses[st:sp] lres.lgDashIndexes = linepatterns[st:sp] lres.lgLineLabelsOn = False lres.lgLabelFontHeightF = 0.01 lg = Ngl.legend_ndc(wks,sp-st,titles[st:sp],x0,y0,lres) #tres = Ngl.Resources() #tres.txFontHeightF = 0.015 #tres.txJust = 'CenterLeft' #y = vpy + 0.03 #x0 = vpx #dx = 0.15 #print nprof #print titles #for jn in range(0,nprof): # tres.txFontColor = linecolors[jn] # x = x0 + dx*jn # Ngl.text_ndc(wks,titles[jn],x,y,tres) if (frame): Ngl.frame(wks)
def plot_dots(wks,vx,vy,vpx=0.2,vpy=0.8,hei=0.3,xlab='',ylab='',\ prof=False,lreg=True,\ dotcolors = ['red','blue','black','green','yellow'],\ dotsizes=[1,1,1,1,1], dotindices=[9,6,2,3,4,5],\ titles=[''],\ xmin=0.,xmax=1000.,ymin=0.,ymax=100.,\ frame=True): """ """ ndots = len(vy) print dotcolors print dotindices print dotsizes dotcolors = fill_blanks(dotcolors,ndots) dotindices = fill_blanks(dotindices,ndots) dotsizes = fill_blanks(dotsizes,ndots) res = Ngl.Resources() res.nglFrame = False res.nglPaperOrientation = 'Portrait' res.nglMaximize = False res.nglDraw = False res.xyMarkLineMode = 'Markers' res.xyMonoMarkerColor = False res.xyMarkerColors = dotcolors res.xyMarkerThicknesses = 2 res.xyMarkerSizes = np.array(dotsizes) * 0.01 res.xyMarkers = dotindices res.tiYAxisString = ylab res.tiXAxisString = xlab res.trXMinF = xmin res.trXMaxF = xmax res.trYMinF = ymin res.trYMaxF = ymax if(prof): wth = hei * 1./np.sqrt(2.) else: wth = hei * np.sqrt(2.) res.vpXF = vpx res.vpYF = vpy res.vpHeightF = hei res.vpWidthF = wth print vx print vy print xmin,xmax,ymin,ymax xy = Ngl.xy(wks,np.transpose(np.vstack((vx,vx))),np.transpose(np.vstack((vy,vy))),res) if (lreg): ## Fit line k,m,cor,sig,err = stats.linregress(vx,vy) vx = np.linspace(xmin,xmax,10) vy = vx * k + m # Plot line lres = Ngl.Resources() lres.gsLineColor = 'black' lres.gsLineDashPattern = 1 lres.gsLineThicknessF = 2 line = Ngl.add_polyline(wks,xy,vx,vy,lres) # Print correlations text = 'R = '+repr(cor) if (sig*100. < 1.): text = text + ' (99% sign.)' elif (sig*100. < 5.): text = text + ' (95% sign.)' else: text = text + ' (not sign.)' tres = Ngl.Resources() tres.txFontHeightF = 0.01 tres.txJust = 'BottomLeft' tres.txFontColor = 'black' Ngl.text_ndc(wks,text,vpx+wth,vpy-hei-0.03,tres) Ngl.draw(xy) #wth2 = 0.15 #hei2 = 0.08 #for jn in range(0,2): # if (jn == 0): # x0 = vpx+wth-(wth2) # y0 = vpy+hei2 # st = 0 # sp = 4 # elif (jn == 1): # x0 = vpx+wth-(2*wth2+0.05) # y0 = vpy+hei2 # st = 4 # sp = 7 # lres = Ngl.Resources() # lres.vpWidthF = wth2 # lres.vpHeightF = hei2 # lres.lgLineColors = linecolors[st:sp] # lres.lgLineThicknesses = linethicknesses[st:sp] # lres.lgDashIndexes = linepatterns[st:sp] # lres.lgLineLabelsOn = False # lres.lgLabelFontHeightF = 0.01 # lg = Ngl.legend_ndc(wks,sp-st,titles[st:sp],x0,y0,lres) if (frame): Ngl.frame(wks)
taus_above_zero = Numeric.take(taus,ind_above_zero) px[0::5] = (taus_above_zero - dx/2.).astype(taus.typecode()) px[1::5] = (taus_above_zero - dx/2.).astype(taus.typecode()) px[2::5] = (taus_above_zero + dx/2.).astype(taus.typecode()) px[3::5] = (taus_above_zero + dx/2.).astype(taus.typecode()) px[4::5] = (taus_above_zero - dx/2.).astype(taus.typecode()) py[0::5] = rain_res.trYMinF py[1::5] = Numeric.take(rain03,ind_above_zero) py[2::5] = Numeric.take(rain03,ind_above_zero) py[3::5] = rain_res.trYMinF py[4::5] = rain_res.trYMinF polyg = Ngl.add_polygon(wks,rainhist,px,py,pgres) # # For the outlines, we don't need the fifth point. # polyl = Ngl.add_polyline(wks,rainhist,px,py,pgres) temptmsz = Ngl.xy(wks,taus,tempht,tempsfc_res) # ---------------------- overlay, draw, and advance frame --------- Ngl.overlay(rhfill,templine) # Overlay temperature contour on rh plot. Ngl.overlay(rhfill,windlayer) # Overlay windbarbs on rh plot. Ngl.draw(rhfill) Ngl.draw(rainhist) Ngl.draw(temptmsz) Ngl.frame(wks) Ngl.end()
plot.append(Ngl.contour(wks, varMPac, resCS)) resCS.tiMainString = "Atlantic meridional overturning" plot.append(Ngl.contour(wks, varMAtl, resCS)) #resCS.tiMainString = "Pacific and Indian meridional overturning" #plot.append(Ngl.contour(wks,varNPac,resCS)) #resCS.tiMainString = "Atlantic meridional overturning" #plot.append(Ngl.contour(wks,varNAtl,resCS)) resCS.tiMainString = "Change in Pacific and Indian meridional overturning" resCS.tiYAxisString = "depth, m" setplotrange(resCS, -5, 5, 1) temp = Ngl.contour(wks, varMPac - varNPac, resCS) Ngl.add_polyline(wks, temp, np.array([0, 0]), np.array([0, 5000]), gsres) plot.append(temp) resCS.tiMainString = "Change in Atlantic meridional overturning" setplotrange(resCS, -5, 5, 1) temp = (Ngl.contour(wks, varMAtl - varNAtl, resCS)) Ngl.add_polyline(wks, temp, np.array([0, 0]), np.array([0, 5000]), gsres) plot.append(temp) nrows = 4 elif var in ["P-E", "PRECT", "EVAP", "SHFLX"]: resMP = Ngl.Resources() resMP = initcontourplot(resMP, plotstartlat, plotstartlon, plotendlat, plotendlon, lats.values, lons) resMP.mpCenterLonF = 0.
# # add specific out line # # attribute of polyline lnres = Ngl.Resources() lnres.gsLineColor = "red" lnres.gsLineThicknessF = 6.0 # 3x as thick lnres.gsLineDashPattern = 0 # china east lonCN = [112, 122] latCN = [22, 37] cnEast_bndry_lon = np.ravel([lonCN[0], lonCN[0], lonCN[1], lonCN[1], lonCN[0]]) cnEast_bndry_lat = np.ravel([latCN[0], latCN[1], latCN[1], latCN[0], latCN[0]]) lnid = Ngl.add_polyline(wks, plot, cnEast_bndry_lon, cnEast_bndry_lat, lnres) # USA east lonUSA = [-90, -80] latUSA = [30, 45] USAEast_bndry_lon = np.ravel( [lonUSA[0], lonUSA[0], lonUSA[1], lonUSA[1], lonUSA[0]]) USAEast_bndry_lat = np.ravel( [latUSA[0], latUSA[1], latUSA[1], latUSA[0], latUSA[0]]) lnid = Ngl.add_polyline(wks, plot, USAEast_bndry_lon, USAEast_bndry_lat, lnres) # EUR west lonEUR = [-1, 14] latEUR = [44, 54] EURwest_bndry_lon = np.ravel( [lonEUR[0], lonEUR[0], lonEUR[1], lonEUR[1], lonEUR[0]])
def plot_psiyr(wks,data,vx,vy,xlab='Latitude [deg N]',ylab = 'y',\ vsurf=[],hei=0.1,ylon=True,xon=False,lbar=False,flipy=False,\ vpx=0.15,vpy=0.8,lsmooth=False): """ Plots meridional overturning stream functions Usage: plot_psiyr(wks,data,vx,vy,xlab='Latitude',ylab='y',vsurf=np.array([]),\ hei=0.15,ylon=True,xon=True,lbar=True,flipy=False) Input: wks - Workstation ID data - 2D matrix. Can be several matrices in a list vx - Latitude vector vy - y-vector. Can be several in a list Optional: xlab - Title for x-axis ylab - Title for y-axis vsurf - Vector of surface values to draw in hei - Height of plot(s) ylon - Turn on y labels on left side (else right) xon - Turn on x labels on bottom lbar - Turn on colorbar Output: None """ ## res = Ngl.Resources() res.wkColorMap = 'ViBlGrWhYeOrRe' Ngl.set_values(wks,res) print ' Plotting overturning stream functions in (y,r) coordinates' print lbar if ( isinstance(data,list) ): nplots = len(data) else: nplots = 1 data = [data] vy = fill_blanks(vy,nplots) ylab = fill_blanks(ylab,nplots) vsurf = fill_blanks(vsurf,nplots) ylon = fill_blanks(ylon,nplots) xon = fill_blanks(xon,nplots) lbar = fill_blanks(lbar,nplots) lbar[0] = True flipy = fill_blanks(flipy,nplots) hei = max([0.8/(nplots+1),hei]) wth = min([0.7,hei * 4]) vpy = 0.9 - hei * np.arange(0,nplots+1) ## ## Color levels for y-r stream functions ## colour_levels = np.arange(-190,210,20) for jn in range(0,nplots): zplot = data[jn] res = Ngl.Resources() res.nglMaximize = False res.nglPaperOrientation = 'Portrait' res.nglFrame = False res.nglDraw = False res.cnFillOn = True res.cnLinesOn = True res.cnLineLabelsOn = False res.cnLineLabelDensityF = 2 res.cnLineLabelBackgroundColor = -1 res.cnLevelSelectionMode = 'ExplicitLevels' res.cnLevels = colour_levels res.sfXArray = vx res.sfYArray = vy[jn] res.vpXF = vpx res.vpWidthF = wth res.vpYF = vpy[jn] res.vpHeightF = hei ## ## Axis ## res.tiYAxisFontHeightF = 0.012 res.tiYAxisString = ylab[jn] res.tiXAxisString = xlab if( ylon[jn] == True ): res.tiYAxisSide = 'Left' res.tmYLLabelsOn = True res.tmYRLabelsOn = False res.tmYLLabelFontHeightF = 0.012 else: res.tiYAxisSide = 'Right' res.tmYLLabelsOn = False res.tmYRLabelsOn = True res.tmYRLabelFontHeightF = 0.012 if( xon[jn] == True ): res.tiXAxisOn = True res.tmXBLabelsOn = True res.tiXAxisFontHeightF = 0.012 res.tmXBLabelFontHeightF = 0.012 else: res.tiXAxisOn = False res.tmXBLabelsOn = False ## ## Labelbar ## if( lbar[jn] == True ): res.lbTitleString = 'Sverdrup (10~S~9~N~kg/s)' res.lbLabelFontHeightF = 0.012 res.lbTitleFontHeightF = 0.015 res.lbLabelBarOn = True res.lbOrientation = 'Horizontal' res.pmLabelBarSide = 'Top' res.pmLabelBarDisplayMode = 'Always' res.pmLabelBarWidthF = 0.65 res.pmLabelBarHeightF = 0.07 else: res.lbLabelBarOn = False ## ## Flip y axis? ## if( flipy[jn] == True ): res.trYReverse = True else: res.trYReverse = False ## Smooth if (lsmooth==True): sigma = 2 order = 0 for ji in range(0,5): ndimage.filters.gaussian_filter(zplot[:,:],sigma,order=order,\ output=zplot[:,:],\ mode='reflect', cval=0.0) cont = Ngl.contour(wks,zplot,res) ## ## Also draw the surface values ## if (vsurf[jn].shape[0] == vx.shape[0]): lres = Ngl.Resources() lres.gsLineThicknessF = 1.5 lres.gsLineColor = 'black' lres.gsLineDashPattern = 1 line = Ngl.add_polyline(wks,cont,vx,vsurf[jn],lres) else: print ' Length of vx and vsurf do not agree ' ## And show the max/min values zmax = np.max( zplot.flatten() ) zmin = np.min( zplot.flatten() ) max_point = np.where(zplot == zmax) min_point = np.where(zplot == zmin) lmax = vx[max_point[1]][0] ymax = vy[jn][max_point[0]][0] print ' psimax = '+repr(zmax) print ' at lat = '+repr(lmax)+', y = '+repr(ymax) lmin = vx[min_point[1]][0] ymin = vy[jn][min_point[0]][0] print ' psimin = '+repr(zmin) print ' at lat = '+repr(lmin)+', y = '+repr(ymin) pres = Ngl.Resources() pres.gsMarkerColor = 'black' pres.gsMarkerThicknessF = 3. mark = Ngl.add_polymarker(wks,cont,lmax,ymax,pres) mark = Ngl.add_polymarker(wks,cont,lmin,ymin,pres) Ngl.draw(cont) #Ngl.frame(wks) flux_label = ['LH flux [PW]',\ 'DSE flux [PW]',\ 'MSE flux [PW]',\ 'Volume flux [m3/s]', 'Pressure flux [hPa]',\ 'Sensible heat flux [PW]'] jj = 0 if(1): vy2 = np.zeros((nplots,vx.shape[0])) for jc in range(0,nplots): zplot = data[jc][:,:] chi = 0.5 * (vy[jc][1:] + vy[jc][:-1]) for jj in range(0,vx.shape[0]): dpsi = zplot[1:,jj] - zplot[:-1,jj] vy2[jc,jj] = np.sum(dpsi * chi) vy2 = 10**(-3) * (-1) * vy2[:,:] # W->PW and change sign linecolors = ['blue','red','black','green','yellow','purple'] del res res = Ngl.Resources() res.nglMaximize = False res.nglPaperOrientation = 'Portrait' res.nglFrame = False res.nglDraw = True res.xyLineColors = linecolors #res.xyLineThicknesses = [2,2,2] #res.xyLabelMode = 'Custom' #res.xyExplicitLabels = ['LH','DSE','MSE'] # #if( np.mod(jc,2) == 0): # res.tiYAxisSide = 'Left' # res.tmYLLabelsOn = True # res.tmYRLabelsOn = False #else: # res.tiYAxisSide = 'Right' # res.tmYLLabelsOn = False # res.tmYRLabelsOn = True # #if( jc == icoord-1): # res.tiXAxisOn = True # res.tmXBLabelsOn = True #else: # res.tiXAxisOn = False # res.tmXBLabelsOn = False ## Axis res.tiXAxisString = 'Latitude' res.tiYAxisString = '[PW]' res.tiXAxisFontHeightF = 0.012 res.tiYAxisFontHeightF = 0.012 res.tmXBLabelFontHeightF = 0.012 res.tmYLLabelFontHeightF = 0.012 res.trYMaxF = 6. res.trYMinF = -6. res.vpXF = vpx res.vpWidthF = wth res.vpYF = vpy[-1] res.vpHeightF = hei cont = Ngl.xy(wks,vx,vy2[0:3],res) Ngl.frame(wks)
#-- create the map, but don't draw it yet map = Ngl.map(wks, res) #---------------------------------------------------------------- #-- polyline coordinates (Germany) #---------------------------------------------------------------- x = [6., 15., 15., 6., 6.] y = [47.5, 47.5, 54.5, 54.5, 47.5] #-- polyline resources plres = Ngl.Resources() plres.gsLineThicknessF = 2.0 #-- set line thickness plres.gsLineColor = "red" #-- set line color #-- add polyline to map box_1 = Ngl.add_polyline(wks, map, x, y, plres) #---------------------------------------------------------------- #-- polygon coordinates (Australia) #---------------------------------------------------------------- x = [110., 160., 160., 110., 110.] y = [-45., -45., -10., -10., -45.] #-- polygon resources pgres = Ngl.Resources() pgres.gsFillColor = "green" #-- fill color pgres.gsFillOpacityF = 0.3 #-- set opacity of polygon #-- add filled polygon to map gon_1 = Ngl.add_polygon(wks, map, x, y, pgres)
def plot_power(Pow, symmetry=("symm"), source="", var1="", plotpath="./", flim=0.5, nWavePlt=20, cmin=0.05, cmax=0.55, cspc=0.05, plotxy=[1, 1], N=[1, 2]): dims = Pow.shape nplot = dims[0] FillMode = "AreaFill" # text labels abc = list(string.ascii_lowercase) # plot resources wkstype = "png" wks = ngl.open_wks(wkstype, plotpath + "SpaceTimePower_" + source + var1) plots = [] # coherence2 plot resources res = coh_resources(cmin, cmax, cspc, FillMode, flim, nWavePlt) # phase arrow resources resA = phase_resources(flim, nWavePlt) # dispersion curve resources dcres = ngl.Resources() dcres.gsLineThicknessF = 2.0 dcres.gsLineDashPattern = 0 # text box resources txres = ngl.Resources() txres.txPerimOn = True txres.txFontHeightF = 0.013 txres.txBackgroundFillColor = "Background" # panel plot resources resP = panel_resources(nplot, abc) # plot contours and phase arrows pp = 0 while pp < nplot: if nplot == 1: coh2 = Pow else: coh2 = Pow[pp, :, :] if len(symmetry) == nplot: Symmetry = symmetry[pp] else: Symmetry = symmetry res.tiMainString = source + " log10( Power(" + var1 + ")) " + Symmetry plot = ngl.contour(wks, coh2, res) (matsuno_names, textlabels, textlocsX, textlocsY) = text_labels(Symmetry) nlabel = len(textlocsX) # generate matsuno mode dispersion curves if Symmetry == "midlat": He = [3000, 7000, 10000] matsuno_modes = mp.matsuno_modes_wk_bg(he=He, n=N, latitude=0., max_wn=nWavePlt, n_wn=500, u=25) else: He = [12, 25, 50] matsuno_modes = mp.matsuno_modes_wk(he=He, n=N, latitude=0., max_wn=nWavePlt, n_wn=500) # add polylines for dispersion curves for he in matsuno_modes: df = matsuno_modes[he] wn = df.index.values for wavename in df: for matsuno_name in matsuno_names: if wavename == (matsuno_name + str(he) + "m)"): wave = df[wavename].values wnwave = wn[~np.isnan(wave)] wave = wave[~np.isnan(wave)] ngl.add_polyline(wks, plot, wnwave, wave, dcres) # add text boxes ll = 0 while ll < nlabel: ngl.add_text(wks, plot, textlabels[ll], textlocsX[ll], textlocsY[ll], txres) ll += 1 plots.append(plot) pp += 1 # panel plots ngl.panel(wks, plots, plotxy, resP) ngl.delete_wks(wks) #ngl.end() return
[res.trXMinF,res.trXMaxF,res.trXMaxF,res.trXMinF,res.trXMinF], [0.,0.,res.trYMaxF,res.trYMaxF,0.],fillres)) fillres.gsFillColor = "LightBlue" fillbox.append(Ngl.add_polygon(wks,plot, \ [res.trXMinF,res.trXMaxF,res.trXMaxF,res.trXMinF,res.trXMinF], [0.,0.,res.trYMinF,res.trYMinF,0.],fillres)) # # Draw some boxes and bars on the XY plot using calls to Ngl.add_polyline. # # First draw a thick line at Y = 0. # lineres = Ngl.Resources() lineres.gsLineThicknessF = 3. zero_line = Ngl.add_polyline(wks,plot,[res.trXMinF,res.trXMaxF], [0.,0.],lineres) # # Add the vertical green "error" bars. # time = Ngl.fspan(1,5,5) lineres.gsLineThicknessF = 2.5 lineres.gsLineColor = "DarkGreen" vlines = [] for ii in range(5): ii1 = ii + 1 vlines.append(Ngl.add_polyline(wks,plot,[ii1,ii1], [minval[ii],maxval[ii]],lineres)) vlines.append(Ngl.add_polyline(wks,plot,[ii1-.08,ii1+.08], \ [maxval[ii],maxval[ii]],lineres)) vlines.append(Ngl.add_polyline(wks,plot,[ii1-.08,ii1+.08], \
def histogram(wks, data, res): """Plot a histogram. The NumPy histogram function is used to define the histogram. Arguments: wks -- Ngl wrokstation. data -- 1D array of data to construct a histogram from. res -- Ngl resources variable. Valid resources are: """ # Define a function to compute bar locations. def bar_position(x, y, dx, ymin, bar_width_perc): """Compute the coordinates required to draw a specified bar.""" dxp = dx * bar_width_perc xbar = np.array([x, x+dxp, x+dxp, x, x]) ybar = np.array([ymin, ymin, y, y, ymin]) return xbar, ybar # Make a local copy of resources so they can be modified. res = copy(res) # Intercept and turn off draw and frame resources. These will be applied # if necessary once the histogram has been constructed. frame_on = getattr(res, 'nglFrame', True) draw_on = getattr(res, 'nglDraw', True) res.nglFrame = False res.nglDraw = False # Set default values of special resources that will not be recognised by # Ngl. resdefaults = { 'nglHistogramBarWidthPercent': 1., 'nglHistogramBinIntervals': None, 'nglHistogramNumberOfBins': 10, 'nglxHistogramRange': None, 'nglxHistogramBarColor': 0, 'nglxHistogramBarOutlineColor': 1, 'nglxHistogramDensity': True, } # Record the values of the special resources, and remove them from the # resource list. specialres = dict() for resname in resdefaults.keys(): specialres[resname] = getattr(res, resname, resdefaults[resname]) try: delattr(res, resname) except AttributeError: pass # Work out the values of histogram parameters. nbins = specialres['nglHistogramBinIntervals'] or \ specialres['nglHistogramNumberOfBins'] hrange = specialres['nglxHistogramRange'] density = specialres['nglxHistogramDensity'] # Compute the histogram with the NumPy routine. hist, binedges = np.histogram(data, bins=nbins, range=hrange, density=density) dx = binedges[1] - binedges[0] ymin = 0. # Draw up to three bars, the first and last and the tallest, if they are # different. This sets up the plot correctly. The user specified plotting # resources are respected during this process. The lines drawn here will # be covered by the histogram. xdum, ydum = list(), list() xbar, ybar = bar_position(binedges[0], hist[0], dx, ymin, # first bar specialres['nglHistogramBarWidthPercent']) xdum.append(xbar) ydum.append(ybar) if nbins > 1: xbar, ybar = bar_position(binedges[-2], hist[-1], dx, ymin, # last bar specialres['nglHistogramBarWidthPercent']) xdum.append(xbar) ydum.append(ybar) i = np.argmax(hist) if i not in (0, nbins-1): xbar, ybar = bar_position(binedges[i], hist[i], dx, ymin, # tallest bar specialres['nglHistogramBarWidthPercent']) xdum.append(xbar) ydum.append(ybar) plot = xy(wks, np.array(xdum), np.array(ydum), res) # Create resources for shading the bars and drawing outlines around them. fillres = Ngl.Resources() fillres.gsFillColor = specialres['nglxHistogramBarColor'] lineres = Ngl.Resources() lineres.gsLineColor = specialres['nglxHistogramBarOutlineColor'] # Draw the bars and their outlines. plot._histbars = list() plot._histlines = list() for bar in xrange(nbins): xbar, ybar = bar_position(binedges[bar], hist[bar], dx, ymin, specialres['nglHistogramBarWidthPercent']) plot._histbars.append(Ngl.add_polygon(wks, plot, xbar, ybar, fillres)) plot._histlines.append(Ngl.add_polyline(wks, plot, xbar, ybar, lineres)) # Apply drawing and frame advancing if they were specified in the input # resources. if draw_on: Ngl.draw(plot) if frame_on: Ngl.frame(plot) # Return a plot identifier. return plot
def plot_psirr(vpx=0.2, vpy=0.8, hei=0.4, lbar=True, xlab=1,ylab=1): ## ## Colors for hydrothermal stream functions ## ld = 550. dl = 50 res = Ngl.Resources() res.wkColorMap = 'WhiteBlue' #res.wkColorMap = 'BlueWhiteOrangeRed' Ngl.set_values(wks,res) ## ## Reverse colormap ## del res res = Ngl.Resources() cmap = Ngl.retrieve_colormap(wks) cmap[2:,:] = cmap[-1:1:-1,:] res.wkColorMap = cmap Ngl.set_values(wks,res) psi_levels = np.arange(-ld,0.,dl) if(1): if(1): del res res = Ngl.Resources() res.nglMaximize = False res.nglPaperOrientation = 'Portrait' res.nglFrame = False res.nglDraw = False res.cnFillOn = True res.cnLinesOn = True res.cnLineLabelsOn = False res.cnLineLabelDensityF = 2 res.cnLineLabelBackgroundColor = -1 res.cnLevelSelectionMode = 'ExplicitLevels' res.cnLevels = psi_levels if (lbar): res.pmLabelBarSide = 'Top' res.lbLabelBarOn = True res.lbOrientation = 'Horizontal' res.pmLabelBarDisplayMode = 'Always' res.pmLabelBarWidthF = 0.6 res.pmLabelBarHeightF = 0.03 res.pmLabelBarOrthogonalPosF = 0.07 #res.pmLabelBarParallelPosF = 1.1 res.lbTitleString = 'Sv (10~S~9~N~kg/s)' res.lbLabelFontHeightF = 0.012 res.lbTitleFontHeightF = 0.015 else: res.pmLabelBarDisplayMode = 'Never' res.sfXArray = vx res.sfYArray = vy res.trXMinF = -3 res.trXMaxF = 55 res.trYMinF = 250 res.trYMaxF = 360 res.tiXAxisString = 'Latent heat [kJ/kg]' res.tiYAxisString = 'Dry static energy [kJ/kg]' res.tiMainString = title res.tiMainOffsetYF = -0.045 res.tiMainFontHeightF = 0.015 if (xlab == 1): res.tiXAxisOn = True res.tmXBLabelsOn = True res.tiXAxisSide = 'Bottom' elif (xlab == -1): res.tiXAxisOn = True res.tmXBLabelsOn = False res.tmXTLabelsOn = True res.tiXAxisSide = 'Top' elif (xlab == 0): res.tiXAxisOn = False res.tmXBLabelsOn = False res.tmXTLabelsOn = False if (ylab == 1): res.tiYAxisOn = True res.tmYLLabelsOn = True res.tmYRLabelsOn = False res.tiYAxisSide = 'Left' elif (ylab == -1): res.tiYAxisOn = True res.tmYLLabelsOn = False res.tmYRLabelsOn = True res.tiYAxisSide = 'Right' elif (ylab == 0): res.tiYAxisOn = False res.tmYLLabelsOn = False res.tmYRLabelsOn = False res.vpWidthF = hei res.vpHeightF = hei res.vpYF = vpy res.vpXF = vpx lsmooth = False if (lsmooth): sigma = 2 order = 0 for ji in range(0,2): ndimage.filters.gaussian_filter(zplot[:,:],sigma,order=order,\ output=zplot[:,:],\ mode='reflect', cval=0.0) cont = Ngl.contour(wks,zplot[:,:],res) ## Clausius-Clapeyron line vy_cc = np.linspace(240,360,101) press = 101300. vx_cc,es = cclap(vy_cc*1000/1004.,press) vx_cc = 2.5 * 10**3 * vx_cc #ccstring = 'C-C, RH=100%' lres = Ngl.Resources() lres.gsLineDashPattern = 15 lres.gsLineLabelFontHeightF = 0.009 lres.gsLineThicknessF = 2 #lres.gsLineLabelString = ccstring line = Ngl.add_polyline(wks,cont,vx_cc,vy_cc,lres) ## MSE profile lres = Ngl.Resources() lres.gsLineDashPattern = 1 lres.gsLineThicknessF = 3 line = Ngl.add_polyline(wks,cont,vlh,vdse,lres) Ngl.draw(cont)
res.pmLabelBarParallelPosF = 0.6 #+U -D plot = Ngl.contour_map(wks, hgt_m, res) # Plot flight track # seeding time: 1250-1257 LST (0450-0457 UTC) lnres = Ngl.Resources() lnres.gsLineColor = 'white' lnres.gsLineThicknessF = 10 for i in range(len(lon) - 1): #print (time[i][0:4]) xd = [lon[i], lon[i + 1]] yd = [lat[i], lat[i + 1]] if np.int(time[i][0:4]) < 1240: lnres.gsLineColor = 'white' plt_track = Ngl.add_polyline(wks, plot, xd, yd, lnres) elif np.int(time[i][0:4]) >= 1240 and np.int(time[i][0:4]) <= 1249: lnres.gsLineColor = 'red' plt_track = Ngl.add_polyline(wks, plot, xd, yd, lnres) elif np.int(time[i][0:4]) > 1249 and np.int(time[i][0:4]) < 1258: lnres.gsLineColor = 'purple' plt_track = Ngl.add_polyline(wks, plot, xd, yd, lnres) else: lnres.gsLineColor = 'orange' plt_track = Ngl.add_polyline(wks, plot, xd, yd, lnres) #if i > 0 and \ # np.int(time[i][0:4]) == 1240 and np.int(time[i-1][0:4]) < 1240: # plt_marker = add_polymarker(wks,plot,lon[i],lat[i], \ # color='red')
taus_above_zero = numpy.take(taus, ind_above_zero) px[0::5] = (taus_above_zero - dx / 2.).astype(taus.dtype.char) px[1::5] = (taus_above_zero - dx / 2.).astype(taus.dtype.char) px[2::5] = (taus_above_zero + dx / 2.).astype(taus.dtype.char) px[3::5] = (taus_above_zero + dx / 2.).astype(taus.dtype.char) px[4::5] = (taus_above_zero - dx / 2.).astype(taus.dtype.char) py[0::5] = rain_res.trYMinF py[1::5] = numpy.take(rain03, ind_above_zero) py[2::5] = numpy.take(rain03, ind_above_zero) py[3::5] = rain_res.trYMinF py[4::5] = rain_res.trYMinF polyg = Ngl.add_polygon(wks, rainhist, px, py, pgres) # # For the outlines, we don't need the fifth point. # polyl = Ngl.add_polyline(wks, rainhist, px, py, pgres) temptmsz = Ngl.xy(wks, taus, tempht, tempsfc_res) # ---------------------- overlay, draw, and advance frame --------- Ngl.overlay(rhfill, templine) # Overlay temperature contour on rh plot. Ngl.overlay(rhfill, windlayer) # Overlay windbarbs on rh plot. Ngl.draw(rhfill) Ngl.draw(rainhist) Ngl.draw(temptmsz) Ngl.frame(wks) Ngl.end()
gsres.gsEdgesOn = True # Line will be drawn around polygon. # Polymarker resources. gsres.gsMarkerIndex = 16 # dots gsres.gsMarkerColor = "HotPink" gsres.gsMarkerSizeF = 0.014 # twice normal size # # Add primitives to plot. They will be drawn in the order # they are added, so some primitives may cover other ones. # # Be sure to use unique variable names on the left-hand side # for the Ngl.add_polyxxxx routines. # prim1 = Ngl.add_polyline(wks, xy1, xx, ymidline, gsres) prim2 = Ngl.add_polygon(wks, xy1, xsquare, ysquare, gsres) prim3 = Ngl.add_polyline(wks, xy1, xx, ytopline, gsres) prim4 = Ngl.add_polyline(wks, xy1, xx, ybotline, gsres) gsres.gsLineColor = "Green" prim5 = Ngl.add_polyline(wks, xy1, x[26:37], y[26:37], gsres) prim6 = Ngl.add_polymarker(wks, xy1, xdots, ydots, gsres) # # New Y points for second XY plot. # y = numpy.cos(3.14159 * x / 32.) # Create second XY plot, but don't draw it yet.
def popsicle_diagram(restartfile, param_file, pftcolors, stemcolor=159, file=None, title=None, xtitle=None, ytitle=None, yrange=None, colormap=None, title_charsize=0.75, aspect_ratio=None, makepng=False, png_dens=pngdens, use_wks=None, showjupyter=False): if use_wks == None: plot_type = get_workstation_type(file) wks_res = Ngl.Resources() if plot_type == 'x11': wks_res.wkPause = False elif plot_type == 'png': wks_res.wkWidth = page_width * 100 wks_res.wkHeight = page_height * 100 else: wks_res.wkPaperWidthF = page_width wks_res.wkPaperHeightF = page_height wks_res.wkOrientation = "portrait" if not colormap == None: colormap = parse_colormap(colormap) wks_res.wkColorMap = colormap wks = Ngl.open_wks(plot_type,file,wks_res) if wks < 0 and plot_type == "x11": clear_oldest_x11_window() wks = Ngl.open_wks(plot_type,file,wks_res) else: wks = use_wks resources = Ngl.Resources() #cdkif plot_type != 'png': resources.nglDraw = False #cdkif plot_type != 'png': resources.nglFrame = False if title != None: resources.tiMainString = title if xtitle != None: resources.tiXAxisString = xtitle if ytitle != None: resources.tiYAxisString = ytitle if yrange != None: resources.trYMinF = np.min(yrange) resources.trYMaxF = np.max(yrange) resources.trXMinF = 0. resources.trXMaxF = 1. resources.tiMainFontHeightF = 0.025 * title_charsize resources.tmXBMajorLengthF = 0.01 resources.tmXBMajorOutwardLengthF = 0.01 resources.tmYLMajorLengthF = 0.01 resources.tmYLMajorOutwardLengthF = 0.01 resources.tmXBMinorOn = False resources.tmYLMinorOn = False resources.tmXTOn = False resources.tmYROn = False resources.tmXBOn = False resources.tmXBLabelsOn = False if aspect_ratio != None: if aspect_ratio > 1.: resources.vpHeightF = 0.6 / aspect_ratio else: resources.vpWidthF = 0.6 * aspect_ratio resources.trXMinF = 0. resources.trXMaxF = 1. if yrange == None: yrange = [0, np.ma.max(restartfile.variables['fates_height'][:])] resources.trYMinF = np.min(yrange) resources.trYMaxF = np.max(yrange) dummies = np.ma.masked_all(3) plot = Ngl.xy(wks, dummies, dummies, resources) #### the main logic all goes here. #### # first calculate the crown areas of each cohort cohort_crownareas = carea_allom(restartfile, param_file) max_coh_per_patch = 100 max_cohorts = len(restartfile.variables['fates_CohortsPerPatch'][:]) max_patches = max_cohorts / max_coh_per_patch maxcanlev = restartfile.variables['fates_canopy_layer'][:].max() cohort_rhs = np.zeros(maxcanlev) ## iterate over patches patch_area_sofar = 0. vline_res = Ngl.Resources vline_res.gsLineThicknessF = .01 # crown_res = Ngl.Resources() crown_res.gsLineColor = "black" crown_res.gsLineThicknessF = .01 crown_res.gsEdgesOn = True crown_res.gsFillOpacityF = 0.5 # shadow_res = Ngl.Resources() shadow_res.gsFillColor = "black" shadow_res.gsEdgesOn = False # stem_res1 = Ngl.Resources() stem_res1.gsLineThicknessF = 1. stem_res1.gsEdgesOn = True stem_res1.gsLineColor = "black" # stem_res2 = Ngl.Resources() stem_res2.gsEdgesOn = False stem_res2.gsFillOpacityF = 1. # for i in range(max_patches): ## draw thin vertical line at patch lower boundary edge to delineate patches patch_lower_edge = 1.-patch_area_sofar - restartfile.variables['fates_area'][i*max_coh_per_patch]/1e4 zlx = [patch_lower_edge, patch_lower_edge] zly = [0., 1000.] Ngl.add_polyline(wks,plot, zlx, zly, vline_res) # ## iterate over cohorts for l in range(maxcanlev-1,-1,-1): shadow_res.gsFillOpacity = l * 0.5 cohort_rhs = 1. - patch_area_sofar if restartfile.variables['fates_CohortsPerPatch'][i*max_coh_per_patch] > 0: for j in range(restartfile.variables['fates_CohortsPerPatch'][i*max_coh_per_patch]-1,-1,-1): cindx = i * max_coh_per_patch + j if restartfile.variables['fates_canopy_layer'][cindx]-1 == l: rhs = cohort_rhs lhs = rhs - cohort_crownareas[cindx]/1e4 ctop = restartfile.variables['fates_height'][cindx] cbot = ctop * 0.6 crown_res.gsFillColor = pftcolors[restartfile.variables['fates_pft'][cindx]-1] px = [rhs,rhs,lhs,lhs,rhs] py = [ctop,cbot,cbot,ctop,ctop] # stem_center = (lhs + rhs) /2. stem_width = .00001 * restartfile.variables['fates_dbh'][cindx] stem_res2.gsFillColor = stemcolor sx = [stem_center+stem_width,stem_center+stem_width,stem_center-stem_width,stem_center-stem_width,stem_center+stem_width] sy = [cbot,0.,0.,cbot,cbot] Ngl.add_polyline(wks,plot,sx,sy,stem_res1) Ngl.add_polygon(wks,plot,sx,sy,stem_res2) # if l > 0: Ngl.add_polygon(wks,plot,px,py,shadow_res) # Ngl.add_polygon(wks,plot,px,py,crown_res) # cohort_rhs = lhs #if lhs < patch_lower_edge: # raise Exception # ## get cohort properties: height, upper horizontal edge, crown area, pft, canopy layer # ## draw cohort as popsicle # patch_area_sofar = patch_area_sofar + restartfile.variables['fates_area'][i*max_coh_per_patch]/1e4 if use_wks == None: Ngl.draw(plot) Ngl.frame(wks) if not file==None: Ngl.delete_wks(wks) # if makepng or showjupyter: pdf_to_png(file, density=png_dens) if jupyter_avail and showjupyter: print(' ') print('showing file '+file) display(Image(file+'.png')) else: x11_window_list.append(wks) else: return plot