def save_ps_map(self, title, data, labels_on=True): """ Directly create a PS file of data with filename=title. Assumes normalized data between 0 and 1. INPUT: title a string describing the dataset data a numpy array containing the map to be drawn """ # Change the levels of contouring resources = self.resources resources.cnLevelSelectionMode = "ExplicitLevels" # Define own levels. resources.cnLevels = np.arange(0., 1., 0.05) wks_type = "ps" wks = Ngl.open_wks(wks_type, title, resources) if labels_on: resources.lbTitleString = title # Reshape for visualization on the sphere data.shape = (self.grid.grid_size()["lat"], self.grid.grid_size()["lon"]) # Generate map plot cmap = Ngl.contour_map(wks, data, resources) # Clear map del cmap Ngl.destroy(wks) # Clean up del resources Ngl.end()
def save(self,filename = 'plot'): #'eps' workstation doesn't work reliably, but 'ps' is OK weps = Ngl.open_wks('ps',filename,self.WorkstationResources) Ngl.change_workstation(self.plot,weps) Ngl.draw(self.plot) Ngl.change_workstation(self.plot,self.workstation) Ngl.destroy(weps)
def skewt(fname, p, tc, tdc, z, wspd, wdir, saveas='pdf', barbstride=20): wks = Ngl.open_wks(saveas,fname) dataOpts = Ngl.Resources() # Options describing """ # data and plotting. dataOpts.sktHeightWindBarbsOn = True # Plot wind barbs at # height levels. dataOpts.sktPressureWindBarbComponents = "SpeedDirection" # Wind speed and # dir [else: u,v]. dataOpts.sktHeightWindBarbPositions = hght # height of wind reports dataOpts.sktHeightWindBarbSpeeds = hspd # speed # [or u components] dataOpts.sktHeightWindBarbDirections = hdir # direction # [or v components] """ skewtOpts = Ngl.Resources() skewtOpts.sktHeightScaleOn = True # default is False skewtOpts.sktHeightScaleUnits = "km" # default is "feet" skewtOpts.sktColoredBandsOn = False # default is False skewtOpts.sktGeopotentialWindBarbColor = "Red" dataOpts.sktPressureWindBarbStride = barbstride skewtOpts.tiMainString = "Graw Launch WBB - Env. Instr Lab 5" # create a background skewt_bkgd = Ngl.skewt_bkg(wks, skewtOpts) # plot the darn profile... skewt_data = Ngl.skewt_plt(wks, skewt_bkgd, p, tc, tdc, z, \ wspd, wdir, dataOpts) Ngl.draw(skewt_bkgd) Ngl.draw(skewt_data) Ngl.frame(wks) Ngl.end()
def plot_using_ngl(self, field_2d = None, file_name = None): import Ngl wks_type = "png" wks = Ngl.open_wks(wks_type, "cv") res = Ngl.Resources() res.mpProjection = "Orthographic" pass
def generate_multiple_map_plots_npy(self, map_names, map_scales, title_on=True, labels_on=True): """ Method for very large datasets (RAM issues) and useful for PARALLEL code. Generates map plots from the datasets stored in the npy files and the list of titles. The data is sorted as parallel computation mixes it up. Stores the plots in the file indicated by filename in the current directory. """ # Set resources resources = self.resources # Set plot title if title_on: resources.tiMainString = self.title for k in range(len(self.map_mult_data)): # Open a workstation for every map, only wks_type = "ps" allows # multiple workstation # Sort dataset, as parallel code will mix it self.map_mult_data[k].sort() # Define own levels resources.cnLevelSelectionMode = "ExplicitLevels" resources.cnLevels = map_scales[k] wks_type = "pdf" wks = Ngl.open_wks(wks_type, map_names[k], resources) # # Generate map plots # for ititle in self.map_mult_data[k]: # Set title if labels_on: resources.lbTitleString = ititle data = np.load(str(k) + "_" + ititle + ".npy") # Reshape for visualization on the sphere data.shape = (self.grid.grid_size()["lat"], self.grid.grid_size()["lon"]) # Generate map plot cmap = Ngl.contour_map(wks, data, resources) # Clear map del cmap Ngl.destroy(wks) # Clean up for file_name in glob.glob('*.npy'): os.remove(file_name) del resources Ngl.end()
def hilo_valplot(lons, lats, highs, lows, cfg): """ Special case of having a value plot with a high and low value to plot, which is common for some climate applications """ tmpfp = tempfile.mktemp() cmap = numpy.array([[1., 1., 1.], [0., 0., 0.], [1., 0., 0.], \ [0., 0., 1.], [0., 1., 0.]], 'f') rlist = Ngl.Resources() rlist.wkColorMap = cmap #rlist.wkOrientation = "landscape" wks = Ngl.open_wks("ps", tmpfp, rlist) res = iowa() res.mpOutlineDrawOrder = "PreDraw" plot = Ngl.map(wks, res) for key in cfg.keys(): if key == 'wkColorMap' or key[0] == "_": continue setattr(res, key, cfg[key]) txres = Ngl.Resources() txres.txFontHeightF = 0.016 txres.txFontColor = "red" txres.txJust = "BottomRight" for i in range(len(lons)): Ngl.add_text(wks, plot, cfg["_format"] % highs[i], lons[i], lats[i],txres) txres = Ngl.Resources() txres.txFontHeightF = 0.016 txres.txFontColor = "blue" txres.txJust = "TopRight" for i in range(len(lons)): Ngl.add_text(wks, plot, cfg["_format"] % lows[i], lons[i], lats[i],txres) if cfg.has_key("_labels"): txres = Ngl.Resources() txres.txFontHeightF = 0.008 txres.txJust = "CenterLeft" txres.txFontColor = 1 for i in range(len(lons)): Ngl.add_text(wks, plot, cfg["_labels"][i], lons[i], lats[i],txres) watermark(wks) manual_title(wks, cfg) vpbox(wks) Ngl.draw(plot) Ngl.frame(wks) del wks return tmpfp
def plot(c): r = resource() r.trYReverse = c.reverseY r.trXReverse = c.reverseX r.trXLog = c.XlogAxis r.trYLog = c.YlogAxis # #Line styles r.xyLineColors = lineColors r.xyLineThicknesses = lineThickness #Plot title r.tiMainString = c.PlotTitle #Axis labels (ToDo: add defaults) #X and Y axis labels r.tiXAxisString = c.Xlabel r.tiYAxisString = c.Ylabel if c.switchXY: r.tiXAxisString,r.tiYAxisString = r.tiYAxisString,r.tiXAxisString # Legends, for multicurve plot legends = [] for id in c.listVariables(): if not id == c.Xid: if len(c.label[id]) > 0: legends.append(c.label[id]) else: legends.append(id) #ToDo: Add option to skip legends #Legends are redundant if there's only one curve if len(legends) > 1: r.pmLegendDisplayMode = "Always" r.xyExplicitLegendLabels = legends # #Suppress line drawing and just plot symbol for scatter plot curves r.xyMarkers = plotSymbols r.xyMarkerColors = lineColors r.xyMarkerSizeF = .01 r.xyMarkLineModes = [] for id in c.listVariables(): if not id == c.Xid: if c.scatter[id]: r.xyMarkLineModes.append('Markers') else: r.xyMarkLineModes.append('Lines') # w = Ngl.open_wks('x11','Climate Workbook') if c.switchXY: plot = Ngl.xy(w,c.Y(),c.X(),r) else: plot = Ngl.xy(w,c.X(),c.Y(),r) # #Now draw the plot r.nglDraw = True Ngl.panel(w,[plot],[1,1],r) return plotObj(w,plot) #So that user can delete window or save plot
def generate_multiple_map_plots(self, map_names, map_scales, title_on=True, labels_on=True): """ Generate map plots from the datasets stored in the :attr:`map_data` list of dictionaries. Stores the plots in the file indicated by filename in the current directory. """ for k in xrange(len(self.map_mult_data)): # Set resources resources = self.resources # Set plot title if title_on: resources.tiMainString = self.title # Open a workstation for every map, only wks_type = "ps" allows # multiple workstations # Define own levels resources.cnLevelSelectionMode = "ExplicitLevels" resources.cnLevels = map_scales[k] wks_type = "pdf" wks = Ngl.open_wks(wks_type, map_names[k], resources) # # Generate map plots # for dataset in self.map_mult_data[k]: # Set title if labels_on: resources.lbTitleString = dataset["title"] # Reshape for visualization on the sphere dataset["data"].shape = (self.grid.grid_size()["lat"], self.grid.grid_size()["lon"]) # Generate map plot cmap = Ngl.contour_map(wks, dataset["data"], resources) # Clear map del cmap Ngl.destroy(wks) # Clean up del resources Ngl.end()
def contour(A,**kwargs): #The following allows an expert user to pass #Ngl options directly to the plotter. #ToDo: Note that #options explicitly specified later will over-ride #what the user specified. This should be fixed, #by checking for things already specified. We should #also allow for using this resource to specify a color #map. if 'resource' in kwargs.keys(): r = kwargs['resource'] else: r = Dummy() # r.cnFillOn = True #Uses color fill # Set axes if they have been specified # as keyword arguments if 'x' in kwargs.keys(): r.sfXArray = kwargs['x'] if 'y' in kwargs.keys(): r.sfYArray = kwargs['y'] # # Now create the plot rw = Dummy() #Set the color map if 'colors' in kwargs.keys(): if (kwargs['colors'] == 'gray') or (kwargs['colors'] == 'grey') : #Set the default greyscale rw.wkColorMap = 'gsdtol' else: rw.wkColorMap = kwargs['colors'] else: #Default rainbow color table rw.wkColorMap = "temp1" w = Ngl.open_wks('x11','Climate Workbook',rw) r.nglDraw = False r.nglFrame = False plot = Ngl.contour(w,A,r) #Now draw the plot r.nglDraw = True Ngl.panel(w,[plot],[1,1],r) return plotObj(w,plot,rw) #So user can delete or save plot
def generate_map_plots(self, file_name, title_on=True, labels_on=True): """ Generate and save map plots. Store the plots in the file indicated by ``file_name`` in the current directory. Map plots are stored in a PDF file, with each map occupying its own page. :arg str file_name: The name for the PDF file containing map plots. :arg bool title_on: Determines, whether main title is plotted. :arg bool labels_on: Determines whether individual map titles are plotted. """ # Set resources resources = self.resources # Set plot title if title_on: resources.tiMainString = self.title # Open a workstation, display in X11 window # Alternatively wks_type = "ps", wks_type = "pdf" or wks_type = "x11" wks_type = "pdf" wks = Ngl.open_wks(wks_type, file_name, resources) # # Generate map plots # for dataset in self.map_data: # Set title if labels_on: resources.lbTitleString = dataset["title"] # Generate map plot cmap = Ngl.contour_map(wks, dataset["data"], resources) # Clean up del cmap del resources Ngl.end()
cmap = numpy.array([[1.00,1.00,1.00],[0.00,0.00,0.00],[1.00,0.00,0.00],\ [0.00,1.00,0.00],[0.00,0.00,1.00],[1.00,1.00,0.00],\ [0.00,1.00,1.00],[1.00,0.00,1.00],[0.70,0.30,0.30],\ [0.50,1.00,1.00],[0.80,0.80,0.20],[1.00,1.00,0.50],\ [0.50,0.00,0.80],[1.00,0.50,0.00],[0.30,0.30,0.80],\ [0.50,1.00,0.00],[0.40,0.00,0.40],[0.50,1.00,0.50],\ [0.80,0.20,0.80],[0.00,0.60,0.00],[0.50,0.50,1.00],\ [1.00,0.00,0.50],[0.50,0.50,0.00],[0.00,0.50,0.50],\ [1.00,0.50,0.50],[0.00,1.00,0.50],[0.80,0.80,0.80],\ [0.20,0.80,0.00],[0.55,0.55,0.00],[0.00,0.70,0.00],\ [0.62,0.62,0.00],[0.25,0.25,0.25]], 'f') rlist = Ngl.Resources() rlist.wkColorMap = cmap wks_type = "ps" wks = Ngl.open_wks (wks_type,"clmdiv1",rlist) # # Create the plot. # # # Map resources. # res = Ngl.Resources() res.mpLambertParallel1F = 33.0 # two parallels res.mpLambertParallel2F = 45.0 res.mpLambertMeridianF = -95.0 # central meridian res.mpLimitMode = "LatLon" # limit map via lat/lon res.mpMinLatF = 24.0 # map area
#-- open file and read variables f = Nio.open_file(diri + fname, "r") #-- open data file temp = f.variables["tsurf"][0, ::-1, :] #-- first time step, reverse latitude u = f.variables["u10"][0, ::-1, :] #-- first time step, reverse latitude v = f.variables["v10"][0, ::-1, :] #-- first time step, reverse latitude lat = f.variables["lat"][::-1] #-- reverse latitudes lon = f.variables["lon"][:] #-- all longitudes nlon = len(lon) #-- number of longitudes nlat = len(lat) #-- number of latitudes #-- open a workstation wkres = Ngl.Resources() #-- generate an resources object for workstation wks_type = "x11" #-- graphics output type wks = Ngl.open_wks(wks_type, "plot_vector_PyNGL", wkres) #-- create 1st plot: vectors on global map res = Ngl.Resources() res.vfXCStartV = float(lon[0]) #-- minimum longitude res.vfXCEndV = float(lon[len(lon[:]) - 1]) #-- maximum longitude res.vfYCStartV = float(lat[0]) #-- minimum latitude res.vfYCEndV = float(lat[len(lat[:]) - 1]) #-- maximum latitude res.tiMainString = "~F25~Wind velocity vectors" #-- title string res.tiMainFontHeightF = 0.024 #-- decrease title font size res.mpLimitMode = "Corners" #-- select a sub-region res.mpLeftCornerLonF = float(lon[0]) #-- left longitude value res.mpRightCornerLonF = float(lon[len(lon[:]) - 1]) #-- right longitude value res.mpLeftCornerLatF = float(lat[0]) #-- left latitude value
# # Import Ngl support functions. # import Ngl import os # # Open the netCDF file. # file = Nio.open_file(os.path.join(Ngl.pynglpath("data"),"cdf","pop.nc")) # # Open a workstation. # wks_type = "png" wks = Ngl.open_wks(wks_type,"streamline1") # # Get the u/v and lat/lon variables. # urot = file.variables["urot"] vrot = file.variables["vrot"] lat2d = file.variables["lat2d"] lon2d = file.variables["lon2d"] # # Set up resource list. # resources = Ngl.Resources() #
# mask_specs = \ ["algeria","angola","angola-exclave-called-cabinda","benin","botswana", \ "burundi","cameroon","central-african-republic","chad","congo","djibouti", \ "egypt","equatorial-guinea","ethiopia","gabon","gambia","ghana","guinea", \ "guinea-bissau","ivory-coast","kenya","lesotho","liberia","libya", \ "madagascar","malawi","mali","mauritania","mauritius","morocco", \ "mozambique","namibia","niger","nigeria","rwanda","senegal","sierra-leone",\ "somalia","south-africa","sudan","swaziland","tanzania","togo","tunisia", \ "uganda","upper-volta","western-sahara","zaire","zambia","zimbabwe"] # # Open a workstation. # wks_type = "ps" wks = Ngl.open_wks(wks_type,"cn12p") dirc = Ngl.ncargpath("data") z = Ngl.asciiread(dirc+"/asc/cn12n.asc",len_dims,"float") resources = Ngl.Resources() resources.sfXCStartV = -18.0 resources.sfXCEndV = 52.0 resources.sfYCStartV = -35.0 resources.sfYCEndV = 38.0 resources.vpXF = 0.1 resources.mpMaskAreaSpecifiers = mask_specs resources.mpFillAreaSpecifiers = fill_specs resources.pmLabelBarDisplayMode = "always" Ngl.contour_map(wks,z[:,:],resources)
# # Read the lat/lon/ele/depth arrays to numpy.arrays. # lat = cfile.variables["lat"][:] lon = cfile.variables["lon"][:] ele = cfile.variables["ele"][:] depth = cfile.variables["depth"][:] # # Select a colormap and open a PostScript workstation. # rlist = Ngl.Resources() rlist.wkColorMap = "rainbow+gray" wks_type = "ps" wks = Ngl.open_wks(wks_type, "chkbay", rlist) # # The next set of resources will apply to the contour plot. # resources = Ngl.Resources() resources.nglSpreadColorStart = 15 resources.nglSpreadColorEnd = -2 resources.sfXArray = lon # Portion of map on which to overlay resources.sfYArray = lat # contour plot. resources.sfElementNodes = ele resources.sfFirstNodeIndex = 1 resources.cnFillOn = True
def draw_2D_plot(ptype, cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs, casedir): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) if not os.path.exists(casedir + '/2D'): os.mkdir(casedir + '/2D') _Font = 25 interp = 2 extrap = False infiles = ['' for x in range(ncases)] ncdfs = ['' for x in range(ncases)] alpha = ['A', 'B', 'C', 'D', 'E', 'F'] cunits = [''] varis = [ 'SWCF', 'LWCF', 'PRECT', 'LHFLX', 'SHFLX', 'TMQ', 'PS', 'TS', 'U10', 'CLDTOT', 'CLDLOW', 'CLDHGH', 'TGCLDLWP' ] varisobs = [ 'SWCF', 'LWCF', 'PRECT', 'LHFLX', 'SHFLX', 'PREH2O', 'PS', 'TS', 'U10', 'CLDTOT_CAL', 'CLDTOT_CAL', 'CLDTOT_CAL', 'TGCLDLWP_OCEAN' ] nvaris = len(varis) cscale = [1, 1, 86400000, 1, 1, 1, 1, 1, 1, 100, 100, 100, 1000, 1, 1, 1] cscaleobs = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # cntrs = [[0 for col in range(11)] for row in range(nvaris)] cntrs = np.zeros((nvaris, 11), np.float32) obsdataset = [ 'CERES-EBAF', 'CERES-EBAF', 'GPCP', 'ERAI', 'NCEP', 'ERAI', 'NCEP', 'ERAI', 'ERAI', 'CALIPSOCOSP', 'CALIPSOCOSP', 'CALIPSOCOSP', 'NVAP' ] plot2d = ['' for x in range(nvaris)] for iv in range(0, nvaris): # make plot for each field if (varis[iv] == 'CLDTOT' or varis[iv] == 'CLDLOW' or varis[iv] == 'CLDHGH'): cntrs[iv, :] = [2, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90] if (varis[iv] == 'LWCF'): cntrs[iv, :] = [1, 2, 5, 10, 15, 20, 25, 30, 35, 40, 45] if (varis[iv] == 'SWCF' or varis[iv] == 'FLUT'): cntrs[iv, :] = [ -40, -50, -60, -70, -80, -90, -100, -110, -120, -130, -140 ] if (varis[iv] == 'PRECT' or varis[iv] == 'QFLX'): cntrs[iv, :] = [0.5, 1.5, 3, 4.5, 6, 7.5, 9, 10.5, 12, 13.5, 15] if (varis[iv] == 'LHFLX'): cntrs[iv, :] = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110] if (varis[iv] == 'SHFLX'): cntrs[iv, :] = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110] if (varis[iv] == 'U10'): cntrs[iv, :] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] if (varis[iv] == 'TMQ'): cntrs[iv, :] = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55] if (varis[iv] == 'TGCLDLWP'): cntrs[iv, :] = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110] # Observational data if (obsdataset[iv] == 'CCCM'): if (cseason == 'ANN'): fileobs = '/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-' + cseason + '.nc' else: fileobs = '/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-2010-' + cseason + '.nc' else: if (varisobs[iv] == 'PRECT'): fileobs = filepathobs + '/GPCP_' + cseason + '_climo.nc' else: fileobs = filepathobs + obsdataset[ iv] + '_' + cseason + '_climo.nc' # infiles[im]=filepath[im]+cases[im]+'/run/'+cases[im]+'_'+cseason+'_climo.nc' inptrobs = Dataset(fileobs, 'r') latobs = inptrobs.variables['lat'][:] lonobs = inptrobs.variables['lon'][:] if (varisobs[iv] == 'U10'): B0 = inptrobs.variables[varisobs[iv]][0, :, :] B1 = inptrobs.variables['V10'][0, :, :] B = (B0 * B0 + B1 * B1) B = B * cscaleobs[iv] B = np.sqrt(B) else: B = inptrobs.variables[varisobs[iv]][0, :, :] B = B * cscaleobs[iv] #************************************************ # create plot #************************************************ plotname = casedir + '/2D/Horizontal_' + varis[iv] + '_' + cseason plot2d[iv] = 'Horizontal_' + varis[iv] + '_' + cseason wks = Ngl.open_wks(ptype, plotname) Ngl.define_colormap(wks, 'cmocean_thermal') # Ngl.define_colormap(wks,'MPL_coolwarm') # ngl_define_colormap(wks,'prcp_1') plot = [] textres = Ngl.Resources() textres.txFontHeightF = 0.02 # Size of title. textres.txFont = _Font Ngl.text_ndc(wks, varis[iv], 0.1, .97, textres) pres = Ngl.Resources() pres.nglMaximize = True pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelBottom = 0.20 pres.nglPanelTop = 0.9 pres.pmLabelBarWidthF = 0.8 pres.nglFrame = False pres.nglPanelLabelBar = True # Turn on panel labelbar pres.nglPanelLabelBarLabelFontHeightF = 0.015 # Labelbar font height pres.nglPanelLabelBarHeightF = 0.0750 # Height of labelbar pres.nglPanelLabelBarWidthF = 0.700 # Width of labelbar pres.lbLabelFont = 'helvetica-bold' # Labelbar font pres.nglPanelTop = 0.935 pres.nglPanelFigureStrings = alpha pres.nglPanelFigureStringsJust = 'BottomRight' res = Ngl.Resources() res.nglDraw = False #-- don't draw plots res.nglFrame = False res.cnFillOn = True res.cnFillMode = 'RasterFill' res.cnLinesOn = False res.nglMaximize = True res.mpFillOn = True res.mpCenterLonF = 180 res.tiMainFont = _Font res.tiMainFontHeightF = 0.025 res.tiXAxisString = '' res.tiXAxisFont = _Font res.tiXAxisFontHeightF = 0.025 res.tiYAxisString = '' res.tiYAxisFont = _Font res.tiYAxisOffsetXF = 0.0 res.tiYAxisFontHeightF = 0.025 res.tmXBLabelFont = _Font res.tmYLLabelFont = _Font res.tiYAxisFont = _Font res.vpWidthF = 0.80 # set width and height res.vpHeightF = 0.40 res.vpXF = 0.04 res.vpYF = 0.30 res.cnInfoLabelOn = False res.cnFillOn = True res.cnLinesOn = False res.cnLineLabelsOn = False res.lbLabelBarOn = False # res.vcRefMagnitudeF = 5. # res.vcMinMagnitudeF = 1. # res.vcRefLengthF = 0.04 # res.vcRefAnnoOn = True#False # res.vcRefAnnoZone = 3 # res.vcRefAnnoFontHeightF = 0.02 # res.vcRefAnnoString2 ='' # res.vcRefAnnoOrthogonalPosF = -1.0 # res.vcRefAnnoArrowLineColor = 'blue' # change ref vector color # res.vcRefAnnoArrowUseVecColor = False # res.vcMinDistanceF = .05 # res.vcMinFracLengthF = . # res.vcRefAnnoParallelPosF = 0.997 # res.vcFillArrowsOn = True # res.vcLineArrowThicknessF = 3.0 # res.vcLineArrowHeadMinSizeF = 0.01 # res.vcLineArrowHeadMaxSizeF = 0.03 # res.vcGlyphStyle = 'CurlyVector' # turn on curley vectors # res@vcGlyphStyle ='Fillarrow' # res.vcMonoFillArrowFillColor = True # res.vcMonoLineArrowColor = True # res.vcLineArrowColor = 'green' # change vector color # res.vcFillArrowEdgeColor ='white' # res.vcPositionMode ='ArrowTail' # res.vcFillArrowHeadInteriorXF =0.1 # res.vcFillArrowWidthF =0.05 #default # res.vcFillArrowMinFracWidthF =.5 # res.vcFillArrowHeadMinFracXF =.5 # res.vcFillArrowHeadMinFracYF =.5 # res.vcFillArrowEdgeThicknessF = 2.0 res.mpFillOn = False res.cnLevelSelectionMode = 'ExplicitLevels' res.cnLevels = cntrs[iv][:] for im in range(0, ncases): ncdfs[im] = './data/' + cases[im] + '_site_location.nc' infiles[im] = filepath[im] + cases[im] + '/' + cases[ im] + '_' + cseason + '_climo.nc' inptrs = Dataset(infiles[im], 'r') # pointer to file1 lat = inptrs.variables['lat'][:] nlat = len(lat) lon = inptrs.variables['lon'][:] nlon = len(lon) area = inptrs.variables['area'][:] area_wgt = np.zeros(nlat) sits = np.linspace(0, nsite - 1, nsite) ncdf = Dataset(ncdfs[im], 'r') n = ncdf.variables['n'][:] idx_cols = ncdf.variables['idx_cols'][:] if (varis[iv] == 'PRECT'): A = inptrs.variables['PRECC'][ 0, :] + inptrs.variables['PRECL'][0, :] else: A = inptrs.variables[varis[iv]][0, :] if (varis[iv] == 'FLUT'): A = inptrs.variables['FLUT'][0, :] - inptrs.variables['FLNS'][ 0, :] else: A = inptrs.variables[varis[iv]][0, :] if (varis[iv] == 'U10'): A = inptrs.variables['U10'][0, :] * inptrs.variables['U10'][ 0, :] A = np.sqrt(A) else: A = inptrs.variables[varis[iv]][0, :] A_xy = A A_xy = A_xy * cscale[iv] ncdf.close() inptrs.close() if im == 0: dsizes = len(A_xy) field_xy = [[0 for col in range(dsizes)] for row in range(ncases)] field_xy[im][:] = A_xy res.lbLabelBarOn = False if (np.mod(im, 2) == 0): res.tiYAxisOn = True else: res.tiYAxisOn = False res.tiXAxisOn = False res.sfXArray = lon res.sfYArray = lat res.mpLimitMode = 'LatLon' res.mpMaxLonF = max(lon) res.mpMinLonF = min(lon) res.mpMinLatF = min(lat) res.mpMaxLatF = max(lat) res.tiMainString = 'GLB=' + str( np.sum(A_xy[:] * area[:] / np.sum(area))) textres.txFontHeightF = 0.015 Ngl.text_ndc(wks, alpha[im] + ' ' + casenames[im], 0.3, .135 - im * 0.03, textres) p = Ngl.contour_map(wks, A_xy, res) plot.append(p) # observation # res.nglLeftString = obsdataset[iv] # res@lbLabelBarOn = True # res@lbOrientation = 'vertical' # vertical label bars res.lbLabelFont = _Font res.tiYAxisOn = True res.tiXAxisOn = True res.tiXAxisFont = _Font rad = 4.0 * np.arctan(1.0) / 180.0 re = 6371220.0 rr = re * rad dlon = abs(lonobs[2] - lonobs[1]) * rr dx = dlon * np.cos(latobs * rad) jlat = len(latobs) dy = np.zeros(jlat, dtype=float) # close enough dy[0] = abs(lat[2] - lat[1]) * rr dy[1:jlat - 2] = abs(lat[2:jlat - 1] - lat[0:jlat - 3]) * rr * 0.5 dy[jlat - 1] = abs(lat[jlat - 1] - lat[jlat - 2]) * rr area_wgt = dx * dy # is_SE = False sum1 = 0 sum2 = 0 for j in range(0, jlat - 1): for i in range(0, len(lonobs) - 1): if (np.isnan(B[j][i]) != '--'): sum1 = sum1 + area_wgt[j] * B[j][i] sum2 = sum2 + area_wgt[j] glb = sum1 / sum2 res.sfXArray = lonobs res.sfYArray = latobs res.mpLimitMode = 'LatLon' res.mpMaxLonF = max(lonobs) res.mpMinLonF = min(lonobs) res.mpMinLatF = min(latobs) res.mpMaxLatF = max(latobs) res.tiMainString = 'GLB=' + str(glb) p = Ngl.contour_map(wks, B, res) if (iv == 0): poly_res = Ngl.Resources() poly_res.gsMarkerIndex = 16 poly_res.gsMarkerSizeF = 0.005 poly_res.gsMarkerColor = 'green' dum = Ngl.add_polymarker(wks, p, lons, lats, poly_res) plot.append(p) if (np.mod(ncases + 1, 2) == 1): Ngl.panel(wks, plot[:], [(ncases + 1) / 2 + 1, 2], pres) else: Ngl.panel(wks, plot[:], [(ncases + 1) / 2, 2], pres) Ngl.frame(wks) Ngl.destroy(wks) # Ngl.end() return plot2d
import Ngl import Nio import numpy import os dirc=Ngl.pynglpath("data") file=Nio.open_file(os.path.join(dirc,"cdf","pop.nc")) wks_type="png" wks=Ngl.open_wks(wks_type,"map2") urot=file.variables["urot"] t=file.variables["t"] lat2d=file.variables["lat2d"] lon2d=file.variables["lon2d"] u=Ngl.add_cyclic(urot[:]) temp=Ngl.add_cyclic(t[0:]) lon=Ngl.add_cyclic(lon2d[0:]) lat=Ngl.add_cyclic(lat2d[0:]) resource=Ngl.Resources() resource.vfXArray=lon resource.vfYArray=lat resource.mpProjection="Stereographic" resource.mpFillOn=True resource.mpInlandWaterFillColor="SkyBlue" resource.mpProjection = "Stereographic"
# Define a color map and open a workstation. # cmap = numpy.array([[1.00,1.00,1.00],[0.00,0.00,0.00],[1.00,0.00,0.00],\ [0.00,1.00,0.00],[0.00,0.00,1.00],[1.00,1.00,0.00],\ [0.00,1.00,1.00],[1.00,0.00,1.00],[0.70,0.30,0.30],\ [0.50,1.00,1.00],[0.80,0.80,0.20],[1.00,1.00,0.50],\ [0.50,0.00,0.80],[1.00,0.50,0.00],[0.30,0.30,0.80],\ [0.50,1.00,0.00],[0.40,0.00,0.40],[0.50,1.00,0.50],\ [0.80,0.20,0.80],[0.00,0.60,0.00],[0.50,0.50,1.00],\ [1.00,0.00,0.50],[0.50,0.50,0.00],[0.00,0.50,0.50],\ [1.00,0.50,0.50],[0.00,1.00,0.50],[0.80,0.80,0.80],\ [0.20,0.80,0.00],[0.55,0.55,0.00],[0.00,0.70,0.00],\ [0.62,0.62,0.00],[0.25,0.25,0.25]], 'f') wks_type = "png" wks = Ngl.open_wks(wks_type, "clmdiv1") # # Create the plot. # # # Map resources. # res = Ngl.Resources() res.mpLambertParallel1F = 33.0 # two parallels res.mpLambertParallel2F = 45.0 res.mpLambertMeridianF = -95.0 # central meridian res.mpLimitMode = "LatLon" # limit map via lat/lon res.mpMinLatF = 24.0 # map area
# First timestep, lowest (bottommost) level, every 5th lat/lon nl = 0 nt = 0 nstep = 5 # a stride to cull some of the streamlines u = ua[nl,::nstep,::nstep] v = va[nl,::nstep,::nstep] spd = np.sqrt(u**2+v**2) # Get the latitude and longitude points lat, lon = latlon_coords(ua) lat = to_np(lat) lon = to_np(lon) # Open file for graphics wks_type = "png" wks = Ngl.open_wks(wks_type,"wrf4") res = Ngl.Resources() res.mpDataBaseVersion = "MediumRes" # Better map outlines res.mpLimitMode = "LatLon" # Zoom in on map area of interest res.mpMinLatF = np.min(lat[:])-0.1 res.mpMaxLatF = np.max(lat[:])+0.1 res.mpMinLonF = np.min(lon[:])-0.1 res.mpMaxLonF = np.max(lon[:])+0.1 res.mpFillOn = True res.mpLandFillColor = "gray85" res.mpOceanFillColor = "transparent" res.mpInlandWaterFillColor = "transparent" res.mpGridLatSpacingF = 1
def draw_e3sm_bgt(ptype, cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs, casedir, dpsc): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = "Red" mkres.gsMarkerSizeF = 15. infiles = ["" for x in range(ncases)] ncdfs = ["" for x in range(ncases)] nregions = nsite varis = ["DCQ", "DCCLDLIQ", "DCCLDICE", "PTEQ", "PTTEND", "DTCOND"] nvaris = len(varis) cscale = [1E8, 1E8, 1E8, 1E8, 1E4, 1E4] chscale = ['1E-8', '1E-8', '1E-8', '1E-8', '1E-4', '1E-4'] plote3smbgt = ["" for x in range(nsite * ncases)] for ire in range(0, nsite): for im in range(0, ncases): if not os.path.exists(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N'): os.mkdir(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N') plotname = casedir + '/' + str(lons[ire]) + 'E_' + str( lats[ire]) + 'N/E3SM_Budgets_' + casenames[im] + "_" + str( lons[ire]) + "E_" + str(lats[ire]) + "N_" + cseason plote3smbgt[im + ncases * ire] = 'E3SM_Budgets_' + casenames[im] + "_" + str( lons[ire]) + "E_" + str(lats[ire]) + "N_" + cseason wks = Ngl.open_wks(ptype, plotname) Ngl.define_colormap(wks, "radar") plot = [] res = Ngl.Resources() res.nglDraw = False res.nglFrame = False res.lgLabelFontHeightF = .012 # change font height res.lgPerimOn = False # no box around res.vpWidthF = 0.30 # set width and height res.vpHeightF = 0.30 # res.txFontHeightF = .01 # res.vpXF = 0.04 # res.vpYF = 0.30 res.tmYLLabelFont = 12 res.tmXBLabelFont = 12 res.tmXBLabelFontHeightF = 0.01 res.tmXBLabelFontThicknessF = 1.0 res.xyMarkLineMode = "MarkLines" res.xyLineThicknesses = [ 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2., 2., 2., 2., 2, 2, 2, 2, 2, 2, 2 ] res.xyLineColors = np.arange(2, 16, 2) res.xyDashPatterns = np.arange(0, 24, 1) res.xyMarkers = np.arange(16, 40, 1) res.xyMarkerSizeF = 0.005 res.xyMarkerColors = np.arange(2, 16, 2) res.pmLegendDisplayMode = "ALWAYS" res.pmLegendSide = "top" # Change location of res.pmLegendParallelPosF = 0.6 # move units right res.pmLegendOrthogonalPosF = -0.55 # more neg = down res.pmLegendWidthF = 0.2 # Decrease width res.pmLegendHeightF = 0.1 # Decrease height res.lgBoxMinorExtentF = 0.1 # Shorten the legend lines res.lgLabelFontHeightF = 0.015 # Change the font size res.lgPerimOn = True res.tiYAxisString = "PRESSURE" res.trYReverse = True pres = Ngl.Resources() pres.nglMaximize = True pres.wkWidth = 2000 pres.wkHeight = 2000 pres.nglFrame = False pres.txFont = 12 pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelTop = 0.93 for iv in range(0, nvaris): if (varis[iv] == "DCQ"): if (dpsc[im] == "zm"): budget_ends = [ "MPDQ", "RVMTEND_CLUBB", "ZMDQ", "EVAPQZM" ] else: budget_ends = ["MPDQ", "RVMTEND_CLUBB"] nterms = len(budget_ends) if (varis[iv] == "DTCOND"): if (dpsc[im] == "zm"): budget_ends = [ "STEND_CLUBB", "MPDT", "DPDLFT", "ZMDT", "EVAPTZM", "ZMMTT" ] else: budget_ends = ["STEND_CLUBB", "MPDT", "DPDLFT"] nterms = len(budget_ends) if (varis[iv] == "PTTEND"): budget_ends = ["DTCOND", "QRS", "QRL", "TTGW"] nterms = len(budget_ends) if (varis[iv] == "PTEQ"): if (dpsc[im] == "zm"): budget_ends = [ "MPDQ", "RVMTEND_CLUBB", "ZMDQ", "EVAPQZM" ] else: budget_ends = ["MPDQ", "RVMTEND_CLUBB"] nterms = len(budget_ends) if (varis[iv] == "DCCLDLIQ"): if (dpsc[im] == "zm"): budget_ends = [ "MPDLIQ", "RCMTEND_CLUBB", "DPDLFLIQ", "ZMDLIQ" ] else: budget_ends = ["MPDLIQ", "RCMTEND_CLUBB", "DPDLFLIQ"] nterms = len(budget_ends) if (varis[iv] == "DCCLDICE"): if (dpsc[im] == "zm"): budget_ends = [ "MPDICE", "RIMTEND_CLUBB", "DPDLFICE", "ZMDICE" ] else: budget_ends = ["MPDICE", "RIMTEND_CLUBB", "DPDLFICE"] nterms = len(budget_ends) ncdfs[im] = './data/' + cases[im] + '_site_location.nc' infiles[im] = filepath[im] + '/' + cases[ im] + '_' + cseason + '_climo.nc' inptrs = Dataset(infiles[im], 'r') # pointer to file1 lat = inptrs.variables['lat'][:] nlat = len(lat) lon = inptrs.variables['lon'][:] nlon = len(lon) ilev = inptrs.variables['lev'][:] nilev = len(ilev) ncdf = Dataset(ncdfs[im], 'r') n = ncdf.variables['n'][:] idx_cols = ncdf.variables['idx_cols'][:, :] ncdf.close() A_field = np.zeros((nterms, nilev), np.float32) theunits = str( chscale[iv]) + "x" + inptrs.variables[varis[iv]].units res.tiMainString = varis[iv] + " " + theunits for it in range(0, nterms): for subc in range(0, n[ire]): varis_bgt = budget_ends[it] npoint = idx_cols[ire, n[subc] - 1] - 1 tmp = inptrs.variables[varis_bgt][0, :, npoint] #/n[ire] tmp = tmp * cscale[iv] if (varis_bgt == "MPDT" or varis_bgt == "STEND_CLUBB"): tmp = tmp / 1004 A_field[it, :] = (A_field[it, :] + tmp[:] / n[ire]).astype(np.float32) inptrs.close() res.xyExplicitLegendLabels = budget_ends[:] p = Ngl.xy(wks, A_field, ilev, res) plot.append(p) xp = np.mod(iv, 2) yp = int(iv / 2) Ngl.panel(wks, plot[:], [nvaris / 2, 2], pres) txres = Ngl.Resources() txres.txFont = _Font txres.txFontHeightF = 0.020 Ngl.text_ndc( wks, casenames[im] + " BUDGET at" + str(lons[ire]) + "E," + str(lats[ire]) + "N", 0.5, 0.95, txres) Ngl.frame(wks) Ngl.destroy(wks) return (plote3smbgt)
lon2d = np.zeros((len(lat), len(lon))) for i in range(0, len(lon)): lat2d[:, i] = lat for i in range(0, len(lat)): lon2d[i, :] = lon # open workspace for analysis plot imagename = "GFSanalysis_%s_%s_LI_PWAT_maxshear_SNGL" % (region, init_dt[0:10]) wks_type = "png" wks_res = ngl.Resources() wks_res.wkBackgroundOpacityF = 0.0 wks = ngl.open_wks(wks_type, imagename, wks_res) # define resources for analysis plot res = ngl.Resources() res.nglDraw = False res.nglFrame = False res.vpWidthF = 0.9 res.vpHeightF = 0.6 cmap = ngl.read_colormap_file("WhiteBlueGreenYellowRed") res.mpGridAndLimbOn = False res.tiMainFontHeightF = 0.015
# create 2d lat and lon lat2d = np.zeros((len(lat), len(lon))) lon2d = np.zeros((len(lat), len(lon))) for i in range(0, len(lon)): lat2d[:, i] = lat for i in range(0, len(lat)): lon2d[i, :] = lon # open workspace for analysis plot wks_type = "png" wks = ngl.open_wks(wks_type, "GFSanalysis_%s_%s_DPTMP2_SNGL" % (region, init_dt[0:10])) # define resources for analysis plot res = ngl.Resources() res.nglDraw = False res.nglFrame = False cmap = ngl.read_colormap_file("WhiteBlueGreenYellowRed") res.mpGridAndLimbOn = False res.pmTickMarkDisplayMode = "Never" res.cnInfoLabelOn = False res.cnFillOn = True res.cnFillPalette = cmap
f = Nio.open_file(filename, "r", options=opt) # Open group "Grid" which will now look like a regular NioFile g = f.groups['Grid'] # Read data from this group precip = g.variables['precipitation'] lat = g.variables['lat'][:] lon = g.variables['lon'][:] # Print the metadata of precip, and min/max values print(precip) print("min/max = {:g} / {:g}".format(precip[:].min(), precip[:].max())) wks_type = "png" wks = Ngl.open_wks(wks_type, "mask1") # Set up resource list for plot options. res = Ngl.Resources() res.nglFrame = False # Will advance the frame later res.cnLinesOn = False # Turn off contour lines res.cnLineLabelsOn = False # Turn off contour labels res.cnFillOn = True # Turn on contour fill res.cnFillMode = "RasterFill" # "AreaFill" is the default and can be slow for large grids. # Define the contour leves and the colors for each. res.cnLevelSelectionMode = "ExplicitLevels" res.cnLevels = [ 0.01, 0.02, 0.04, 0.08, 0.16, \ 0.32, 0.64, 0.96]
# # Output: # A single visualization with two XY curves # from __future__ import print_function import numpy,os import Ngl,Nio dirc = Ngl.pynglpath("data") f = Nio.open_file(os.path.join(dirc,"cdf","uv300.nc")) u = f.variables["U"][0,:,8] lat = f.variables["lat"][:] #---Start the graphics section wks_type = "png" wks = Ngl.open_wks (wks_type,"newcolor2") # Open "newcolor2.png" for graphics #---Set some resources. res = Ngl.Resources() res.nglDraw = False res.nglFrame = False res.xyLineThicknessF = 4.0 plot = Ngl.xy (wks,lat,u,res) # Create plot txres = Ngl.Resources() # text mods desired txres.txFont = 30 txres.txFontHeightF = 0.04 # font smaller. default big txres.txFontOpacityF = 0.10 # highly transparent #txres.txFontOpacityF = 0.5 # half transparent txres.txAngleF = 45.
y[0,0:y1.shape[0]] = y1 y[1,0:y2.shape[0]] = y2 time[0,0:time1.shape[0]] = time1.astype('f') time[1,0:time2.shape[0]] = time2.astype('f') # # Define a color map and open a workstation. # cmap = numpy.zeros((2,3),'f') cmap[0] = [1.,1.,1.] cmap[1] = [0.,0.,0.] rlist = Ngl.Resources() rlist.wkColorMap = cmap wks_type = "ps" wks = Ngl.open_wks(wks_type,"ngl10p",rlist) resources = Ngl.Resources() resources.caXMissingV = -999. resources.caYMissingV = -999. resources.vpWidthF = 0.8 resources.vpXF = 0.13 resources.tiMainString = "~F22~Sulfur Emissions" # "~F22~" changes resources.tiXAxisString = "~F22~Year" # the font to "22" resources.tiYAxisString = "~F22~Tg s/yr" # which is helvetica # bold. resources.tmXBLabelFont = 21 resources.tmYLLabelFont = 21
# create 2d lat and lon lat2d = np.zeros((len(lat),len(lon))) lon2d = np.zeros((len(lat),len(lon))) for i in range(0, len(lon)): lat2d[:,i] = lat for i in range(0, len(lat)): lon2d[i,:] = lon # open workspace for analysis plot wks_type = "png" wks = ngl.open_wks(wks_type, "GFSanalysis_%s_%s_theta_%shPa" % (region, init_dt[0:10], lev_hPa)) # define resources for analysis plot res = ngl.Resources() res.nglDraw = False res.nglFrame = False res.mpGridAndLimbOn = False res.pmTickMarkDisplayMode = "Never" res.cnInfoLabelOn = False res.cnLineLabelsOn = True res.cnFillOn = True res.cnInfoLabelOn = False res.cnLineLabelBackgroundColor = -1
T = numpy.zeros([N,M]) # # create a mound as a test data set # jspn = numpy.power(xrange(-M/2+5,M/2+5),2) ispn = numpy.power(xrange(-N/2-3,N/2-3),2) for i in xrange(len(ispn)): T[i,:] = ispn[i] + jspn T = 100. - 8.*numpy.sqrt(T) # # Open a workstation and draw a contour plot. # wks_type = "ps" wks = Ngl.open_wks(wks_type,"cns01p") res = Ngl.Resources() res.cnMonoLineDashPattern = False plot1 = Ngl.contour(wks,T,res) # # Retrieve the automatically set line labels. # These will be: ['-80', '-60', '-40', '-20', '0', '20', '40', '60', '80'] # line_labels1 = Ngl.get_string_array(plot1,"cnLineLabelStrings") # # Set explicit line labels. Notice that the dash line # setting carries over from the first plot.
# You must have the RANGS/GSHHS database installed in order to # generate the third frame of this example. # # For information on getting the RANGS/GSHHS database, see: # # http://www.pyngl.ucar.edu/Graphics/rangs.shtml # # # Import packages needed. # import Ngl import os wks_type = "png" wks = Ngl.open_wks(wks_type, "coast1") # # Set some map resources. # mpres = Ngl.Resources() mpres.mpLimitMode = "LatLon" mpres.mpMinLonF = -15. mpres.mpMaxLonF = 15 mpres.mpMinLatF = 40. mpres.mpMaxLatF = 70. mpres.mpGridAndLimbOn = False mpres.mpGeophysicalLineThicknessF = 2. mpres.pmTitleDisplayMode = "Always" resolutions = ["LowRes", "MediumRes", "HighRes"]
import numpy import os # # Open the netCDF file. # dirc = Ngl.pynglpath("data") file = Nio.open_file(os.path.join(dirc,"cdf","pop.nc")) # # Open a workstation. # rlist = Ngl.Resources() rlist.wkColorMap = ["White","Black","Tan1","SkyBlue","Red"] wks_type = "ps" wks = Ngl.open_wks(wks_type,"vector_pop",rlist) # # Get the u/v and lat/lon variables. # urot = file.variables["urot"] vrot = file.variables["vrot"] lat2d = file.variables["lat2d"] lon2d = file.variables["lon2d"] t = file.variables["t"] u = Ngl.add_cyclic(urot[290:]) v = Ngl.add_cyclic(vrot[290:]) lon = Ngl.add_cyclic(lon2d[290:]) lat = Ngl.add_cyclic(lat2d[290:]) temp = Ngl.add_cyclic(t[290:])
def large_scale_prf(ptype, cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs, casedir, dofv): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = "Red" mkres.gsMarkerSizeF = 15. infiles = ["" for x in range(ncases)] ncdfs = ["" for x in range(ncases)] nregions = nsite varis = [ "CLOUD", "OMEGA", "Q", "CLDLIQ", "THETA", "RELHUM", "U", "CLDICE", "T" ] varisobs = [ "CC_ISBL", "OMEGA", "SHUM", "CLWC_ISBL", "THETA", "RELHUM", "U", "CIWC_ISBL", "T" ] nvaris = len(varis) cunits = [ "%", "mba/day", "g/kg", "g/kg", "K", "%", "m/s", "g/kg", "m/s", "m/s", "K", "m" ] cscale = [100, 864, 1000, 1000, 1., 1, 1, 1000, 1, 1, 1, 1, 1, 1, 1] cscaleobs = [100, 1, 1, 1000, 1., 1, 1, 1000, 1, 1, 1, 1, 1, 1, 1] obsdataset = [ "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI" ] plotlgs = ["" for x in range(nsite)] for ire in range(0, nsite): if not os.path.exists(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N'): os.mkdir(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N') plotname = casedir + '/' + str(lons[ire]) + 'E_' + str( lats[ire]) + 'N/Largescale_' + str(lons[ire]) + "E_" + str( lats[ire]) + "N_" + cseason plotlgs[ire] = 'Largescale_' + str(lons[ire]) + "E_" + str( lats[ire]) + "N_" + cseason wks = Ngl.open_wks(ptype, plotname) Ngl.define_colormap(wks, "GMT_paired") plot = [] res = Ngl.Resources() res.nglMaximize = False res.nglDraw = False res.nglFrame = False res.lgPerimOn = False # no box around res.vpWidthF = 0.30 # set width and height res.vpHeightF = 0.30 res.tiYAxisString = "Pressure [hPa]" res.tiMainFont = _Font res.tmYLLabelFont = _Font res.tmXBLabelFont = _Font res.tiYAxisFont = _Font res.tiXAxisFont = _Font res.tmXBLabelFontHeightF = 0.01 res.tmXBLabelFontThicknessF = 1.0 res.xyMarkLineMode = 'Lines' # res.tmXBLabelAngleF = 45 res.xyLineThicknesses = [ 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3., 3., 3., 3., 3, 3, 3, 3, 3, 3, 3 ] res.xyDashPatterns = np.arange(0, 24, 1) pres = Ngl.Resources() pres.nglFrame = False pres.txString = "Large-scale VAR at" + str(lons[ire]) + "E," + str( lats[ire]) + "N" pres.txFont = _Font pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelTop = 0.88 pres.wkPaperWidthF = 17 # in inches pres.wkPaperHeightF = 28 # in inches pres.nglMaximize = True pres.wkWidth = 10000 pres.wkHeight = 10000 for iv in range(0, nvaris): if (iv == nvaris - 1): res.pmLegendDisplayMode = "NEVER" res.xyExplicitLegendLabels = casenames[:] res.pmLegendSide = "top" res.pmLegendParallelPosF = 0.6 res.pmLegendOrthogonalPosF = -0.5 res.pmLegendWidthF = 0.10 res.pmLegendHeightF = 0.10 res.lgLabelFontHeightF = .02 res.lgLabelFontThicknessF = 1.5 res.lgPerimOn = True else: res.pmLegendDisplayMode = "NEVER" if (obsdataset[iv] == "CCCM"): if (cseason == "ANN"): fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-" + cseason + ".nc" else: fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-2010-" + cseason + ".nc" inptrobs = Dataset(fileobs, 'r') latobs = inptrobs.variables['lat'][:] latobs_idx = np.abs(latobs - lats[ire]).argmin() lonobs = inptrobs.variables['lon'][:] lonobs_idx = np.abs(lonobs - lons[ire]).argmin() B = inptrobs.variables[varisobs[iv]][:, latobs_idx, lonobs_idx] else: if (varisobs[iv] == "PRECT"): fileobs = filepathobs + '/GPCP_' + cseason + '_climo.nc' else: fileobs = filepathobs + obsdataset[ iv] + '_' + cseason + '_climo.nc' inptrobs = Dataset(fileobs, 'r') if (varisobs[iv] == "THETA"): latobs = inptrobs.variables['lat'][:] latobs_idx = np.abs(latobs - lats[ire]).argmin() lonobs = inptrobs.variables['lon'][:] lonobs_idx = np.abs(lonobs - lons[ire]).argmin() B = inptrobs.variables['T'][0, :, latobs_idx, lonobs_idx] pre1 = inptrobs.variables['lev'][:] for il1 in range(0, len(pre1)): B[il1] = B[il1] * (1000 / pre1[il1])**0.286 else: pre1 = inptrobs.variables['lev'][:] latobs = inptrobs.variables['lat'][:] latobs_idx = np.abs(latobs - lats[ire]).argmin() lonobs = inptrobs.variables['lon'][:] lonobs_idx = np.abs(lonobs - lons[ire]).argmin() B = inptrobs.variables[varisobs[iv]][0, :, latobs_idx, lonobs_idx] B[:] = B[:] * cscaleobs[iv] for im in range(0, ncases): ncdfs[im] = './data/' + cases[im] + '_site_location.nc' infiles[im] = filepath[im] + '/' + cases[ im] + '_' + cseason + '_climo.nc' inptrs = Dataset(infiles[im], 'r') # pointer to file1 lat = inptrs.variables['lat'][:] nlat = len(lat) lon = inptrs.variables['lon'][:] nlon = len(lon) lev = inptrs.variables['lev'][:] nlev = len(lev) ncdf = Dataset(ncdfs[im], 'r') n = ncdf.variables['n'][:] idx_cols = ncdf.variables['idx_cols'][:, :] if (dofv): idx_lats = ncdf.variables['idx_coord_lat'][:, :] idx_lons = ncdf.variables['idx_coord_lon'][:, :] ncdf.close() theunits = "[units]" if (im == 0): A_field = np.zeros((ncases, nlev), np.float32) for subc in range(0, n[ire]): npoint = idx_cols[ire, n[subc] - 1] - 1 if (dofv): npointlat = idx_lats[ire, 0] npointlon = idx_lons[ire, 0] if (varis[iv] == 'THETA'): if (dofv): tmp = inptrs.variables['T'][0, :, npointlat, npointlon] else: tmp = inptrs.variables['T'][0, :, npoint] hyam = inptrs.variables['hyam'][:] hybm = inptrs.variables['hybm'][:] if (dofv): ps = inptrs.variables['PS'][0, npointlat, npointlon] else: ps = inptrs.variables['PS'][0, npoint] ps = ps p0 = 100000.0 #CAM uses a hard-coded p0 pre = np.zeros((nlev), np.float32) for il in range(0, nlev): pre[il] = hyam[il] * p0 + hybm[il] * ps tmp[il] = tmp[il] * (100000 / pre[il])**0.286 theunits = str( cscale[iv]) + "x" + inptrs.variables['T'].units else: if (dofv): tmp = inptrs.variables[varis[iv]][0, :, npointlat, npointlon] else: tmp = inptrs.variables[varis[iv]][0, :, npoint] theunits = str(cscale[iv]) + "x" + inptrs.variables[ varis[iv]].units ##import pdb; pdb.set_trace() A_field[im, :] = (A_field[im, :] + tmp[:] / n[ire]).astype( np.float32) A_field[im, :] = A_field[im, :] * cscale[iv] inptrs.close() res.tiMainString = varis[iv] + " " + theunits res.trXMinF = min(np.min(A_field[0, :]), np.min(B)) res.trXMaxF = max(np.max(A_field[0, :]), np.max(B)) if (varis[iv] == "THETA"): res.trXMinF = 270. res.trXMaxF = 400. if (varis[iv] == "CLOUD" or varis[iv] == "RELHUM"): res.trXMinF = 0. res.trXMaxF = 100. if (varis[iv] == "T"): res.trXMinF = 180 res.trXMaxF = 300 if (varis[iv] == "U"): res.trXMinF = -40 res.trXMaxF = 40 res.trYReverse = True res.xyLineColors = np.arange(3, 20, 2) res.xyMarkerColors = np.arange(2, 20, 2) p = Ngl.xy(wks, A_field, lev, res) res.trYReverse = False res.xyLineColors = ["black"] pt = Ngl.xy(wks, B, pre1, res) Ngl.overlay(p, pt) plot.append(p) Ngl.panel(wks, plot[:], [nvaris / 3, 3], pres) txres = Ngl.Resources() txres.txFontHeightF = 0.02 txres.txFont = _Font Ngl.text_ndc( wks, "Large-scale VAR at" + str(lons[ire]) + "E," + str(lats[ire]) + "N", 0.5, 0.92 + ncases * 0.01, txres) Common_functions.create_legend(wks, casenames, 0.02, np.arange(3, 20, 2), 0.1, 0.89 + ncases * 0.01) Ngl.frame(wks) Ngl.destroy(wks) return plotlgs
# from __future__ import print_function import Ngl import numpy M = 29 N = 25 T = numpy.zeros([N, M]) # # create a mound as a test data set # jspn = numpy.power(range(-M // 2 + 5, M // 2 + 5), 2) ispn = numpy.power(range(-N // 2 - 3, N // 2 - 3), 2) for i in range(len(ispn)): T[i, :] = ispn[i] + jspn T = 100. - 8. * numpy.sqrt(T) # # Open a workstation and draw the contour plot with color fill. # wks_type = "png" wks = Ngl.open_wks(wks_type, "cn02p") res = Ngl.Resources() res.cnFillOn = True Ngl.contour(wks, T, res) Ngl.end()
lon = ext_axis(lon) print(lon) f = Nio.open_file(args.SSTAYYC_file, "r") data = f.variables["SSTAYYC"][selected_month-1, :, :] missing_value = f.variables["SSTAYYC"]._FillValue[0] data[np.isnan(data)] = missing_value data = ext(data) f.close() print("Creating workstation...") wks_type = "png" wks = Ngl.open_wks(wks_type, "%s/%s-SSTAYYC-%02d" % (args.output_dir, args.casename, selected_month)) #-- open a workstation print("Defining res...") cnres = Ngl.Resources() cnres.sfMissingValueV = missing_value cnres.tiMainFontHeightF = 0.01 cnres.tiMainString = "[%s] SSTA year-to-year correlation of month %d" % (args.casename, selected_month) # Contour resources cnres.cnFillOn = True cnres.cnFillPalette = "BlueYellowRed" # New in PyNGL 1.5.0 cnres.cnLinesOn = False cnres.cnLineLabelsOn = False
sst_lon = cdf_file2.variables["lon"][:] sst_lat = cdf_file2.variables["lat"][:] sst_nlon = len(sst_lon) sst_nlat = len(sst_lat) pf_lon = cdf_file3.variables["lon"][:] pf_lat = cdf_file3.variables["lat"][:] pf_nlon = len(pf_lon) pf_nlat = len(pf_lat) # # Open a workstation. # wks_type = "png" wks = Ngl.open_wks(wks_type, "ngl05p") #----------- Begin first plot ----------------------------------------- resources = Ngl.Resources() resources.sfXCStartV = float(min(psl_lon)) resources.sfXCEndV = float(max(psl_lon)) resources.sfYCStartV = float(min(psl_lat)) resources.sfYCEndV = float(max(psl_lat)) map = Ngl.contour_map(wks, psl, resources) #----------- Begin second plot ----------------------------------------- resources.mpProjection = "Orthographic" # Change the map projection.
# # Read the grid centers and the kinetic energy into local variables. # r2d = 57.2957795 # radians to degrees x = cfile.variables["grid_center_lon"][:] * r2d y = cfile.variables["grid_center_lat"][:] * r2d cx = cfile.variables["grid_corner_lon"][:] * r2d cy = cfile.variables["grid_corner_lat"][:] * r2d ke = cfile.variables["kinetic_energy"][2, :] # # Open a workstation. # wks_type = "png" wks = Ngl.open_wks(wks_type, "geodesic") # # The next set of resources will apply to the contour plot and the labelbar. # resources = Ngl.Resources() resources.sfXArray = x # These four resources define resources.sfYArray = y # the type of grid we want to resources.sfXCellBounds = cx # contour. resources.sfYCellBounds = cy resources.cnFillOn = True resources.cnFillMode = "RasterFill" resources.cnLinesOn = False resources.cnLineLabelsOn = False
cmap = numpy.array([ \ [1.00,1.00,1.00], [0.00,0.00,0.00], [1.00,1.00,0.50], \ [0.00,0.00,0.50], [0.50,1.00,1.00], [0.50,0.00,0.00], \ [1.00,0.00,1.00], [0.00,1.00,1.00], [1.00,1.00,0.00], \ [0.00,0.00,1.00], [0.00,1.00,0.00], [1.00,0.00,0.00], \ [0.50,0.00,1.00], [1.00,0.50,0.00], [0.00,0.50,1.00], \ [0.50,1.00,0.00], [0.50,0.00,0.50], [0.50,1.00,0.50], \ [1.00,0.50,1.00], [0.00,0.50,0.00], [0.50,0.50,1.00], \ [1.00,0.00,0.50], [0.50,0.50,0.00], [0.00,0.50,0.50], \ [1.00,0.50,0.50], [0.00,1.00,0.50], [0.50,0.50,0.50], \ [0.625,0.625,0.625] ],dtype=float) rlist = Ngl.Resources() rlist.wkColorMap = cmap wks_type = "ps" wks = Ngl.open_wks(wks_type,"ngl09p",rlist) # Open a workstation. resources = Ngl.Resources() resources.sfMissingValueV = fill_value icemonnew,hlonnew = Ngl.add_cyclic(icemon[0:nsub+1,:],hlon[:]) resources.sfXArray = hlonnew # Necessary for overlay on a map. resources.sfYArray = hlat[0:nsub+1] resources.nglSpreadColors = False # Do not interpolate color space. resources.tiMainString = "CSM Y00-99 Mean Ice Fraction Month =" + str(month) resources.pmTickMarkDisplayMode = "Never" map = Ngl.contour_map(wks,icemonnew,resources) # Draw a contour # over a map.
square = [v * v for v in np.arange(0, 10, 0.1)] #-- retrieve maximum size of plotting data maxdim = max(len(data), len(linear), len(square)) #-- create 2D arrays to hold 1D arrays above y = -999. * np.ones( (3, maxdim), 'f') #-- assign y array containing missing values y[0, 0:(len(data))] = data y[1, 0:(len(linear))] = linear y[2, 0:(len(square))] = square #-- open a workstation wks_type = "png" #-- output type wks_name = os.path.basename(__file__).split(".")[0] wks = Ngl.open_wks(wks_type, wks_name) #-- set resources res = Ngl.Resources() #-- generate an res object for plot res.tiMainString = "Title string" #-- set x-axis label res.tiXAxisString = "x-axis label" #-- set x-axis label res.tiYAxisString = "y-axis label" #-- set y-axis label res.vpWidthF = 0.9 #-- viewport width res.vpHeightF = 0.6 #-- viewport height res.caXMissingV = -999. #-- indicate missing value res.caYMissingV = -999. #-- indicate missing value #-- marker and line settings res.xyLineColors = ["blue", "green", "red"] #-- set line colors
'/nobackup/vagn2/x_joakj/data/gfdl/psi/gfdl_rcp85_2080-2099',\ '/nobackup/vagn2/x_joakj/data/ipsl/psi/ipsl_rcp85_2080-2099', '/nobackup/vagn2/x_joakj/data/noresm/psi/noresm_rcp85_2080-2099'] titles1 = ['CanESM2','CCSM4','EC-Earth2.3','GFDL-CM3','IPSL-CM5A-LR','NorESM1-M','ERA-Interim'] titles2 = ['CanESM2','CCSM4','EC-Earth2.3','GFDL-CM3','IPSL-CM5A-LR','NorESM1-M'] colors = [ 2,3,4,7,13,23,1 ] thicknesses = [ 2,2,2,2,2,2,5 ] patterns = [ 0,0,0,0,0,0,0 ] ## ## Open file and open PDF output ## wks = Ngl.open_wks('pdf','cmip5') hei = 0.22 x0 = 0.1 ; y0 = 0.9 dx = hei * 1.1 ; dy = hei * 1.1 vpx = [] ; vpy = [] xlab = [] ; ylab = [] for jn in range(0,len(ncFiles1)): if (jn == len(ncFiles1)-1): x = x0 + dx else: x = x0 + np.mod(jn,3) * dx if (np.mod(jn,3) == 0): ylab.append(1)
# Effects illustrated: # o Using mpShapeMode to allow a free aspect ratio. # o Changing the map projection. # # Output: # This example produces two visualizations: # 1.) Cylindrical Equidistant projection # 2.) Mollweide projection # # Notes: # import Ngl wks_type = "ps" wks = Ngl.open_wks(wks_type,"map1") projections = ["CylindricalEquidistant","Mollweide"] mpres = Ngl.Resources() # Indicate you want to set some # resources. mpres.mpShapeMode = "FreeAspect" # Allow the aspect ratio to be # changed. mpres.vpWidthF = 0.8 # Make the aspect ratio square. mpres.vpHeightF = 0.8 mpres.pmTitleDisplayMode = "Always" # Force the title to appear. for i in xrange(len(projections)): mpres.mpProjection = projections[i]
# # Import Ngl support functions. # import Ngl wks_type = "ps" wks = Ngl.open_wks(wks_type,"legend") labels = ["One","Two","Three","Four","Five","Six"] # # Generate a legend with the default settings. # lg = Ngl.legend_ndc(wks,5,labels,0.3,0.9) Ngl.frame(wks) # # Change the font of the labels. # rlist = Ngl.Resources() rlist.lgLabelFont = 21 lg = Ngl.legend_ndc(wks,5,labels,0.3,0.9,rlist) Ngl.frame(wks) # # Change the orientation and size. # rlist.vpWidthF = 0.85 rlist.vpHeightF = 0.20 rlist.lgOrientation = "Horizontal"
print(lon) print(lat) print("Getting Data") data = f.variables["SSTAYYC"][11, :, :] print(data.shape) print("DONE") data[:] = 0 #---Start the graphics print("Start plotting...") wks_type = "png" wks = Ngl.open_wks(wks_type, "%s/SSTAYYC" % (output_dir,)) #---Read in desired color map so we can subset it later cmap = Ngl.read_colormap_file("WhiteBlueGreenYellowRed") res = Ngl.Resources() # Plot mods desired. res.cnFillOn = True # color plot desired res.cnFillPalette = cmap[48:208,:] # Don't use white res.cnLinesOn = False # turn off contour lines res.cnLineLabelsOn = False # turn off contour labels res.lbOrientation = "Horizontal" # vertical by default res.trGridType = "TriangularMesh" # This is required to allow # missing coordinates. res.cnLevelSelectionMode = "ManualLevels"
# import Ngl # # Open the netCDF file. # file = NetCDFFile(Ngl.ncargpath("data") + "/cdf/pop.nc","r") # # Open a workstation. # wks_type = "ps" rlist = Ngl.Resources() rlist.wkColorMap = ["White","Black","Tan1","SkyBlue","Red"] wks = Ngl.open_wks(wks_type,"streamline",rlist) # # Get the u/v and lat/lon variables. # urot = file.variables["urot"] vrot = file.variables["vrot"] lat2d = file.variables["lat2d"][:,:] lon2d = file.variables["lon2d"][:,:] # # Set up resource list. # resources = Ngl.Resources() #
#-- open a file and read variables f = Nio.open_file("../read_data/rectilinear_grid_2D.nc", "r") u = f.variables["u10"] v = f.variables["v10"] ua = f.variables["u10"][0, :, :] va = f.variables["v10"][0, :, :] lat = f.variables["lat"] lon = f.variables["lon"] nlon = len(lon) nlat = len(lat) #-- open a workstation wks = Ngl.open_wks("png", "plot_TRANS_streamline_py") #-- resource settings stres = Ngl.Resources() stres.nglFrame = False stres.vfXArray = lon[::3] stres.vfYArray = lat[::3] stres.mpFillOn = True stres.mpOceanFillColor = "Transparent" stres.mpLandFillColor = "Gray90" stres.mpInlandWaterFillColor = "Gray90" #-- create the plot plot = Ngl.streamline_map(wks, ua[::3, ::3], va[::3, ::3], stres)
res.cnInfoLabelOn = False res.lbOrientation = "Horizontal" return (res) # Read in zonal winds f = Nio.open_file("$NCARG_ROOT/lib/ncarg/data/cdf/uv300.nc", "r") u = f.variables["U"] lat = f.variables["lat"] lon = f.variables["lon"] # Start the graphics wks_type = "png" wks = Ngl.open_wks(wks_type, "./output/ngl_report/newcolor6") res = set_common_resources() # Set resources for contour/map plot bres = set_common_resources() bres.mpFillOn = False bres.tiMainString = "Use transparency to emphasize a particular area" bres.tiMainFontHeightF = 0.018 bres.cnFillOpacityF = 0.5 # Half transparent unew, lonnew = Ngl.add_cyclic(u[1, :, :], lon[:]) bres.sfMissingValueV = u._FillValue bres.sfXArray = lonnew[:]
for attrib in dir(file.variables[names[1]]): t = getattr(file.variables[names[1]],attrib) if (type(t) != types.BuiltinFunctionType): print "Attribute " + "'" + attrib + "' has value:", t # # For variable in names[1], retrieve and print the dimension names. # print "\nFor variable " + names[1] + " the dimension names are:" print file.variables[names[1]].dimensions # # Open a workstation. # wks_type = "ps" wks = Ngl.open_wks(wks_type,"ngl04p",None) #----------- Begin first plot ----------------------------------------- resources = Ngl.Resources() # # Get the u/v variables. # uvar = file.variables["U_GRD_6_ISBL"] vvar = file.variables["V_GRD_6_ISBL"] # # Set resources and plot. # if hasattr(uvar,"units"): resources.tiMainString = "GRD_6_ISBL (u,v " + uvar.units + ")"
import Ngl # # Draw four wind barbs of the same magnitude, but at different # locations and in different directions. # # Open a workstation. # wks_type = "ps" wks = Ngl.open_wks(wks_type, "wmbarb") # # Draw wind barbs. # x = [0.25, 0.75, 0.75, 0.25] # x,y,u,v can also be Numeric arrays. y = [0.25, 0.25, 0.75, 0.75] u = [50., -50., -50., 50.0] v = [50., 50., -50., -50.0] Ngl.wmsetp("wbs", 0.2) # Scale the size. Ngl.wmbarb(wks, x, y, u, v) # Draw barbs. Ngl.frame(wks) # Draw plot. # # Retrieve the value of the wbs parameter. # size = Ngl.wmgetp("wbs") print size Ngl.end()
import Ngl #-- open workstation wks_type = "png" wks = Ngl.open_wks(wks_type,"plot_TRANS_maps_py") #-- which projection do we want to plot projections = ["CylindricalEquidistant","Mollweide",\ "Robinson","Orthographic"] #-- resource settings #mpres = Ngl.Resources() #-- resource object mpres.vpWidthF = 0.8 #-- viewport width mpres.vpHeightF = 0.8 #-- viewport height mpres.mpFillOn = True mpres.mpOceanFillColor = "Transparent" mpres.mpLandFillColor = "Gray90" mpres.mpInlandWaterFillColor = "Gray90" for proj in projections: mpres.mpProjection = proj mpres.tiMainString = proj map = Ngl.map(wks,mpres) Ngl.end()
dirc = Ngl.ncargpath("data") ufile = NetCDFFile(dirc + "/cdf/Ustorm.cdf","r") # Open two netCDF files. vfile = NetCDFFile(dirc + "/cdf/Vstorm.cdf","r") # # Get the u/v variables. # u = ufile.variables["u"] v = vfile.variables["v"] lat = ufile.variables["lat"] lon = ufile.variables["lon"] ua = u[0,:,:] va = v[0,:,:] wks_type = "ps" wks = Ngl.open_wks(wks_type,"ngl03p") resources = Ngl.Resources() if hasattr(u,"_FillValue"): resources.vfMissingUValueV = u._FillValue if hasattr(v,"_FillValue"): resources.vfMissingVValueV = v._FillValue vc = Ngl.vector(wks,ua,va,resources) #----------- Begin second plot ----------------------------------------- resources.vcMinFracLengthF = 0.33 resources.vcRefMagnitudeF = 20.0 resources.vcRefLengthF = 0.045 resources.vcMonoLineArrowColor = False # Draw vectors in color.
"You do not have the necessary '{}' file to run this example.".format( filename)) print("See the comments at the top of this script for more information.") sys.exit() a = Nio.open_file(filename) vname = "TS" data = a.variables[vname] lat = a.variables["lat"][:] # 1D array (48602 cells) lon = a.variables["lon"][:] # ditto ncells = data.shape[1] print("There are {} cells in the {} variable".format(ncells, vname)) wks_type = "png" wks = Ngl.open_wks(wks_type, "camse1") #---Set some plot options res = Ngl.Resources() # Contour options res.cnFillOn = True # turn on contour fill res.cnLinesOn = False # turn off contour lines res.cnLineLabelsOn = False # turn off line labels res.cnLevelSpacingF = 2.5 # NCL chose 5.0 res.cnFillPalette = "WhiteBlueGreenYellowRed" # Map options res.mpProjection = "Orthographic" res.mpCenterLonF = 40 res.mpCenterLatF = 60
f = Nio.open_file(diri + fname,"r") #-- open data file temp = f.variables["tsurf"][0,::-1,:] #-- first time step, reverse latitude u = f.variables["u10"][0,::-1,:] #-- first time step, reverse latitude v = f.variables["v10"][0,::-1,:] #-- first time step, reverse latitude lat = f.variables["lat"][::-1] #-- reverse latitudes lon = f.variables["lon"][:] #-- all longitudes nlon = len(lon) #-- number of longitudes nlat = len(lat) #-- number of latitudes #-- open a workstation wkres = Ngl.Resources() #-- generate an resources object for workstation #wkres.wkWidth = 2500 #-- plot resolution 2500 pixel width #wkres.wkHeight = 2500 #-- plot resolution 2500 pixel height wks_type = "x11" #-- graphics output type wks = Ngl.open_wks(wks_type,"plot_vector_PyNGL",wkres) #-- create 1st plot: vectors on global map res = Ngl.Resources() res.vfXCStartV = float(lon[0]) #-- minimum longitude res.vfXCEndV = float(lon[len(lon[:])-1]) #-- maximum longitude res.vfYCStartV = float(lat[0]) #-- minimum latitude res.vfYCEndV = float(lat[len(lat[:])-1]) #-- maximum latitude res.tiMainString = "~F25~Wind velocity vectors" #-- title string res.tiMainFontHeightF = 0.024 #-- decrease title font size res.mpLimitMode = "Corners" #-- select a sub-region res.mpLeftCornerLonF = float(lon[0]) #-- left longitude value res.mpRightCornerLonF = float(lon[len(lon[:])-1]) #-- right longitude value res.mpLeftCornerLatF = float(lat[0]) #-- left latitude value
# create 2d lat and lon lat2d = np.zeros((len(lat), len(lon))) lon2d = np.zeros((len(lat), len(lon))) for i in range(0, len(lon)): lat2d[:, i] = lat for i in range(0, len(lat)): lon2d[i, :] = lon # open workspace for analysis plot wks_type = "png" wks = ngl.open_wks( wks_type, "GFSanalysis_%s_%s_meanVwinds_%shPa_%shPa_SNGL" % (region, init_dt[0:10], lev1, lev2)) # define resources for analysis plot res = ngl.Resources() res.nglDraw = False res.nglFrame = False res.vpWidthF = 0.9 res.vpHeightF = 0.6 cmap = ngl.read_colormap_file("BlueRed") res.pmTickMarkDisplayMode = "Never"
# 2.) changing the font and alignment # 3.) changing the size, orientation and fill pattern # 4.) using lots of user-specified labels # # Notes: # # # Import Ngl support functions. # import Ngl wkres = Ngl.Resources() wkres.wkColorMap = "default" wks_type = "ps" wks = Ngl.open_wks(wks_type, "labelbar", wkres) labels = ["One", "Two", "Three", "Four", "Five", "Six"] # # Generate a labelbar with the default settings. # lb = Ngl.labelbar_ndc(wks, 5, labels, 0.3, 0.9) Ngl.frame(wks) # # Change the font and alignment of the labels. # rlist = Ngl.Resources() rlist.lbLabelFont = "Times-Bold" rlist.lbLabelAlignment = "InteriorEdges"
def clubb_std_prf(ptype, cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs, casedir, varis, cscale, chscale, pname, dofv): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = "Red" mkres.gsMarkerSizeF = 15. infiles = ["" for x in range(ncases)] ncdfs = ["" for x in range(ncases)] nregions = nsite # varisobs = ["CC_ISBL", "OMEGA","SHUM","CLWC_ISBL", "THETA","RELHUM","U","CIWC_ISBL","T" ] nvaris = len(varis) # cunits = ["%","mba/day","g/kg","g/kg","K", "%", "m/s", "g/kg", "m/s", "m/s","K","m" ] # cscaleobs = [100, 1, 1, 1000 , 1., 1, 1, 1000, 1,1,1,1,1,1,1] # obsdataset =["ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI","ERAI","ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI","ERAI","ERAI"] plotstd = ["" for x in range(nsite)] for ire in range(0, nsite): if not os.path.exists(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N'): os.mkdir(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N') plotname = casedir + '/' + str(lons[ire]) + 'E_' + str( lats[ire]) + 'N/' + pname + '_' + str(lons[ire]) + "E_" + str( lats[ire]) + "N_" + cseason plotstd[ire] = pname + '_' + str(lons[ire]) + "E_" + str( lats[ire]) + "N_" + cseason wks = Ngl.open_wks(ptype, plotname) Ngl.define_colormap(wks, "GMT_paired") plot = [] res = Ngl.Resources() res.nglDraw = False res.nglFrame = False res.lgLabelFontHeightF = .02 # change font height res.lgPerimOn = False # no box around res.vpWidthF = 0.30 # set width and height res.vpHeightF = 0.30 #res.vpXF = 0.04 # res.vpYF = 0.30 res.tmYLLabelFont = _Font res.tmXBLabelFont = _Font res.tmXBLabelFontHeightF = 0.01 res.tmXBLabelFontThicknessF = 2.0 res.xyMarkLineMode = "Lines" res.xyLineThicknesses = [ 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3., 3., 3., 3., 3, 3, 3, 3, 3, 3, 3 ] res.xyDashPatterns = np.arange(0, 24, 1) # res.xyMarkers = np.arange(16,40,1) # res.xyMarkerSizeF = 0.005 pres = Ngl.Resources() pres.nglMaximize = True pres.nglFrame = False pres.txFont = _Font pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelTop = 0.88 pres.wkWidth = 5000 pres.wkHeight = 5000 for iv in range(0, nvaris): if (iv == nvaris - 1): res.pmLegendDisplayMode = "NEVER" res.xyExplicitLegendLabels = casenames[:] res.pmLegendSide = "top" res.pmLegendParallelPosF = 0.6 res.pmLegendOrthogonalPosF = -0.5 res.pmLegendWidthF = 0.10 res.pmLegendHeightF = 0.10 res.lgLabelFontHeightF = .02 res.lgLabelFontThicknessF = 1.5 res.lgPerimOn = True else: res.pmLegendDisplayMode = "NEVER" # if(obsdataset[iv] =="CCCM"): # if(cseason == "ANN"): # fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-"+cseason+".nc" # else: # fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-2010-"+cseason+".nc" # inptrobs = Dataset(fileobs,'r') # B=inptrobs.variables[varisobs[iv]][:,(lats[ire]),(lons[ire])] # else: # if (varisobs[iv] =="PRECT"): # fileobs = filepathobs+'/GPCP_'+cseason+'_climo.nc' # else: # fileobs = filepathobs + obsdataset[iv]+'_'+cseason+'_climo.nc' # inptrobs = Dataset(fileobs,'r') # if (varisobs[iv] =="THETA"): # B = inptrobs.variables['T'][0,:,(lats[ire]),(lons[ire])] # pre1 = inptrobs.variables['lev'][:] # for il1 in range (0, len(pre1)): # B[il1] = B[il1]*(1000/pre1[il1])**0.286 # else: # pre1 = inptrobs.variables['lev'][:] # B = inptrobs.variables[varisobs[iv]][0,:,(lats[ire]),(lons[ire])] # # B[:]=B[:] * cscaleobs[iv] for im in range(0, ncases): ncdfs[im] = './data/' + cases[im] + '_site_location.nc' infiles[im] = filepath[im] + '/' + cases[ im] + '_' + cseason + '_climo.nc' inptrs = Dataset(infiles[im], 'r') # pointer to file1 lat = inptrs.variables['lat'][:] nlat = len(lat) lon = inptrs.variables['lon'][:] nlon = len(lon) lev = inptrs.variables['ilev'][:] nlev = len(lev) ncdf = Dataset(ncdfs[im], 'r') n = ncdf.variables['n'][:] idx_cols = ncdf.variables['idx_cols'][:, :] if (dofv): idx_lats = ncdf.variables['idx_coord_lat'][:, :] idx_lons = ncdf.variables['idx_coord_lon'][:, :] ncdf.close() if (im == 0): A_field = np.zeros((ncases, nlev), np.float32) for subc in range(0, n[ire]): npoint = idx_cols[ire, n[subc] - 1] - 1 if (dofv): npointlat = idx_lats[ire, 0] npointlon = idx_lons[ire, 0] if (varis[iv] == 'THETA'): if (dofv): tmp = inptrs.variables['T'][0, :, npointlat, npointlon] else: tmp = inptrs.variables['T'][0, :, npoint] hyam = inptrs.variables['hyam'][:] hybm = inptrs.variables['hybm'][:] if (dofv): ps = inptrs.variables['PS'][0, npointlat, npointlon] else: ps = inptrs.variables['PS'][0, npoint] ps = ps p0 = inptrs.variables['P0'] pre = np.zeros((nlev), np.float32) for il in range(0, nlev): pre[il] = hyam[il] * p0 + hybm[il] * ps tmp[il] = tmp[il] * (100000 / pre[il])**0.286 theunits = str( chscale[iv]) + "x" + inptrs.variables['T'].units else: if (dofv): tmp = inptrs.variables[varis[iv]][0, :, npointlat, npointlon] else: tmp = inptrs.variables[varis[iv]][0, :, npoint] theunits = str(chscale[iv]) + 'x' + inptrs.variables[ varis[iv]].units if (varis[iv] == 'tau_zm' or varis[iv] == 'tau_wp2_zm' \ or varis[iv] == 'tau_wp3_zm' or varis[iv] == 'tau_xp2_zm' \ or varis[iv] == 'tau_no_N2_zm' or varis[iv] == 'tau_wpxp_zm'): tmp = 1 / tmp tmp[0:10] = 0.0 theunits = str( chscale[iv]) + 'x' + inptrs.variables[ varis[iv]].units + '^-1' A_field[im, :] = (A_field[im, :] + tmp[:] / n[ire]).astype( np.float32) A_field[im, :] = A_field[im, :] * cscale[iv] inptrs.close() if (varis[iv] == 'tau_zm' or varis[iv] == 'tau_wp2_zm' \ or varis[iv] == 'tau_wp3_zm' or varis[iv] == 'tau_xp2_zm' \ or varis[iv] == 'tau_no_N2_zm' or varis[iv] == 'tau_wpxp_zm'): res.tiMainString = "invrs_" + varis[iv] + " " + theunits else: res.tiMainString = varis[iv] + " " + theunits res.trYReverse = True res.xyLineColors = np.arange(3, 20, 2) res.xyMarkerColors = np.arange(2, 20, 2) p = Ngl.xy(wks, A_field, lev, res) # res.trYReverse = False # res.xyLineColors = ["black"] # pt = Ngl.xy(wks,B,pre1,res) # Ngl.overlay(p,pt) plot.append(p) pres.txString = "CLUBB VAR at" + str(lons[ire]) + "E," + str( lats[ire]) + "N" txres = Ngl.Resources() txres.txFontHeightF = 0.02 txres.txFont = _Font Ngl.text_ndc( wks, "CLUBB VAR at" + str(lons[ire]) + "E," + str(lats[ire]) + "N", 0.5, 0.92 + ncases * 0.01, txres) Common_functions.create_legend(wks, casenames, 0.02, np.arange(3, 20, 2), 0.1, 0.89 + ncases * 0.01) Ngl.panel(wks, plot[:], [nvaris / 3, 3], pres) Ngl.frame(wks) Ngl.destroy(wks) return plotstd
import Ngl import os, sys wks_type = "ps" wks = Ngl.open_wks(wks_type,"color1") rlist = Ngl.Resources() # # Loop through all of the listed color maps and draw them as a # table of colors and index values. # # Originally, this example drew *all* of the color maps in the colormaps # directory. This resulted in a large PostScript file, so just do a # subset instead. If you want to do all of them, uncomment the following # code: # #pkgs_pth = os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], # 'site-packages') #color_dir = pkgs_pth + "/PyNGL/ncarg/colormaps" #color_files = os.listdir(color_dir) color_files = ["thelix","GreenYellow","rainbow"] for i in xrange(len(color_files)): # # Uncomment this code too, if you want to draw all colormaps, # and comment out the other wkColorMap line below. # #base_name = os.path.splitext(color_files[i]) #print base_name[0]
figPath = np.array(figData[4]) figPath = str(figPath) if figPath == '/no': continue else: # ---Generate some dummy lat/lon data lat = np.squeeze(np.array(figData[1], 'f')) lon = np.squeeze(np.array(figData[0], 'f')) nlat = lat.size nlon = lon.size # ---Start the graphics section 创建画板 wks_type = "eps" wks = Ngl.open_wks(wks_type, figPath) # # One color map per row of plots colormap = np.array(figData[5]) # ---Values to use for contour labelbar varMin = -0.1 # Data mins varMax = 0.7 # Data maxs varInt = 0.1 # Data spacing levels = np.arange(varMin, varMax + 0.0001, varInt) # list(np.arange(varMin,varMax,varInt)) nlevs = len(levels) # -- number of levels # -- convert list of floats to list of strings labels = ['{:.1f}'.format(x) for x in levels] labels = str(labels)
# Read the grid centers and the kinetic energy into local variables. # r2d = 57.2957795 # radians to degrees x = cfile.variables["grid_center_lon"][:] * r2d y = cfile.variables["grid_center_lat"][:] * r2d cx = cfile.variables["grid_corner_lon"][:] * r2d cy = cfile.variables["grid_corner_lat"][:] * r2d ke = cfile.variables["kinetic_energy"][2,:] # # Select a colormap and open a workstation. # rlist = Ngl.Resources() rlist.wkColorMap = "gui_default" wks_type = "ps" wks = Ngl.open_wks(wks_type,"geodesic",rlist) # # The next set of resources will apply to the contour plot and the labelbar. # resources = Ngl.Resources() resources.sfXArray = x # These four resources define resources.sfYArray = y # the type of grid we want to resources.sfXCellBounds = cx # contour. resources.sfYCellBounds = cy resources.cnFillOn = True resources.cnFillMode = "RasterFill" resources.cnLinesOn = False resources.cnLineLabelsOn = False
def plotline(nlines,plotin,yearsin,nsep,title,Datatitle,figtitlein,colormap,xString,yString,unit): wkres = Ngl.Resources() wkres.wkColorMap = colormap wks_type = "eps" wks = Ngl.open_wks(wks_type,figtitlein,wkres) res = Ngl.Resources() plot = [] res.tiXAxisString = xString res.tiYAxisString = yString for iline in range(0,nlines): yearsplot = yearsin[iline] print yearsplot # nyearsin = len(yearsplot) # yearnums = range(0,nyearsin) A = np.array(yearsplot) regress = (np.zeros((5,nsep),np.float)) for ibin in range(0,nsep): if ibin == 0: if (plotdensity): res.tiYAxisString = "frequency" else: res.tiYAxisString = "number of events" else: res.tiYAxisString = "" linreg = plotin[iline][ibin][:] print A.shape print linreg.shape regress[:,ibin] = stats.linregress(A,linreg) if ibin == nsep -1: res.tiMainString = '{:^80}'.format(' >' + '{:2.1g}'.format(tbound1[ibin]) + unit + '; p=' + '{:5.3f}'.format(regress[3,ibin]) + " ") else: res.tiMainString = '{:^80}'.format('{:2.1g}'.format(tbound1[ibin]) + '-' + '{:2.1g}'.format(tbound2[ibin]) + unit + '; p=' + '{:5.3f}'.format(regress[3,ibin])) plot.append(Ngl.xy(wks,yearsplot,plotin[iline][ibin,:],res)) panelres = Ngl.Resources() panelres.nglPanelLabelBar = True panelres.nglPanelYWhiteSpacePercent = 8. panelres.nglPanelXWhiteSpacePercent = 0.0 panelres.nglPanelLabelBar = False # Turn on panel labelbar panelres.nglPanelTop = 1.0 panelres.nglPanelBottom = 0.00 panelres.nglPanelLeft = 0.0 panelres.nglPanelRight = 1.0 panelres.nglPaperOrientation = "Portrait" panelres.nglScale = False panelres.nglMaximize = True #txres = Ngl.Resources() #txres.txFontHeightF = 0.012 #Ngl.text_ndc(wks,'Annual timeseries of global number of events of various scales from' + Datatitle,0.5,0.94,txres) Ngl.panel(wks,plot,[nlines,float(nbounds)],panelres) print 'panelled'
# # Define a color map and open four different types of workstations. # cmap = Numeric.array([[1.00, 1.00, 1.00], [0.00, 0.00, 0.00], \ [1.00, 0.00, 0.00], [1.00, 0.00, 0.40], \ [1.00, 0.00, 0.80], [1.00, 0.20, 1.00], \ [1.00, 0.60, 1.00], [0.60, 0.80, 1.00], \ [0.20, 0.80, 1.00], [0.20, 0.80, 0.60], \ [0.20, 0.80, 0.00], [0.20, 0.40, 0.00], \ [0.20, 0.45, 0.40], [0.20, 0.40, 0.80], \ [0.60, 0.40, 0.80], [0.60, 0.80, 0.80], \ [0.60, 0.80, 0.40], [1.00, 0.60, 0.80]],Numeric.Float0) rlist = Ngl.Resources() rlist.wkColorMap = cmap xwks = Ngl.open_wks( "x11","ngl08p",rlist) # Open an X11 workstation. cgmwks = Ngl.open_wks("ncgm","ngl08p",rlist) # Open an NCGM workstation. pswks = Ngl.open_wks( "ps","ngl08p",rlist) # Open a PS workstation. pdfwks = Ngl.open_wks( "pdf","ngl08p",rlist) # Open a PDF workstation. #----------- Begin first plot ----------------------------------------- resources = Ngl.Resources() resources.sfXArray = xo # X axes data points resources.sfYArray = yo # Y axes data points resources.tiMainString = "Depth of a subsurface stratum" resources.tiMainFont = "Times-Bold" resources.tiXAxisString = "x values" # X axis label. resources.tiYAxisString = "y values" # Y axis label.
def plotmap(plotvars1,plotvars2, plotmin1,plotmax1,plotmin2,plotmax2, vartitle1,vartitle2, title, figtitle, minlon,maxlon,minlat,maxlat, FillValue,panellabels = [], labelbarlabels = [], labelbarlabels2 = []): nplots = plotvars1.shape[0] wkres = Ngl.Resources() wkres.wkColorMap = "WhiteBlue" wks_type = "eps" wks = Ngl.open_wks(wks_type,figtitle,wkres) # if lons start negative, shift everything over so there isn't a line down # the middle of the Pacific lons1 = plotvars1.lon.values lons2 = plotvars2.lon.values lats1 = plotvars1.lat.values lats2 = plotvars2.lat.values if lons1[0] < 0: #nlonhalf1 = len(lons1)/2 #lonsnew1 = np.zeros(lons1.shape,np.float) #lonsnew1[0:nlonhalf1] = lons1[nlonhalf1:nlons1] #lonsnew1[nlonhalf1:nlons1] = lons1[0:nlonhalf1] + 360.0 lonsnew1 = shiftlonlons(lons1,len(lons1)) lonsnew2 = shiftlonlons(lons2,len(lons2)) for iplot in range(0,nplots): plotvars1[iplot] = shiftlons(plotvars1[iplot],len(lons1)) plotvars2[iplot] = shiftlons(plotvars2[iplot],len(lons2)) else: lonsnew1 = lons1 lonsnew2 = lons2 # initialize plotting resources res1 = Ngl.Resources() res1 = initcontourplot(res1,minlat,minlon,maxlat,maxlon,lats1,lonsnew1) res1.sfMissingValueV = FillValue res1.lbOrientation = "Vertical" # including some font heights res1.lbLabelFontHeightF = 0.01 res1.lbTitleFontHeightF = 0.01 res1.tiMainFontHeightF = 0.015 res1.lbTitlePosition = 'Bottom' res1.lbBottomMarginF = 0.0 # initialize plotting resources res2 = Ngl.Resources() res2 = initcontourplot(res2,minlat,minlon,maxlat,maxlon,lats2,lonsnew2) res2.sfMissingValueV = FillValue res2.lbOrientation = "Vertical" # including some font heights res2.lbLabelFontHeightF = 0.01 res2.lbTitleFontHeightF = 0.01 res2.tiMainFontHeightF = 0.008 res2.lbTitlePosition = 'Bottom' res2.lbBottomMarginF = 0.0 # turn off grid lines res1.mpGridAndLimbOn = False res2.mpGridAndLimbOn = False # initialize plotting array toplot = [] # fill plotting array for iplot in range(0,nplots): tempplot = plotvars1[iplot].values tempplot[np.where(np.isnan(tempplot))] = FillValue # update plot resources with correct lat/lon res1.cnMinLevelValF = plotmin1[iplot] res1.cnMaxLevelValF = plotmax1[iplot] res1.cnLevelSpacingF = ((plotmax1[iplot]-plotmin1[iplot])/10.0) res1.tiMainString = (vartitle1[iplot]) if panellabels != []: res1.lbTitleString = labelbarlabels[iplot] res1.tiYAxisString = panellabels[iplot] # Y axes label. toplot.append(Ngl.contour_map(wks,tempplot,res1)) tempplot = plotvars2[iplot].values tempplot[np.where(np.isnan(tempplot))] = FillValue res2.cnMinLevelValF = plotmin2[iplot] # contour levels. res2.cnMaxLevelValF = plotmax2[iplot] res2.cnLevelSpacingF = ((plotmax2[iplot]-plotmin2[iplot])/10.0) res2.tiMainString = vartitle2[iplot] if panellabels != []: res2.lbTitleString = labelbarlabels2[iplot] res2.tiYAxisString = " " # so plots are the same # size toplot.append(Ngl.contour_map(wks,tempplot,res2)) textres = Ngl.Resources() textres.txFontHeightF = 0.015 Ngl.text_ndc(wks,title,0.5,0.87,textres) panelres = Ngl.Resources() panelres.nglPanelLabelBar = True panelres.nglPanelYWhiteSpacePercent = 0. panelres.nglPanelXWhiteSpacePercent = 0. panelres.nglPanelLabelBar = False # Turn on panel labelbar if nplots > 5: panelres.nglPanelTop = 0.8 panelres.nglPanelBottom = 0.15 else: panelres.nglPanelTop = 0.95 panelres.nglPanelBottom = 0.01 panelres.nglPanelLeft = 0.01 panelres.nglPanelRight = 0.99 panelres.nglPanelFigureStrings = ( ['a.','b.','c.','d.','e.','f.','g.','h.','i.','j.','k.','l.','m.','n.','o.','p.']) panelres.nglPanelFigureStringsJust = "TopLeft" panelres.nglPanelFigureStringsFontHeightF = 0.008 panelres.nglPanelFigureStringsParallelPosF = -0.55 panelres.nglPanelFigureStringsOrthogonalPosF = -0.7 panelres.nglPanelFigureStringsPerimOn = False # turn off boxes #panelres.amJust = "TopLeft" panelres.nglPaperOrientation = "Auto" plot = Ngl.panel(wks,toplot,[nplots,2],panelres)
def main(data_path = DEFAULT_PATH): #get data to memory [data, times, x_indices, y_indices] = data_select.get_data_from_file(data_path) the_mean = np.mean(data, axis = 0) lons2d, lats2d = polar_stereographic.lons, polar_stereographic.lats lons = lons2d[x_indices, y_indices] lats = lats2d[x_indices, y_indices] #colorbar wres = Ngl.Resources() wres.wkColorMap = "BlGrYeOrReVi200" wks_type = "ps" wks = Ngl.open_wks(wks_type,"test_pyngl", wres) #plot resources res = Ngl.Resources() res.cnFillMode = "RasterFill" #res.cnFillOn = True # Turn on contour fill #res.cnMonoFillPattern = True # Turn solid fill back on. #res.cnMonoFillColor = False # Use multiple colors. res.cnLineLabelsOn = False # Turn off line labels. res.cnInfoLabelOn = False # Turn off informational res.pmLabelBarDisplayMode = "Always" # Turn on label bar. res.cnLinesOn = False # Turn off contour lines. res.mpProjection = "LambertConformal" res.mpDataBaseVersion = "MediumRes" # res.mpLimitMode = "LatLon" # limit map via lat/lon # res.mpMinLatF = np.min(lats) # map area # res.mpMaxLatF = np.max(lats) # latitudes # res.mpMinLonF = np.min( lons ) # and # res.mpMaxLonF = np.max( lons ) # longitudes print np.min(lons), np.max(lons) res.tiMainFont = 26 res.tiXAxisFont = 26 res.tiYAxisFont = 26 res.sfXArray = lons2d res.sfYArray = lats2d # # Set title resources. # res.tiMainString = "Logarithm of mean annual streamflow m**3/s" to_plot = np.ma.masked_all(lons2d.shape) to_plot[x_indices, y_indices] = np.log(the_mean[:]) # for i, j, v in zip(x_indices, y_indices, the_mean): # to_plot[i, j] = v Ngl.contour_map(wks, to_plot[:,:], res) Ngl.end() pass
PS[:, :, :], interp, p0mb1, 1, extrap) NewTracer_AI_Uni = Ngl.vinth2p(DU_AI[:, :, :, :], hyam, hybm, pnew, PS[:, :, :], interp, p0mb1, 1, extrap) NewTracer_AI_Uni = np.ma.masked_where(NewTracer_AI_Uni == 1.e30, NewTracer_AI_Uni) print(np.max(NewTracer_AI_Uni)) # day 10 to 20 # set up colormap rlist = Ngl.Resources() rlist.wkColorMap = "WhiteYellowOrangeRed" for it in range(30): print(it) # use colormap and type information to setup output background wks_type = "pdf" wks = Ngl.open_wks(wks_type, "Uniform" + str(it), rlist) # resources for the contour res = Ngl.Resources() res.lbLabelBarOn = False # Filled contour/labels/labelinfos res.cnLinesOn = False res.cnFillOn = True res.cnLineLabelsOn = False res.cnInfoLabelOn = False res.mpGridAndLimbOn = False #anotherway to define colormap (overlay the predefined color map) # cmap = Ngl.read_colormap_file("WhiteBlueGreenYellowRed") #Level selection # res.lbBoxLinesOn = False res.cnLevelSelectionMode = "ExplicitLevels" # Set explicit contour levels res.cnLevels = np.arange(1e-5, 8.e-4, 4e-5) # 0,5,10,...,70