#------------------------------------------------------- # MAIN #------------------------------------------------------- wks = Ngl.open_wks("png","plot_mptick_10") #-- open workstation #----------------------------------- #-- first plot: Lambert Conformal #----------------------------------- #-- northern hemisphere minlon = -90. #-- min lon to mask maxlon = 40. #-- max lon to mask minlat = 20. #-- min lat to mask maxlat = 80. #-- max lat to mask mpres = Ngl.Resources() #-- resource object mpres.nglMaximize = True mpres.nglDraw = False #-- turn off plot draw and frame advance. We will mpres.nglFrame = False #-- do it later after adding subtitles. mpres.mpFillOn = True #-- turn map fill on mpres.mpOutlineOn = False #-- outline map mpres.mpOceanFillColor = "Transparent" #-- set ocean fill color to transparent mpres.mpLandFillColor = "Gray90" #-- set land fill color to gray mpres.mpInlandWaterFillColor = "Gray90" #-- set inland water fill color to gray mpres.tiMainString = "Adding lat/lon labels to a masked LC map~C~(northern hemisphere)" mpres.tiMainOffsetYF = 0.05 mpres.tiMainFontHeightF = 0.016 #-- decrease font size mpres.mpProjection = "LambertConformal"
def plot_oope_map(data, figname, size_class=None, percentage=1): ''' Draws 2D OOPE maps. :param xarray.Dataset data: 2D OOPE array. Dims must be (y, x, comm, size) :param str figname: Name of the figure file (must end by .png or .pdf) :param list size_class: Size classes to output (in m) :param float percentage: percentage used to saturate colorbar from percentile. Colorbar is saturated from values of the (X) and (100 - X) percentile. :return: None ''' if size_class is None: size_class = [1e-3, 1e-2, 1e-1, 1] # sort size class in ascending order, and add 0 and infinity as size bounds size_class = np.sort(size_class) if size_class[0] != 0: size_class = np.concatenate(([0], size_class), axis=0) if size_class[-1] != np.Inf: size_class = np.concatenate((size_class, [np.Inf]), axis=0) # Check that the OOPE dataset has 4 dimensions (i.e. no time dimension) ndims = len(data['OOPE'].dims) if ndims != 4: message = 'Data must have dimensions of size (lat, lon, comm, wei)' print(message) sys.exit(0) # Recover data variables length = data['length'].values oope = data['OOPE'].values lon = data['longitude'][:].values lat = data['latitude'][:].values comm = data['community'][:].values.astype(np.int) # mask oope where land oope = np.ma.masked_where(np.isnan(oope), oope) comm_string = misc.extract_community_names(data) if figname.endswith('png'): form = 'png' elif figname.endswith('pdf'): form = 'pdf' else: message = 'Figure name should end with png or pdf' print(message) sys.exit(0) # opens the document wks = Ngl.open_wks(form, figname) # set the document colormap # resngl = Ngl.Resources() # resngl.wkColorMap = 'precip2_15lev' # Ngl.set_values(wks, resngl) # Add gray to the workspace Ngl.new_color(wks, 0.7, 0.7, 0.7) # init the plot resources # For a detailed description, see https://www.ncl.ucar.edu/Document/Graphics/Resources/ res = Ngl.Resources() # not necessary, just a good habit res.nglDraw = False res.nglFrame = False # Set map resources. res.mpLimitMode = "LatLon" # limit map via lat/lon res.mpMinLatF = lat.min() # map area res.mpMaxLatF = lat.max() # latitudes res.mpMinLonF = lon.min() # and res.mpMaxLonF = lon.max() # longitudes res.mpFillOn = True res.mpLandFillColor = "LightGray" res.mpOceanFillColor = -1 res.mpInlandWaterFillColor = "LightBlue" res.mpGeophysicalLineThicknessF = 1 # thickness of coastlines # coordinates for contour plots res.sfXArray = lon res.sfYArray = lat res.cnFillOn = True # filled contour res.cnLinesOn = False # no lines res.cnLineLabelsOn = False # no labels res.cnInfoLabelOn = False # no info about contours res.cnFillMode = 'CellFill' # contourf=AreaFill, pcolor="CellFill" or "RasterFill" res.lbOrientation = "Horizontal" # colorbar orientation res.lbLabelFontHeightF = 0.012 # colorbar label fontsize res.lbTitlePosition = "Bottom" # position of colorbar title res.lbTitleFontHeightF = 0.012 # title font height # res.cnFillPalette = "wgne15" res.cnFillPalette = "WhiteBlueGreenYellowRed" txres = Ngl.Resources() txres.txJust = "BottomCenter" txres.txFontHeightF = 0.02 res.cnLevelSelectionMode = 'ExplicitLevels' res.cnMaxLevelCount = 41 res.mpGridAndLimbOn = True # Equations are complicated with NCARG # see https://www.ncl.ucar.edu/Applications/fcodes.shtml res.lbTitleString = "OOPE (J.kg~S~-1~N~.m~S~-2~N~)" # title of colorbar # Loop over communities for icom in comm: # Loop over size classes for isize in xrange(0, len(size_class) - 1): # Extract sizes comprised between the size class bound iw = np.nonzero((length >= size_class[isize]) & (length < size_class[isize+1]))[0] if iw.size == 0: continue # Integrate OOPE for the given community and given size class temp = oope[:, :, icom, iw] temp = np.sum(temp, axis=-1) # Finds the colorbar limits cmin, cmax = misc.find_percentile(temp, percentage=1) # draw the contour maps # defines the contour res.cnLevels = np.linspace(cmin, cmax, res.cnMaxLevelCount) mapplot = Ngl.contour_map(wks, temp, res) # add title title = 'Community=%s, %.2E m <= L < %.2E m' % (comm_string[icom], size_class[isize], size_class[isize + 1]) Ngl.text_ndc(wks, title, 0.5, 0.85, txres) # draws the map Ngl.draw(mapplot) # add a page to the pdf output Ngl.frame(wks)
def plot_rain_around_point(path, data_rain_tot_sum, hour_start, hour_end, point, stat_processing, member): if stat_processing == 'max': data_processed = (data_rain_tot_sum[hour_end, :, :] - data_rain_tot_sum[hour_start, :, :]).max(axis=0) elif stat_processing == 'member_extract': data_processed = data_rain_tot_sum[hour_end, member-1, :] - data_rain_tot_sum[hour_start, member-1, :] ######################################################################## if stat_processing == 'max': member_text_filename = 'max' elif stat_processing == 'member_extract': member_text_filename = 'm{:02d}'.format(member) plot_name = 'iconeueps_rain_{}_{:02d}Z-{:02d}Z_{}'.format(\ point['name'], hour_start+12, hour_end+12, member_text_filename) mpi_file = nc.Dataset(path['base'] + path['grid'] + 'icon_grid_0028_R02B07_N02.nc', 'r') vlat = mpi_file.variables['clat_vertices'][:].data * 180./np.pi vlon = mpi_file.variables['clon_vertices'][:].data * 180./np.pi clat = mpi_file.variables['clat'][:].data * 180./np.pi clon = mpi_file.variables['clon'][:].data * 180./np.pi mpi_file.close() ######################################################################## x_resolution = 800 y_resolution = 800 wks_res = Ngl.Resources() wks_res.wkWidth = x_resolution wks_res.wkHeight = y_resolution wks_type = 'png' wks = Ngl.open_wks(wks_type, path['base'] + path['plots'] + plot_name, wks_res) resources = Ngl.Resources() resources.mpProjection = 'Hammer' resources.mpCenterLonF = point['lon'] resources.mpCenterLatF = point['lat'] radius = 500 # image radius in km around centered point cutout_plot = dict( lat_min = point['lat'] - radius / 111.2, lat_max = point['lat'] + radius / 111.2, lon_min = point['lon'] - radius / (111.2 * np.cos(point['lat']*np.pi/180)), lon_max = point['lon'] + radius / (111.2 * np.cos(point['lat']*np.pi/180)), ) resources.mpLimitMode = 'latlon' resources.mpMinLonF = cutout_plot['lon_min'] resources.mpMaxLonF = cutout_plot['lon_max'] resources.mpMinLatF = cutout_plot['lat_min'] resources.mpMaxLatF = cutout_plot['lat_max'] resources.nglMaximize = False resources.vpXF = 0.05 resources.vpYF = 0.95 resources.vpWidthF = 0.7 resources.vpHeightF = 0.7 ######################################################################## # Turn on filled map areas: resources.mpFillOn = True # Set colors for [FillValue, Ocean, Land , InlandWater]: resources.mpFillColors = ['pink','blue','white','blue'] resources.mpDataBaseVersion = 'MediumRes' resources.mpDataSetName = 'Earth..4' resources.mpOutlineBoundarySets = 'national' resources.mpGeophysicalLineThicknessF = 7.0 * x_resolution / 1000 resources.mpNationalLineThicknessF = 7.0 * x_resolution / 1000 #resources.mpGridAndLimbDrawOrder = 'postdraw' resources.mpGridAndLimbOn = False #resources.mpLimbLineColor = 'black' #resources.mpLimbLineThicknessF = 10 #resources.mpGridLineColor = 'black' #resources.mpGridLineThicknessF = 1.0 #resources.mpGridSpacingF = 1 resources.mpPerimOn = True resources.mpPerimLineColor = 'black' resources.mpPerimLineThicknessF = 8.0 * x_resolution / 1000 resources.tmXBOn = False resources.tmXTOn = False resources.tmYLOn = False resources.tmYROn = False resources.sfDataArray = data_processed resources.sfXArray = clon resources.sfYArray = clat resources.sfXCellBounds = vlon resources.sfYCellBounds = vlat resources.sfMissingValueV = 9999 resources.cnFillOn = True resources.cnFillMode = 'CellFill' resources.cnCellFillEdgeColor = 'black' resources.cnMissingValFillColor = 'black' resources.cnFillPalette = 'WhiteBlueGreenYellowRed' resources.cnLevelSelectionMode = 'ManualLevels' minlevel = 0.0 maxlevel = 50.0 numberoflevels = 250 resources.cnMinLevelValF = minlevel resources.cnMaxLevelValF = maxlevel resources.cnLevelSpacingF = (maxlevel - minlevel) / numberoflevels # Turn off contour lines and labels: resources.cnLinesOn = False resources.cnLineLabelsOn = False # Set resources for a nice label bar resources.lbLabelBarOn = True resources.lbAutoManage = False resources.lbOrientation = 'vertical' resources.lbLabelOffsetF = 0.05 #resources.lbBoxMinorExtentF = 0.2 resources.lbLabelStride = 25 resources.lbLabelFontHeightF = 0.02 resources.lbBoxSeparatorLinesOn = False resources.lbBoxLineThicknessF = 4.0 #resources.lbBoxEndCapStyle = 'TriangleBothEnds' resources.lbLabelAlignment = 'BoxCenters' resources.lbTitleString = 'mm' resources.lbTitleFontHeightF = 0.02 resources.lbTitlePosition = 'Right' resources.lbTitleDirection = 'Across' resources.lbTitleAngleF = 90.0 resources.lbTitleExtentF = 0.1 resources.lbTitleOffsetF = 0.0 resources.nglFrame = False plot = Ngl.contour_map(wks, data_processed, resources) ######################################################################## polymarker_res_1 = Ngl.Resources() polymarker_res_1.gsMarkerColor = 'black' polymarker_res_1.gsMarkerIndex = 16 polymarker_res_1.gsMarkerSizeF = 0.012 polymarker_res_1.gsMarkerThicknessF = 1 Ngl.polymarker(wks, plot, point['lon'], point['lat'], polymarker_res_1) ######################################################################## polymarker_res_2 = Ngl.Resources() polymarker_res_2.gsMarkerColor = 'white' polymarker_res_2.gsMarkerIndex = 16 polymarker_res_2.gsMarkerSizeF = 0.008 polymarker_res_2.gsMarkerThicknessF = 1 Ngl.polymarker(wks, plot, point['lon'], point['lat'], polymarker_res_2) ######################################################################## if stat_processing == 'max': member_text = 'max member of each cell' elif stat_processing == 'member_extract': member_text = 'member {:d}'.format(member) text = 'rain_gsp + rain_con, 07.08.19 {}Z-{}Z, {}'.format(hour_start+12, hour_end+12, member_text) x = 0.1 y = 0.95 text_res_1 = Ngl.Resources() text_res_1.txFontHeightF = 0.02 text_res_1.txJust = 'BottomLeft' Ngl.text_ndc(wks, text, x, y, text_res_1) Ngl.frame(wks) Ngl.destroy(wks) return
# http://www.ncl.ucar.edu/Document/Manuals/NCL_User_Guide/Data/ # ''' Transition Guide Python Example: TRANS_xy_0.py - Drawing a xy plot 2018-08-21 kmf ''' import numpy import Ngl import os #-- define x and y variables x = [10., 20., 30., 40., 50., 60., 70., 80., 90.] y = numpy.array([0., 0.7, 1., 0.7, 0., -0.7, -1., -0.7, 0.], numpy.float32) #-- open a workstation wkres = Ngl.Resources() wks_type = "png" #-- output type of workstation wks = Ngl.open_wks(wks_type, os.path.basename(__file__).split('.')[0]) #-- set resources res = Ngl.Resources() #-- generate an res object for plot #-- draw the plot plot = Ngl.xy(wks, x, y, res) #-- done Ngl.end()
def rain_prf (ptype,cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs,casedir,varis,cscale,chscale,pname): # 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'] plotrain=['' 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 plotrain[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.tiMainFont = _Font res.tmXBLabelFontHeightF = 0.015 res.tmXBLabelFontThicknessF = 1.0 # res.tmXBLabelAngleF = 45 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 = 2500 pres.wkHeight = 2500 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 = False else: res.pmLegendDisplayMode = 'NEVER' 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) lev=inptrs.variables['lev'][:] nlev=len(lev) ncdf= Dataset(ncdfs[im],'r') n =ncdf.variables['n'][:] idx_cols=ncdf.variables['idx_cols'][:,:] 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 tmp=inptrs.variables[varis[iv]][0,:,npoint] theunits=str(chscale[iv])+'x'+inptrs.variables[varis[iv]].units 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, :])) # res.trXMaxF = max(np.max(A_field[0, :])) 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 = pname+' at'+ str(lons[ire])+'E,'+str(lats[ire])+'N' txres = Ngl.Resources() txres.txFontHeightF = 0.020 txres.txFont = _Font Ngl.text_ndc(wks,pname+' at'+ str(lons[ire])+'E,'+str(lats[ire])+'N',0.5,0.92+ncases*0.01,txres) Common_functions.create_legend(wks,casenames,np.arange(3,20,2),0.1,0.89+ncases*0.01) Ngl.panel(wks,plot[:],[nvaris/2,2],pres) Ngl.frame(wks) Ngl.destroy(wks) return plotrain
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]+'/'+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)
# Open a workstation. # wks_type = "png" wks = Ngl.open_wks(wks_type, "color5") # # Define our own color table going around # all the hues in the HLS color space, starting # with blue. # for k in range(0, niter): h = 360 * float(k) / float(niter) r, g, b = Ngl.hlsrgb(h, 50., 100.) Ngl.set_color(wks, k, r, g, b) # # Create the set and draw the color cells. # poly_res = Ngl.Resources() for j in range(ny): for i in range(nx): x, y = get_cell(i, j, xl, xr, yb, yt, nx, ny) iter = convg(complex(x[0], y[0]), niter, 0.001, 10000) poly_res.gsFillColor = iter - 1 # iter will be at least one. for i in range(len(x)): x[i], y[i] = user2ndc(x[i], y[i]) Ngl.polygon_ndc(wks, x, y, poly_res) Ngl.frame(wks) Ngl.end()
from __future__ import print_function import numpy,os # # Import Ngl,Nio support functions. # import Ngl, Nio wks_type = "png" wks = Ngl.open_wks (wks_type,"shapefile1") Ngl.define_colormap(wks,"rainbow+gray") # # Map resources. # res = Ngl.Resources() res.mpProjection = "LambertConformal" res.mpLambertParallel1F = 33 # two parallels res.mpLambertParallel2F = 45 res.mpLambertMeridianF = -98 # central meridian res.mpLimitMode = "Corners" # limit map via two opposite corners res.mpLeftCornerLatF = 22 # left corner res.mpLeftCornerLonF = -125 # left corner res.mpRightCornerLatF = 50 # right corner res.mpRightCornerLonF = -64 # right corner res.mpFillOn = True # Turn on fill for map areas. res.mpLandFillColor = "LightGray"
ncdf = Nio.open_file(os.path.join(dirc, "cdf", "scatter1.nc"), "r") x = ncdf.variables["x"][:] y = ncdf.variables["y"][:] colors = ncdf.variables["colors"][:] color_index = colors.astype('i') # # Open an output workstation. # wks_type = "png" wks = Ngl.open_wks(wks_type, "scatter1") # # Label the plot. # resources = Ngl.Resources() resources.tiMainString = "2000 Mar 19 1040-1725Z" resources.tiMainFont = "helvetica-bold" resources.tiXAxisString = "Cloud Thickness (m)" resources.tiXAxisFont = "helvetica-bold" resources.tiYAxisString = "Liquid Water Path (mm)" resources.tiYAxisFont = "helvetica-bold" resources.tiXAxisFontHeightF = 0.025 # Change the font size. resources.tiYAxisFontHeightF = 0.025 resources.xyLineColors = "black" # Set the line colors. resources.xyMonoLineThickness = True # Set the line colors. resources.xyLineThicknessF = 3.0 # Triple the width. resources.tmXBMajorLengthF = 0.02 # Force tickmarks to point resources.tmXBMajorOutwardLengthF = 0.02 # out by making the outward
[ 0, 255, 255], "Cyan", \ [ 79, 148, 205], "SteelBlue3", \ [ 0, 0, 255], "Blue", \ [148, 0, 211], "DarkViolet", \ [255, 0, 255], "Magneta", \ [255, 255, 255], "White", \ [153, 153, 153], "Gray60", \ [102, 102, 102], "Gray40", \ [ 0, 0, 0], "Black" \ ] # # Open a workstation with a default color table having # background color "black" and foreground color "white". # rlist = Ngl.Resources() rlist.wkColorMap = "default" rlist.wkForegroundColor = "White" rlist.wkBackgroundColor = "Black" wks_type = "png" wks = Ngl.open_wks(wks_type, "color4", rlist) # # Extract the colors and labels. # colors = colors_and_labels[0:len(colors_and_labels):2] labels = colors_and_labels[1:len(colors_and_labels):2] # # Set up arrays and resource lists for drawing the boxes. # Select "Helvetica-Bold" for all text.
for i in range(0, len(lon)): lat2d[:, i] = lat for i in range(0, len(lat)): lon2d[i, :] = lon # open workspace for forecast plots wks_type = "png" wks = ngl.open_wks( wks_type, "GFSanalysis_%s_%s_dewpoint_%shPa" % (region, init_dt[0:10], lev_hPa)) # define resources for forecast plots 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.cnFillPalette = cmap[:30:-1] res.pmTickMarkDisplayMode = "Never" res.cnInfoLabelOn = False res.cnFillOn = True res.cnLineLabelsOn = False
xo = numpy.arange(xl, xr + 0.0001, inc) # Create output X coordinate array. # Add a small amount to xr to make # sure xr is the final value in the # range. period = 3.0 yo = Ngl.ftcurvp(xi, yi, period, xo) # Interpolate. yint = numpy.zeros(npts, 'f') for i in xrange(npts): yint[i] = Ngl.ftcurvpi(0., xo[i], period, xi, yi) # Send graphics to PNG file wks_type = "png" wks = Ngl.open_wks(wks_type, "ngl07p") txres = Ngl.Resources() # Set up variable for TextItem resources. xyres = Ngl.Resources() # Set up variable for XyPlot resources. gsres = Ngl.Resources() # Set up variable for GraphicStyle resources. xyres.nglFrame = False # Don't advance the frame. xyres.nglMaximize = False # Don't advance the frame. xyres.tmXTBorderOn = False # Don't draw top axis. xyres.tmXTOn = False # Don't draw top axis tick marks. xyres.tmBorderThicknessF = 1.0 # Default thickness is 2.0 xyres.tmXBLabelFont = 21 # Change font and size of xyres.tmXBLabelFontHeightF = 0.025 # X axis labels. xyres.tmXBMajorLengthF = 0.015 # Default is 0.02. xyres.tmXBMajorThicknessF = 1.0 # Default is 2. xyres.tmXBMinorLengthF = 0.0075 # Default is 0.01.
# This example produces two visualizations: # 1.) Cylindrical Equidistant projection # 2.) Mollweide projection # # Notes: # from __future__ import print_function import Ngl wks_type = "png" 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 range(len(projections)): mpres.mpProjection = projections[i] mpres.tiMainString = projections[i] map = Ngl.map(wks, mpres) Ngl.end()
def add_labels_lcm(wks,map,dlat,dlon): PI = 3.14159 RAD_TO_DEG = 180./PI #-- determine whether we are in northern or southern hemisphere if (float(minlat) >= 0. and float(maxlat) > 0.): HEMISPHERE = "NH" else: HEMISPHERE = "SH" #-- pick some "nice" values for the latitude labels. lat_values = np.arange(int(minlat),int(maxlat),10) lat_values = lat_values.astype(float) nlat = len(lat_values) #-- We need to get the slope of the left and right min/max longitude lines. #-- Use NDC coordinates to do this. lat1_ndc = 0. lon1_ndc = 0. lat2_ndc = 0. lon2_ndc = 0. lon1_ndc,lat1_ndc = Ngl.datatondc(map,minlon,lat_values[0]) lon2_ndc,lat2_ndc = Ngl.datatondc(map,minlon,lat_values[nlat-1]) slope_lft = (lat2_ndc-lat1_ndc)/(lon2_ndc-lon1_ndc) lon1_ndc,lat1_ndc = Ngl.datatondc(map,maxlon,lat_values[0]) lon2_ndc,lat2_ndc = Ngl.datatondc(map,maxlon,lat_values[nlat-1]) slope_rgt = (lat2_ndc-lat1_ndc)/(lon2_ndc-lon1_ndc) #-- set some text resources txres = Ngl.Resources() txres.txFontHeightF = 0.01 txres.txPosXF = 0.1 #-- Loop through lat values, and attach labels to the left and right edges of #-- the masked LC plot. The labels will be rotated to fit the line better. dum_lft = [] #-- assign arrays dum_rgt = [] #-- assign arrays lat_label_lft = [] #-- assign arrays lat_label_rgt = [] #-- assign arrays for n in range(0,nlat): #-- left label if(HEMISPHERE == "NH"): rotate_val = -90. direction = "N" else: rotate_val = 90. direction = "S" #-- add extra white space to labels lat_label_lft.append("{}~S~o~N~{} ".format(str(np.abs(lat_values[n])),direction)) lat_label_rgt.append(" {}~S~o~N~{}".format(str(np.abs(lat_values[n])),direction)) txres.txAngleF = RAD_TO_DEG * np.arctan(slope_lft) + rotate_val dum_lft.append(Ngl.add_text(wks,map,lat_label_lft[n],minlon,lat_values[n],txres)) #-- right label if(HEMISPHERE == "NH"): rotate_val = 90 else: rotate_val = -90 txres.txAngleF = RAD_TO_DEG * np.arctan(slope_rgt) + rotate_val dum_rgt.append(Ngl.add_text(wks,map,lat_label_rgt[n],maxlon,lat_values[n],txres)) #---------------------------------------------------------------------- # Now do longitude labels. These are harder because we're not adding # them to a straight line. # Loop through lon values, and attach labels to the bottom edge for # northern hemisphere, or top edge for southern hemisphere. #---------------------------------------------------------------------- del(txres.txPosXF) txres.txPosYF = -5.0 #-- pick some "nice" values for the longitude labels lon_values = np.arange(int(minlon+10),int(maxlon-10),10).astype(float) lon_values = np.where(lon_values > 180, 360-lon_values, lon_values) nlon = lon_values.size dum_bot = [] #-- assign arrays lon_labels = [] #-- assign arrays if(HEMISPHERE == "NH"): lat_val = minlat else: lat_val = maxlat ctrl = "~C~" for n in range(0,nlon): if(lon_values[n] < 0): if(HEMISPHERE == "NH"): lon_labels.append("{}~S~o~N~W{}".format(str(np.abs(lon_values[n])),ctrl)) else: lon_labels.append("{}{}~S~o~N~W".format(ctrl,str(np.abs(lon_values[n])))) elif(lon_values[n] > 0): if(HEMISPHERE == "NH"): lon_labels.append("{}~S~o~N~E{}".format(str(lon_values[n]),ctrl)) else: lon_labels.append("{}{}~S~o~N~E".format(ctrl,str(lon_values[n]))) else: if(HEMISPHERE == "NH"): lon_labels.append("{}0~S~o~N~{}".format(ctrl,ctrl)) else: lon_labels.append("{}0~S~o~N~{}".format(ctrl,ctrl)) #-- For each longitude label, we need to figure out how much to rotate #-- it, so get the approximate slope at that point. if(HEMISPHERE == "NH"): #-- add labels to bottom of LC plot lon1_ndc,lat1_ndc = Ngl.datatondc(map, lon_values[n]-0.5, minlat) lon2_ndc,lat2_ndc = Ngl.datatondc(map, lon_values[n]+0.5, minlat) txres.txJust = "TopCenter" else: #-- add labels to top of LC plot lon1_ndc,lat1_ndc = Ngl.datatondc(map, lon_values[n]+0.5, maxlat) lon2_ndc,lat2_ndc = Ngl.datatondc(map, lon_values[n]-0.5, maxlat) txres.txJust = "BottomCenter" slope_bot = (lat1_ndc-lat2_ndc)/(lon1_ndc-lon2_ndc) txres.txAngleF = RAD_TO_DEG * np.arctan(slope_bot) #-- attach to map dum_bot.append(Ngl.add_text(wks, map, str(lon_labels[n]), \ lon_values[n], lat_val, txres)) return
t = f.t[0, 0, :, :].values rhum = f.rhumidity[0, 0, :, :].values lat = f.lat.values lon = f.lon.values ###f = Nio.open_file("rectilinear_grid_3D.nc", "r") ###t = f.variables["t"][0,0,:,:] ###rhum = f.variables["rhumidity"][0,0,:,:] ###lat = f.variables["lat"][:] ###lon = f.variables["lon"][:] #-- define workstation wks = Ngl.open_wks("png", os.path.basename(__file__).split('.')[0]) #-- plot resources for the map mpres = Ngl.Resources() mpres.nglDraw = False #-- don't draw plot mpres.nglFrame = False #-- don't advance frame mpres.mpOutlineOn = True #-- turn on map outlines mpres.mpGeophysicalLineColor = "gray50" #-- map outline color mpres.mpLimitMode = "LatLon" #-- limit map via lat/lon mpres.mpMinLatF = 20.0 #-- min lat mpres.mpMaxLatF = 60.0 #-- max lat mpres.mpMinLonF = -10.0 #-- min lon mpres.mpMaxLonF = 40.0 #-- max lon #-- plot resources for the temperature plot tres = Ngl.Resources() tres.nglDraw = False #-- don't draw plot tres.nglFrame = False #-- don't advance frame tres.cnFillOn = True #-- turn on color fill
def plot_Robinson_pyngl(var, lon, lat, wks_name='plot', clim=None, cspace=None, cmap=None): # # Select a colormap and open a workstation. # rlist = Ngl.Resources() wks_type = "png" wks = Ngl.open_wks(wks_type, wks_name, rlist) if cmap is None: mycmap = 'BlAqGrYeOrReVi200' Ngl.define_colormap(wks, mycmap) else: try: mycmap = '/Users/frederic/python/cmap/' + cmap mycmap = np.loadtxt(mycmap) except: mycmap = cmap try: Ngl.define_colormap(wks, mycmap) except: raise Warning, 'Unknown colormap' # # The next set of resources will apply to the contour plot and the labelbar. # resources = Ngl.Resources() resources.sfXArray = lon resources.sfYArray = lat resources.gsnMaximize = True # use full page resources.cnFillOn = True resources.cnFillMode = "RasterFill" resources.cnMaxLevelCount = 255 resources.cnLinesOn = False resources.cnLineLabelsOn = False if clim is not None: resources.cnLevelSelectionMode = "ManualLevels" # set manual contour levels resources.cnMinLevelValF = clim[0] # set min contour level resources.cnMaxLevelValF = clim[1] # set max contour level if cspace is None: LevelSpacing = (clim[1] - clim[0]) / 100. resources.cnLevelSpacingF = LevelSpacing # set contour spacing else: resources.cnLevelSpacingF = cspace # set contour spacing resources.lbOrientation = "Horizontal" # Default is vertical. resources.lbBoxLinesOn = False resources.lbLabelFontHeightF = 0.01 # label font height resources.lbBoxMinorExtentF = 0.15 # # The contour plot is not very interesting, so don't draw it. # resources.nglDraw = False resources.nglFrame = False contour = Ngl.contour(wks, var, resources) # # Retrieve the actual lat/lon end points of the scalar array so # we know where to overlay on map. # xs = Ngl.get_float(contour.sffield, "sfXCActualStartF") xe = Ngl.get_float(contour.sffield, "sfXCActualEndF") ys = Ngl.get_float(contour.sffield, "sfYCActualStartF") ye = Ngl.get_float(contour.sffield, "sfYCActualEndF") resources.nglDraw = True # Turn these resources back on. resources.nglFrame = True resources.mpProjection = "Robinson" resources.mpCenterLonF = 270 resources.mpCenterLatF = 0 resources.mpGeophysicalLineThicknessF = 2 map = Ngl.contour_map(wks, var, resources) Ngl.end()
import numpy wks_type = "png" wks = Ngl.open_wks(wks_type, "format") # # Create some dummy data for an XY plot. We are only doing this # to create an object that has tickmarks. # x = Ngl.fspan(0, 1, 20) y = x # # Set some resouces for a dummy XY plot. # res = Ngl.Resources() res.nglMaximize = False res.nglDraw = False res.nglFrame = False res.xyLineColor = -1 # Transparent line # # Resources for main title and Y axis title. # res.tiMainFont = "Helvetica-Bold" res.tiMainFontHeightF = 0.015 res.tiMainJust = "CenterLeft" res.tiMainPosition = "Left" res.tiYAxisAngleF = 0.0 res.tiYAxisFont = "Courier-Bold"
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 imagename = "GFSanalysis_%s_%s_CAPECIN_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.tmXBOn = False #res.tmXTOn = False #res.tmYLOn = False #res.tmYROn = False res.vpWidthF = 0.9
N = 25 T = numpy.zeros((N, N), 'f') jspn = numpy.power(numpy.arange(-12, 13), 2) ispn = numpy.power(numpy.arange(-12, 13), 2) for i in range(0, len(ispn)): T[i, :] = (jspn + ispn[i]).astype('f') T = 100.0 - numpy.sqrt(64 * T) # # Open the workstation and change the color map. # rlist = Ngl.Resources() rlist.wkColorMap = "default" wks_type = "png" wks = Ngl.open_wks(wks_type, "contour2", rlist) cnres = Ngl.Resources() cnres.cnFillOn = True # Turn on contour level fill. cnres.cnMonoFillPattern = False # Indicate you want multiple fill patterns. # # Set cnFillPatterns and cnFillColors to various indexes representing # fill patterns and colors. A fill pattern index of "0" is solid fill. # If you don't want any fill for a particular contour level, set it # to "-1," which means "transparent." #
del latVertex, lonVertex, verticesOnCell #---Debug prints print("This MPAS file has {} cells.".format(nCells)) print_min_max(t2m, "t2m") print_min_max(latCell, "latCell") print_min_max(lonCell, "lonCell") print_min_max(latvoc, "latvoc") print_min_max(lonvoc, "lonvoc") #---Start the graphics wks_type = "png" wks = Ngl.open_wks(wks_type, "mpas2") res = Ngl.Resources() # Plot mods desired. res.nglDraw = False # Turn off plot draw and frame advance. We will res.nglFrame = False # do it later after adding subtitles. res.cnFillOn = True # color plot desired res.cnFillPalette = "ncl_default" res.cnLinesOn = False # turn off contour lines res.cnLineLabelsOn = False # turn off contour labels res.cnLevelSelectionMode = "ExplicitLevels" res.cnLevels = Ngl.fspan(min(t2m), max(t2m), 253) # 253 levels (hence 254 colors) res.lbOrientation = "Horizontal" # vertical by default res.lbBoxLinesOn = False # turn off labelbar boxes
def __init__(self, grid, title): """ Initialize an instance of MapPlots. Plotting of maps is powered by PyNGL. :type grid: :class:`.Grid` :arg grid: The Grid object describing the map data to be plotted. :arg str title: The title describing the map data. """ self.grid = grid """(Grid) - The Grid object describing the map data to be plotted.""" self.title = title """(string) - The title describing the map data.""" # Initialize list to store data sets and titles self.map_data = [] """(list) - The list storing map data and titles.""" # Also for multiple maps self.map_mult_data = [] """(list) - The list storing map data and titles for multiple maps.""" # # Adjust PyNGL settings, fine tuning can be done externally # # Set PyNGL resources resources = Ngl.Resources() # Define grid resources.sfXArray = self.grid.lon_sequence() resources.sfYArray = self.grid.lat_sequence() # Change the map projection resources.mpProjection = "Robinson" # Rotate the projection # Center in the middle of lonMin and lonMax # resources.mpRelativeCenterLon = "true" # Set plot limits resources.mpLimitMode = "LatLon" resources.mpMinLonF = self.grid.boundaries()["lon_min"] resources.mpMaxLonF = self.grid.boundaries()["lon_max"] resources.mpMinLatF = self.grid.boundaries()["lat_min"] resources.mpMaxLatF = self.grid.boundaries()["lat_max"] # Change the color map resources.wkColorMap = "wh-bl-gr-ye-re" # Change thickness of geophysical lines resources.mpGeophysicalLineThicknessF = 2.0 # Configure the legend resources.lbAutoManage = False resources.lbOrientation = "Horizontal" resources.lbLabelFont = "Helvetica" resources.lbLabelFontHeightF = 0.0075 resources.lbTitleFontHeightF = 0.01 # Larger font for regional networks # resources.lbLabelFontHeightF = 0.014 # resources.lbTitleFontHeightF = 0.02 # Configure the contour plots resources.cnFillOn = True resources.cnLinesOn = False resources.cnLineLabelsOn = False resources.cnInfoLabelOn = False resources.cnMaxLevelCount = 22 resources.cnFillMode = "RasterFill" # Make resources object accessible from outside self.resources = resources """The PyNGL resources allow fine tuning of plotting options."""
# cmap = numpy.array([[1.00,.000,.000],\ [.950,.010,.000],[.870,.050,.000],[.800,.090,.000],\ [.700,.090,.000],[.700,.120,.000],[.700,.180,.000],\ [.700,.260,.000],[.700,.285,.000],[.680,.330,.000],\ [.570,.420,.000],[.560,.530,.000],[.550,.550,.000],\ [.130,.570,.000],[.060,.680,.000],[.000,.690,.000],\ [.000,.700,.100],[.000,.600,.300],[.000,.500,.500],\ [.000,.400,.700],[.000,.300,.700],[.000,.200,.700],\ [.000,.100,.700],[.000,.000,.700],[.100,.100,.700],\ [.200,.200,.700],[.300,.300,.700],[.420,.400,.700],\ [.560,.500,.700],[.610,.600,.700],[.700,.700,.700]], 'f') #--- Indicate where to send graphics rlist = Ngl.Resources() wks_type = "png" wks = Ngl.open_wks(wks_type, "panel1", rlist) # # Turn off draw for the individual plots, since we are going to # panel them later. # resources = Ngl.Resources() resources.nglDraw = False resources.nglFrame = False # # Loop through the timesteps and create each plot, titling each # one according to which timestep it is. #
# A single visualization with two XY curves # 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 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.txAngleF = 45. txid = Ngl.add_text(wks,plot,"Preliminary Data",10,15,txres) Ngl.draw(plot) # Drawing plot will draw attached text Ngl.frame(wks) # Advance frame
def grid_order_contourplot(model, grid, first_varying_var, cut_domain): # define paths # path = dict(base='/', plots='data/plots/experimental/gridpoint_order/') print('plotting model: {}'.format(model)) # load icosahedral grid information # if grid == 'icosahedral': clat, clon, vlat, vlon = read_grid_coordinates(model, grid) data_array1 = np.arange(clat.shape[0], dtype='float32') else: clat, clon = read_grid_coordinates(model, grid) clon = clon - 180 if first_varying_var == 'lon': data_array1 = np.arange(clat.shape[0] * clon.shape[0], dtype='float32').reshape( (clat.shape[0], clon.shape[0])) elif first_varying_var == 'lat': data_array1 = np.arange(clat.shape[0] * clon.shape[0], dtype='float32').reshape( (clon.shape[0], clat.shape[0])).T print('data_array1:', data_array1.shape, 'clat:', clat.shape, 'clon:', clon.shape) if grid == 'icosahedral': print('vlat:', vlat.shape, 'vlon:', vlon.shape) print('data_array1 min,max:', data_array1.min(), data_array1.max()) print('clat min,max:', clat.min(), clat.max()) print('clon min,max:', clon.min(), clon.max()) if grid == 'icosahedral': print('vlat min,max:', vlat.min(), vlat.max()) print('vlon min,max:', vlon.min(), vlon.max()) print('------------------------------------------') if cut_domain['name'] == 'uncut': data_array1_cut = data_array1 else: margin_deg = 0 if grid == 'icosahedral': data_array1_cut, clat, clon, vlat, vlon \ = cut_by_domain(cut_domain, grid, data_array1, clat, clon, vlat, vlon, margin_deg) else: data_array1_cut, clat, clon \ = cut_by_domain(cut_domain, grid, data_array1, clat, clon, None, None, margin_deg) print('data_array1:', data_array1_cut.shape, 'clat:', clat.shape, 'clon:', clon.shape) if grid == 'icosahedral': print('vlat:', vlat.shape, 'vlon:', vlon.shape) print('data_array1_cut min,max:', data_array1_cut.min(), data_array1_cut.max()) print('clat min,max:', clat.min(), clat.max()) print('clon min,max:', clon.min(), clon.max()) if grid == 'icosahedral': print('vlat min,max:', vlat.min(), vlat.max()) print('vlon min,max:', vlon.min(), vlon.max()) if grid == 'icosahedral': plot_name = 'gridpoint_order_{}_{}_global_{}'.format( model, grid, cut_domain['name']) else: plot_name = 'gridpoint_order_{}_{}_{}-varying-first_global_{}'.format( model, grid, first_varying_var, cut_domain['name']) # plot basic map with borders # wks_res = Ngl.Resources() x_resolution = 800 y_resolution = 800 wks_res.wkWidth = x_resolution wks_res.wkHeight = y_resolution wks_res.wkColorMap = 'BkBlAqGrYeOrReViWh200' levels1 = np.linspace(data_array1.min(), data_array1.max(), 200) wks_type = 'png' wks = Ngl.open_wks(wks_type, path['base'] + path['plots'] + plot_name, wks_res) mpres = Ngl.Resources() mpres.mpProjection = 'CylindricalEquidistant' mpres.mpLimitMode = 'LatLon' mpres.mpCenterLonF = 0.0 mpres.mpCenterLatF = 0.0 mpres.mpMinLonF = -180. mpres.mpMaxLonF = 180. mpres.mpMinLatF = -90. mpres.mpMaxLatF = 90. mpres.nglMaximize = False mpres.vpXF = 0.003 mpres.vpYF = 1.00 mpres.vpWidthF = 0.86 mpres.vpHeightF = 1.00 mpres.mpMonoFillColor = 'True' mpres.mpFillColor = -1 #Ngl.set_values(wks,mpres) mpres.mpFillOn = True #resources.cnFillDrawOrder = 'Predraw' # draw contours first mpres.mpGridAndLimbOn = False mpres.mpGreatCircleLinesOn = False #mpres.mpOutlineDrawOrder = 'PreDraw' mpres.mpDataBaseVersion = 'LowRes' mpres.mpDataSetName = 'Earth..4' mpres.mpOutlineBoundarySets = 'national' mpres.mpGeophysicalLineColor = 'black' mpres.mpNationalLineColor = 'black' mpres.mpGeophysicalLineThicknessF = 2. * x_resolution / 1000 mpres.mpNationalLineThicknessF = 2. * x_resolution / 1000 mpres.mpPerimOn = True mpres.mpPerimLineColor = 'black' mpres.mpPerimLineThicknessF = 8.0 * x_resolution / 1000 mpres.tmXBOn = False mpres.tmXTOn = False mpres.tmYLOn = False mpres.tmYROn = False mpres.nglDraw = False #-- don't draw plot mpres.nglFrame = False #-- don't advance frame basic_map = Ngl.map(wks, mpres) # plot variable1 in shading/contours # v1res = Ngl.Resources() v1res.sfDataArray = data_array1_cut v1res.sfXArray = clon v1res.sfYArray = clat if grid == 'icosahedral': v1res.cnFillMode = 'CellFill' v1res.sfXCellBounds = vlon v1res.sfYCellBounds = vlat else: v1res.cnFillMode = 'RasterFill' v1res.sfMissingValueV = 9999 v1res.cnLinesOn = False # Turn off contour lines. v1res.cnFillOn = True #v1res.cnFillOpacityF = 0.5 #v1res.cnFillDrawOrder = 'Predraw' v1res.cnLineLabelsOn = False v1res.cnLevelSelectionMode = 'ExplicitLevels' v1res.cnLevels = levels1 # set resources for a nice label bar # v1res.lbLabelBarOn = True v1res.lbAutoManage = False v1res.lbOrientation = 'vertical' v1res.lbLabelOffsetF = 0.04 # minor axis fraction: the distance between colorbar and numbers v1res.lbBoxMinorExtentF = 0.20 # minor axis fraction: width of the color boxes when labelbar down v1res.lbTopMarginF = 0.05 # make a little more space at top for the unit label v1res.lbRightMarginF = 0.0 v1res.lbBottomMarginF = 0.0 v1res.lbLeftMarginF = -0.35 v1res.cnLabelBarEndStyle = 'ExcludeOuterBoxes' #v1res.cnLabelBarEndStyle = 'IncludeOuterBoxes' #v1res.cnExplicitLabelBarLabelsOn = True #v1res.pmLabelBarDisplayMode = 'Always' v1res.pmLabelBarWidthF = 0.10 #v1res.lbLabelStrings = label_str_list v1res.lbLabelFontHeightF = 0.010 #v1res.lbBoxCount = 40 v1res.lbBoxSeparatorLinesOn = False v1res.lbBoxLineThicknessF = 4 #v1res.lbBoxEndCapStyle = 'TriangleBothEnds' v1res.lbLabelAlignment = 'InteriorEdges' v1res.lbLabelStride = 1 v1res.nglFrame = False v1res.nglDraw = False v1plot = Ngl.contour(wks, data_array1_cut, v1res) # plot label bar unit # text_str = 'Index' text_res_1 = Ngl.Resources() text_res_1.txFontColor = 'black' text_x = 0.975 text_y = 0.72 text_res_1.txFontHeightF = 0.012 Ngl.overlay(basic_map, v1plot) Ngl.draw(basic_map) Ngl.text_ndc(wks, text_str, text_x, text_y, text_res_1) Ngl.frame(wks) Ngl.destroy(wks) #Ngl.end() # cut top and bottom whitespace of plot # im = Image.open(path['base'] + path['plots'] + plot_name + '.png') image_array = np.asarray(im.convert('L')) image_array = np.where(image_array < 255, 1, 0) image_filter = np.amax(image_array, axis=1) vmargins = [ np.nonzero(image_filter)[0][0], np.nonzero(image_filter[::-1])[0][0] ] #print(vmargins) #print(im.size) im_cropped = Image.new( 'RGB', (im.size[0], im.size[1] - vmargins[0] - vmargins[1]), (255, 255, 255)) im_cropped.paste( im.crop((0, vmargins[0], im.size[0], im.size[1] - vmargins[1])), (0, 0)) #print(im_cropped.size) im.close() im_cropped.save(path['base'] + path['plots'] + plot_name + '.png', 'png') im_cropped.close() del data_array1, data_array1_cut, clat, clon if grid == 'icosahedral': del vlat, vlon return
# # Import PyNGL support functions. # import Ngl import os, string, types # Read data off file. filename = os.path.join(Ngl.pynglpath("data"), "asc", "fcover.dat") data = Ngl.asciiread(filename, [3, 73, 73], "float") # Send graphics to PNG file wks_type = "png" wks = Ngl.open_wks(wks_type, "streamline2") stres = Ngl.Resources() cnres = Ngl.Resources() mpres = Ngl.Resources() cnres.nglDraw = False cnres.nglFrame = False mpres.nglDraw = False mpres.nglFrame = False stres.nglDraw = False stres.nglFrame = False # Set sf/vf resources to indicate where on map to overlay. cnres.sfXCStartV = -180. cnres.sfXCEndV = 180. cnres.sfYCStartV = -90. cnres.sfYCEndV = 90.
#-- information print("") print("Cell points: ", nv) print("Cells: ", str(ncells)) print("Variable ta min/max: %.2f " % np.min(var) + "/" + " %.2f" % np.max(var)) print("") #-- open a workstation wks_type = "x11" #-- graphics output type wks = Ngl.open_wks(wks_type, "plot_contour_unstructured_PyNGL") #-- open a workstation #-- set resources res = Ngl.Resources() #-- plot mods desired. res.nglDraw = False #-- turn off plot draw and frame advance. We will res.nglFrame = False #-- do it later after adding subtitles. res.cnFillOn = True #-- color plot desired res.cnFillMode = "CellFill" #-- set fill mode res.cnFillPalette = "BlueWhiteOrangeRed" #-- choose colormap res.cnLinesOn = False #-- turn off contour lines res.cnLineLabelsOn = False #-- turn off contour labels res.cnLevelSelectionMode = "ExplicitLevels" #-- use explicit levels res.cnLevels = levels #-- set levels res.lbOrientation = "Horizontal" #-- vertical by default res.lbBoxLinesOn = False #-- turn off labelbar boxes res.lbLabelFontHeightF = 0.01 #-- labelbar label font size
# ---Values to use for contour labelbar if plotType == 4: varMin = -0.5 # Data mins elif plotType == 6: varMin = -1.5 # Data mins varMax = 4 # Data maxs varInt = 0.5 # 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) # Create resource list for customizing contour over maps res = Ngl.Resources() res.nglMaximize = False res.nglFrame = False res.nglDraw = False res.sfXArray = lon res.sfYArray = lat res.sfMissingValueV = -99999 # Title res.tiMainFont = "Helvetica-Bold" res.tiMainFontHeightF = 0.015 # res.tiMainOffsetYF = 0.02 # Map
- Drawing a map - Drawing polylines - Drawing polygons - Drawing all available (16) polymarkers 2018-09-11 kmf ''' import Ngl import os #-- open a workstation and define colormap wks = Ngl.open_wks("png", os.path.basename(__file__).split('.')[0]) #-- set resources res = Ngl.Resources() res.nglDraw = False #-- don't draw the plot yet res.nglFrame = False #-- don't advance the frame yet res.mpFillOn = True res.mpOutlineOn = False res.mpOceanFillColor = "Transparent" res.mpLandFillColor = "Gray80" res.mpInlandWaterFillColor = "Gray80" res.mpGridAndLimbOn = False #-- don't draw grid lines res.pmTickMarkDisplayMode = "Always" #-- turn on map tickmark #-- create the map, but don't draw it yet map = Ngl.map(wks, res)
cdf_file = Nio.open_file(os.path.join(data_dir, "cdf", "ocean.nc")) T = ma.masked_values(cdf_file.variables["T"][:, :], cdf_file.variables["T"]._FillValue) lat_t = cdf_file.variables["lat_t"][:] z_t = cdf_file.variables["z_t"][:] / 100. # convert cm to m # # Open a workstation. # wks_type = "png" wks = Ngl.open_wks(wks_type, "irregular") # # Set up a resource list for plot options. # resources = Ngl.Resources() resources.sfXArray = lat_t resources.sfYArray = z_t resources.cnFillOn = True resources.cnFillPalette = "gui_default" resources.cnLineLabelsOn = False resources.tiMainString = "Default axes" # main title # # Draw the plot as is, with no transformations in place. # plot = Ngl.contour(wks, T, resources)
# wks_type = "png" wks = Ngl.open_wks(wks_type,"ngl11p") dirc = Ngl.pynglpath("data") data = Ngl.asciiread(dirc+"/asc/u.cocos",(39,14),"float") pressure = data[:,0] # First column of data is pressure (mb). height = data[:,1] # Second column is height (km). u = data[:,2:14] # Rest of columns are climatological zonal winds # (u: m/s) unew = Ngl.add_cyclic(u) # Add cyclic points to u. #----------- Begin first plot ----------------------------------------- resources = Ngl.Resources() resources.tiMainString = "~F26~Cocos Island" # Main title. resources.tiYAxisString = "~F25~Pressure (mb)" # Y axes label. resources.sfYCStartV = float(max(pressure)) # Indicate start and end of left resources.sfYCEndV = float(min(pressure)) # Y axes values. resources.trYReverse = True # Reverse the Y values. resources.trYLog = True # Use log scale. resources.tmXBMode = "Explicit" # Define your own tick mark labels. resources.tmXBLabelFont = "times-roman" # Change font of labels. resources.tmXBLabelFontHeightF = 0.015 # Change font height of labels. resources.tmXBMinorOn = False # No minor tick marks. resources.tmXBValues = range(0,13,1) # Location to put tick mark labels