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 create_rain_bar_plot(wks, rain3h_time, rain3h_sum, rain3h_res): rainhist = Ngl.xy(wks, rain3h_time, rain3h_sum, rain3h_res) dummy = rain3h_res.trYMinF * numpy.ones([len(rain3h_sum)], rain3h_sum.dtype.char) # check for bars for the first and last value on the x axis dx = min(rain3h_time[1:-1] - rain3h_time[0:-2]) rain3h_res.trXMinF = min(rain3h_time) - dx / 2. rain3h_res.trXMaxF = max(rain3h_time) + dx / 2. rainhist = Ngl.xy(wks, rain3h_time, dummy, rain3h_res) # check where the rain sum is > 0 and craw a bar for it above_zero = numpy.greater(rain3h_sum, 0.0) ind_above_zero = numpy.nonzero(above_zero) num_above = len(ind_above_zero[0]) px = numpy.zeros(5 * num_above, rain3h_time.dtype.char) py = numpy.zeros(5 * num_above, rain3h_sum.dtype.char) # bar resource pgres = Ngl.Resources() pgres.gsFillColor = "green" pgres.gsFillOpacityF = 0.75 taus_above_zero = numpy.take(rain3h_time, ind_above_zero) # create bar rectangle taus_plus = (taus_above_zero + dx / 2.).astype(rain3h_time.dtype.char) taus_minus = (taus_above_zero - dx / 2.).astype(rain3h_time.dtype.char) px[0::5] = taus_minus px[1::5] = taus_minus px[2::5] = taus_plus px[3::5] = taus_plus px[4::5] = taus_minus py[0::5] = rain3h_res.trYMinF py[1::5] = numpy.take(rain3h_sum, ind_above_zero) py[2::5] = numpy.take(rain3h_sum, ind_above_zero) py[3::5] = rain3h_res.trYMinF py[4::5] = rain3h_res.trYMinF Ngl.add_polygon(wks, rainhist, px, py, pgres) return rainhist
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
#-- 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) #---------------------------------------------------------------- #-- polygon coordinates (Greenland) #---------------------------------------------------------------- x = [-75., -10., -10., -75., -75.] #-- define polygon x-array y = [55., 55., 87., 87., 57.] #-- define polygon y-array #-- polygon resources pres = Ngl.Resources() pres.gsFillColor = "orange" #-- fill color pres.gsFillOpacityF = 0.2 #-- set opacity #-- add polygon and polyline to map gon_2 = Ngl.add_polygon(wks, map, x, y, pres) plres.gsLineColor = "darkorange" #-- set line color
def _plot_trj_marker(wks, plot, x, y, angle, res): ''' Plots a single arrow head onto the a trajectory plot pgon = _plot_trj_marker(wks, plot, x, y, angle, res) wks : The identifier returned from calling Ngl.open_wks. x,y : The X and Y coordinates of the arrow heads centre. xMarker, yMarker : X and Y coordinates in data coordinates of the marker polygon angle: angle relative to the x axis of the marker res: Resource list using following special resources: Special resources: trjArrowDirection : can be 'pos' or 'neg' to select direction of the arrows trjArrowXShapeF : Array containing the x coordinates of the arrow head relative to the heads centre. trjArrowYShapeF : Array containing the y coordinates of the arrow head relative to the heads centre. ''' # get plot centre in data coordinates xMid, yMid = [(ngl.get_float(plot, "tr" + ax + "MaxF") + ngl.get_float(plot, "tr" + ax + "MinF")) / 2. for ax in "XY"] # rotate arrow if res.trjArrowDirection == "neg": angle = angle - np.pi xMarker = copy.deepcopy(res.trjArrowXShapeF) yMarker = copy.deepcopy(res.trjArrowYShapeF) # scale marker xMarker = xMarker * res.trjArrowXScaleF * res.trjArrowSizeF + xMid yMarker = yMarker * res.trjArrowYScaleF * res.trjArrowSizeF + yMid xMarker_ndc, yMarker_ndc = ngl.datatondc(plot, xMarker, yMarker) # move centre of mass to origin xMarker_ndc, yMarker_ndc = [xMarker_ndc - np.mean(xMarker_ndc), yMarker_ndc - np.mean(yMarker_ndc)] # rotate marker xMarker_ndc, yMarker_ndc = [ np.cos(angle) * xMarker_ndc - np.sin(angle) * yMarker_ndc, np.sin(angle) * xMarker_ndc + np.cos(angle) * yMarker_ndc] # shift to final position xOffset_ndc, yOffset_ndc = ngl.datatondc(plot, x, y) xMarker_ndc += xOffset_ndc yMarker_ndc += yOffset_ndc # convert back to coordinates xMarker, yMarker = ngl.ndctodata(plot, xMarker_ndc, yMarker_ndc) # filter attributes from res for attr in dir(res): if not attr[0:2] in ["gs", "__"] or attr[0:3] == "gsn": delattr(res, attr) return ngl.add_polygon(wks, plot, xMarker, yMarker, res)
# 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. xy2 = Ngl.xy(wks, x, y, xyres)
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
res.cnMinLevelValF = -0.1#0.45#-0.1 #-- contour min. value res.cnMaxLevelValF = 2.0#1.5#2.0 #-- contour max. value res.cnLevelSpacingF = 0.1#0.05#0.1 #-- contour interval colors00 = Ngl.read_colormap_file("MPL_RdBu") ncolors00= colors00.shape[0] colors0 = colors00[np.linspace(2,ncolors00-1,int((res.cnMaxLevelValF-res.cnMinLevelValF)/res.cnLevelSpacingF),dtype=int),:] grey_color = np.expand_dims(np.array([0.85, 0.85, 0.85, 1]), axis=0) colors = np.append(grey_color,colors0[::-1,:],axis=0) res.cnFillPalette = colors#'BlWhRe' #'MPL_YlOrRd' #-- choose color map plot = [] title = 'CESM all forcing vs '+sf+' foricng~C~FWI >= p'+str(pxx)+' risk ratio' for pp in range(2,nperiods,1): print('period '+str(pp+1)) res.tiMainString = str(pyear0[pp])+'-'+str(pyear1[pp]) riskratio_cyc, lon_cyc = Ngl.add_cyclic(riskratio_ens_agree_masked[pp,:,:], lon) res.sfXArray = lon_cyc p = Ngl.contour_map(wks,riskratio_cyc,res) if pp==(nperiods-1): for rr in range(0,n_reg,1): poly_y = [df_reg['reg_N'][rr],df_reg['reg_S'][rr],df_reg['reg_S'][rr],df_reg['reg_N'][rr],df_reg['reg_N'][rr]] poly_x = [df_reg['reg_E'][rr],df_reg['reg_E'][rr],df_reg['reg_W'][rr],df_reg['reg_W'][rr],df_reg['reg_E'][rr]] poly_reg = Ngl.add_polygon(wks,p,poly_x,poly_y,gsres) plot.append(p) Ngl.panel(wks,plot,[4,1],pres) Ngl.text_ndc(wks,title,0.5,0.92,txres) Ngl.frame(wks) Ngl.delete_wks(wks)
# Use PyNIO's selection syntax to subset the lat/lon area of interest overlay_plot = Ngl.contour(wks, u['time|i1 lat|-30:30 lon|-120:120'], ores) # Overlay the contour plot on the contour/map plot Ngl.overlay(base_plot, overlay_plot) # Drawing the base plot draws both plots Ngl.draw(base_plot) Ngl.frame(wks) # Create the contour/plot again, but with no transparency del bres.cnFillOpacityF plot = Ngl.contour_map(wks, u[1, :, :], bres) # Set resources for a partially transparent polygon. gnres = Ngl.Resources() gnres.gsFillOpacityF = 0.6 # mostly opaque gnres.gsFillColor = "white" lat_box = [-30, -30, 30, 30, -30] lon_box = [-120, 120, 120, -120, -120] # Add a partially opaque filled polygon box to the filled contours gsid = Ngl.add_polygon(wks, plot, lon_box, lat_box, gnres) # This draws the filled contours with the partially opaque box on top. Ngl.draw(plot) Ngl.frame(wks) Ngl.end()
#************************************************* plres = Ngl.Resources() # resources for polylines plres.gsLineColor = "navyblue" plres.gsLineThicknessF = 2.0 # default is 1.0 plres.gsSegments = segments[:, 0] # This can be slow. Need to investigate. lnid = Ngl.add_polyline(wks, plot, lon, lat, plres) Ngl.draw(plot) # This draws map and attached polylines Ngl.frame(wks) # Advance frame. # Second frame: filled polygons plot = Ngl.map(wks, res) # Just create map, don't draw it. colors = ["antiquewhite3","brown3","navyblue","orange",\ "cadetblue2","tan1","forestgreen","royalblue",\ "darkslategray4","sandybrown","plum3","lemonchiffon",\ "palegreen","khaki3","slateblue4","yellow","violetred",\ "wheat1","purple","mediumspringgreen","peachpuff2",\ "orchid4"] plres.gsColors = colors gnid = Ngl.add_polygon(wks, plot, lon, lat, plres) Ngl.draw(plot) # This draws map and attached polygons Ngl.frame(wks) # Advance frame. Ngl.end()
gscolors[varM >= varMax] = colors[(nlevs-1)+2] #-- set color index for cells greater than levels[nlevs-1] gscolors[np.nonzero(varM.mask)] = 20 #-- set color index for missing values #-- set polygon resources pgres = Ngl.Resources() pgres.gsEdgesOn = True #-- draw the edges pgres.gsFillIndex = 0 #-- solid fill pgres.gsLineColor = 'black' #-- edge line color pgres.gsLineThicknessF = 0.7 #-- line thickness pgres.gsColors = gscolors #-- use color array pgres.gsSegments = range(0,len(vlon[:,0])*3,3) #-- define segments array x1d, y1d = np.ravel(vlon), np.ravel(vlat) #-- convert to 1D-arrays #-- add polygons to map polyg = Ngl.add_polygon(wks1,map,x1d,y1d,pgres) #-- add a labelbar lbres = Ngl.Resources() lbres.vpWidthF = 0.85 lbres.vpHeightF = 0.15 lbres.lbOrientation = 'Horizontal' lbres.lbFillPattern = 'SolidFill' lbres.lbMonoFillPattern = 21 #-- must be 21 for color solid fill lbres.lbMonoFillColor = False #-- use multiple colors lbres.lbFillColors = colors #-- indices from loaded colormap lbres.lbBoxCount = len(colormap[colors,:]) lbres.lbLabelFontHeightF= 0.014 lbres.lbLabelAlignment = 'InteriorEdges' lbres.lbLabelStrings = labels
gscolors[varM >= varMax] = nlevs+1 #-- set color index for cells greater than levels[nlevs-1] gscolors[np.nonzero(varM.mask)] = -1 #-- set color index for missing locations #-- set polygon resources pgres = Ngl.Resources() pgres.gsEdgesOn = True #-- draw the edges pgres.gsFillIndex = 0 #-- solid fill pgres.gsLineColor = 'black' #-- edge line color pgres.gsLineThicknessF = 0.7 #-- line thickness pgres.gsColors = colormap[gscolors,:] #-- use color array pgres.gsSegments = range(0,len(vlon[:,0])*3,3) #-- define segments array for fast draw lon1d, lat1d = np.ravel(vlon), np.ravel(vlat) #-- convert to 1D-arrays #-- add polygons to map polyg = Ngl.add_polygon(wks,map,lon1d,lat1d,pgres) #-- add a labelbar lbres = Ngl.Resources() lbres.vpWidthF = 0.85 lbres.vpHeightF = 0.15 lbres.lbOrientation = 'Horizontal' lbres.lbFillPattern = 'SolidFill' lbres.lbMonoFillPattern = 21 #-- must be 21 for color solid fill lbres.lbMonoFillColor = False #-- use multiple colors lbres.lbFillColors = colormap lbres.lbLabelFontHeightF= 0.014 lbres.lbLabelAlignment = 'InteriorEdges' lbres.lbLabelStrings = labels lb = Ngl.labelbar_ndc(wks,nlevs+1,labels,0.1,0.24,lbres)
if (unemp[i] >= 0.02 and unemp[i] < 0.03): plres.gsFillColor = colors[1] if (unemp[i] >= 0.03 and unemp[i] < 0.04): plres.gsFillColor = colors[2] if (unemp[i] >= 0.04): plres.gsFillColor = colors[3] startSegment = geometry[i][geom_segIndex] numSegments = geometry[i][geom_numSegs] lines = [] for seg in range(startSegment, startSegment+numSegments): startPT = segments[seg, segs_xyzIndex] endPT = startPT + segments[seg, segs_numPnts] - 1 lines.append(Ngl.add_polygon(wks, plot, lon[startPT:endPT], \ lat[startPT:endPT], plres)) segNum = segNum + 1 Ngl.draw(plot) # Make a labelbar... labels = [ "1", "2", "3", "4" ] lres = Ngl.Resources() lres.vpWidthF = 0.50 # location lres.vpHeightF = 0.05 # " " lres.lbPerimOn = False # Turn off perimeter. lres.lbOrientation = "Horizontal" # Default is vertical. lres.lbLabelAlignment = "BoxCenters" # Default is "BoxCenters". lres.lbFillColors = colors lres.lbMonoFillPattern = True # Fill them all solid.
res.tiYAxisFontHeightF = 0.01 res.tiYAxisOffsetXF = -.017 res.xyLineColor = "transparent" plot = Ngl.xy(wks,range(1,6),arr,res) # # Fill area above Y=0 pink, and below Y=0 light blue. # fillres = Ngl.Resources() fillbox = [] fillres.gsFillColor = "pink" fillbox.append(Ngl.add_polygon(wks,plot, \ [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],
# pgres = Ngl.Resources() pgres.gsFillColor = "green" 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)
gscolors[varM >= varMax] = nlevs+1 #-- set color index for cells greater than levels[nlevs-1] gscolors[np.nonzero(varM.mask)] = -1 #-- set color index for missing locations #-- set polygon resources pgres = Ngl.Resources() pgres.gsEdgesOn = True #-- draw the edges pgres.gsFillIndex = 0 #-- solid fill pgres.gsLineColor = 'black' #-- edge line color pgres.gsLineThicknessF = 0.7 #-- line thickness pgres.gsColors = colormap[gscolors,:] #-- use color array pgres.gsSegments = range(0,len(vlon[:,0])*3,3) #-- define segments array for fast draw lon1d, lat1d = np.ravel(vlon), np.ravel(vlat) #-- convert to 1D-arrays #-- add polygons to map polyg = Ngl.add_polygon(wks,map,lon1d,lat1d,pgres) #-- add a labelbar lbres = Ngl.Resources() lbres.vpWidthF = 0.85 lbres.vpHeightF = 0.15 lbres.lbOrientation = 'Horizontal' lbres.lbFillPattern = 'SolidFill' lbres.lbMonoFillPattern = 21 #-- must be 21 for color solid fill lbres.lbMonoFillColor = False #-- use multiple colors lbres.lbFillColors = colormap lbres.lbLabelFontHeightF= 0.014 lbres.lbLabelAlignment = 'InteriorEdges' lbres.lbLabelStrings = labels lb = Ngl.labelbar_ndc(wks,nlevs+1,labels,0.1,0.24,lbres)
res.tiYAxisFontHeightF = 0.01 res.tiYAxisOffsetXF = -.017 res.xyLineColor = "transparent" plot = Ngl.xy(wks, list(range(1, 6)), arr, res) # # Fill area above Y=0 pink, and below Y=0 light blue. # fillres = Ngl.Resources() fillbox = [] fillres.gsFillColor = "pink" fillbox.append(Ngl.add_polygon(wks,plot, \ [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.],
#-- set polygon resources pgres = Ngl.Resources() pgres.gsEdgesOn = True #-- draw the edges pgres.gsFillIndex = 0 #-- solid fill pgres.gsLineColor = 'black' #-- edge line color pgres.gsLineThicknessF = 0.7 #-- line thickness pgres.gsColors = gscolors #-- use color array pgres.gsSegments = list(range(0, len(vlon[:, 0]) * 3, 3)) #-- define segments array x1d, y1d = np.ravel(vlon), np.ravel(vlat) #-- convert to 1D-arrays #-- add polygons to map polyg = Ngl.add_polygon(wks1, map, x1d, y1d, pgres) #-- add a labelbar lbres = Ngl.Resources() lbres.vpWidthF = 0.85 lbres.vpHeightF = 0.15 lbres.lbOrientation = 'Horizontal' lbres.lbFillPattern = 'SolidFill' lbres.lbMonoFillPattern = 21 #-- must be 21 for color solid fill lbres.lbMonoFillColor = False #-- use multiple colors lbres.lbFillColors = colors #-- indices from loaded colormap lbres.lbBoxCount = len(colormap[colors, :]) lbres.lbLabelFontHeightF = 0.014 lbres.lbLabelAlignment = 'InteriorEdges' lbres.lbLabelStrings = labels
def simple_grid_fill(xaxis, yaxis, grid, cfg): """ Generate a simple plot, but we already have the data! """ tmpfp = tempfile.mktemp() rlist = Ngl.Resources() if cfg.has_key("wkColorMap"): rlist.wkColorMap = cfg['wkColorMap'] #rlist.wkOrientation = "landscape" # Create Workstation wks = Ngl.open_wks( "ps",tmpfp,rlist) if cfg.has_key("_conus"): res = conus() elif cfg.get("_midwest", False): res = midwest() elif cfg.get("_louisiana", False): res = louisiana2() else: res = iowa2() if cfg.has_key("_MaskZero"): mask = numpy.where( grid <= 0.01, True, False) grid = numpy.ma.array(grid, mask=mask) for key in cfg.keys(): if key == 'wkColorMap' or key[0] == "_": continue setattr(res, key, cfg[key]) res.sfXArray = xaxis res.sfYArray = yaxis # Generate Contour contour = Ngl.contour_map(wks,grid,res) # if cfg.has_key("_showvalues") and cfg['_showvalues']: # txres = Ngl.Resources() # txres.txFontHeightF = 0.012 # for i in range(len(xaxis)): # if cfg.has_key("_valuemask") and cfg['_valuemask'][i] is False: # continue # Ngl.add_text(wks, contour, cfg["_format"] % vals[i], # lons[i], lats[i],txres) if cfg.has_key('_drawx'): for lo, la in zip(cfg['_drawx'], cfg['_drawy']): #print 'Adding Polygon!' plres = Ngl.Resources() plres.gsEdgesOn = True plres.gsEdgeColor = "black" plres.gsFillColor = -1 Ngl.add_polygon(wks, contour, lo, la, plres) if cfg.get("_showvalues", False): txres = Ngl.Resources() txres.txFontHeightF = 0.012 (rows, cols) = numpy.shape(xaxis) for row in range(rows): for col in range(cols): if xaxis[row,col] > res.mpMinLonF and xaxis[row,col] < res.mpMaxLonF and yaxis[row,col] > res.mpMinLatF and yaxis[row,col] < res.mpMaxLatF: Ngl.add_text(wks, contour, cfg["_format"] % grid[row, col], xaxis[row, col], yaxis[row, col], txres) Ngl.draw(contour) if cfg.get('_watermark', True): watermark(wks) manual_title(wks, cfg) Ngl.frame(wks) del wks return tmpfp
print "++ min/max vlat: ", np.min(vlat), np.max(vlat) #-- set polygon resources pgres = Ngl.Resources() pgres.gsEdgesOn = True #-- draw the edges pgres.gsFillIndex = 0 #-- solid fill pgres.gsLineColor = "black" #-- edge line color pgres.gsLineThicknessF = 0.7 #-- line thickness pgres.gsColors = gscolors #-- use color array pgres.gsSegments = range(0,len(vlon[:,0])*3,3) #-- define segments array x1d = np.ravel(vlon) #-- 1D-array y1d = np.ravel(vlat) #-- 1D-array #-- draw polygons polyg = Ngl.add_polygon(wks1,map,x1d,y1d,pgres) #-- add polygons to map #-- labelbar resources lbres = Ngl.Resources() lbres.vpWidthF = 0.85 #-- labelbar width lbres.vpHeightF = 0.15 #-- labelbar height lbres.lbOrientation = "Horizontal" #-- labelbar orientation lbres.lbFillPattern = "SolidFill" #-- labelbar box fill style lbres.lbMonoFillPattern = 21 #-- labelbar box fill pattern lbres.lbMonoFillColor = False #-- use multiple colors lbres.lbFillColors = colors #-- set color array lbres.lbLabelFontHeightF = 0.014 #-- labelbar label font size lbres.lbLabelAlignment = "InteriorEdges" #-- draw labels between boxes #-- add labelbar to workstation lb = Ngl.labelbar_ndc(wks1,nlevels,labels,0.1,0.2,lbres)
# pgres = Ngl.Resources() pgres.gsFillColor = "green" 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)
if (unemp[i] >= 0.02 and unemp[i] < 0.03): plres.gsFillColor = colors[1] if (unemp[i] >= 0.03 and unemp[i] < 0.04): plres.gsFillColor = colors[2] if (unemp[i] >= 0.04): plres.gsFillColor = colors[3] startSegment = geometry[i][geom_segIndex] numSegments = geometry[i][geom_numSegs] lines = [] for seg in range(startSegment, startSegment+numSegments): startPT = segments[seg, segs_xyzIndex] endPT = startPT + segments[seg, segs_numPnts] - 1 lines.append(Ngl.add_polygon(wks, plot, lon[startPT:endPT], \ lat[startPT:endPT], plres)) segNum = segNum + 1 Ngl.draw(plot) # Make a labelbar... labels = [ "1", "2", "3", "4" ] lres = Ngl.Resources() lres.vpWidthF = 0.50 # location lres.vpHeightF = 0.05 # " " lres.lbPerimOn = False # Turn off perimeter. lres.lbOrientation = "Horizontal" # Default is vertical. lres.lbLabelAlignment = "BoxCenters" # Default is "BoxCenters". lres.lbFillColors = colors lres.lbMonoFillPattern = True # Fill them all solid.
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