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 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 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 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 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()
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
wkres.wkColorMap = "rainbow+gray" Ngl.set_values(wks,wkres) vcres.nglSpreadColorStart = 24 vcres.nglSpreadColorEnd = -2 # Don't include last color, which is gray vcres.mpOceanFillColor = "Transparent" vcres.mpLandFillColor = "Gray" vcres.vcRefAnnoArrowLineColor = "Black" vcres.vcMaxLevelCount = 23 vcres.vcMonoLineArrowColor = False vcres.tiMainString = "Curly vectors colored by magnitude" plot = Ngl.vector_map(wks,u,v,vcres) # # Change to filled arrows. # vcres.vcGlyphStyle = "FillArrow" vcres.vcMonoFillArrowFillColor = False vcres.vcRefMagnitudeF = 0.0 vcres.vcRefAnnoOrthogonalPosF = -0.20 vcres.tiMainString = "Filled arrows" plot = Ngl.vector_map(wks,u,v,vcres) Ngl.end()
#---Open file for graphics wks_type = "png" wks = Ngl.open_wks(wks_type, "wrf3") # Set some map options based on information in WRF output file res = get_pyngl(tc) res.tfDoNDCOverlay = True # required for native projection #---Contour options res.cnFillOn = True # turn on contour fill res.cnLinesOn = False # turn off contour lines res.cnLineLabelsOn = False # turn off line labels res.cnFillMode = "RasterFill" # These two resources res.trGridType = "TriangularMesh" # can speed up plotting. res.cnFillPalette = "ncl_default" res.lbOrientation = "horizontal" # default is vertical res.pmLabelBarHeightF = 0.08 res.pmLabelBarWidthF = 0.65 res.lbTitleString = "%s (%s)" % (tc.description, tc.units) res.lbTitleFontHeightF = 0.015 res.lbLabelFontHeightF = 0.015 res.tiMainString = filename res.tiMainFont = "helvetica-bold" res.tiMainFontHeightF = 0.02 plot = Ngl.contour_map(wks, tc[0, :, :], res) Ngl.end()
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()
def draw_gh_500hPa(sel_year, sel_month): print("darwing 500hPa gh plot for " + str(sel_month).zfill(2) + " " + str(sel_year)) files_cli = sorted( glob.glob( os.path.join( '/home/alley/work/Dong/mongo/seasonal_analysis/data/data/download_from_mongo/cli/', 'gh_500_*.grb'))) f_cli = xr.open_mfdataset(files_cli, concat_dim="time", combine="nested", engine="cfgrib", parallel=True) h = f_cli["z"] h = h.mean(dim="time") h_cli = h / 98 lat = f_cli["latitude"].values lon = f_cli["longitude"].values file_cur = "/home/alley/work/Dong/mongo/seasonal_analysis/data/data/download_from_mongo/cur/gh_500_" + str( sel_year) + str(sel_month).zfill(2) + ".grb" # print(file_cur) f_cur = xr.open_mfdataset(file_cur, engine="cfgrib", parallel=True) h_cur = f_cur["z"] / 98 h_ano = h_cur - h_cli leftString = "500hPa Height & Anomaly for " + str(sel_month) + str( sel_year) rightString = "dagpm" wks_type = 'png' wks = Ngl.open_wks( wks_type, '/home/alley/work/Dong/mongo/seasonal_analysis/images/gh_500hPa_' + str(sel_year) + str(sel_month).zfill(2) + '.png') res = Ngl.Resources() res.nglFrame = False res.nglDraw = False res.mpLimitMode = "LatLon" res.mpMinLonF = 60 res.mpMaxLonF = 180 res.mpMinLatF = 0 res.mpMaxLatF = 60 plot_map = Ngl.map(wks, res) fres = Ngl.Resources() fres.nglFrame = False fres.nglDraw = False fres.cnFillOn = True fres.sfXArray = lon fres.sfYArray = lat fres.lbOrientation = "Horizontal" # horizontal labelbar fres.cnLinesOn = False fres.cnLineLabelsOn = False fres.cnLevelSelectionMode = "ExplicitLevels" fres.cnFillPalette = "BlueDarkRed18" fres.cnLevels = np.arange(-5, 6, 1) plot_cn = Ngl.contour(wks, h_ano, fres) cnres = Ngl.Resources() cnres.nglDraw = False cnres.nglFrame = False cnres.cnFillOn = False cnres.cnLinesOn = True cnres.cnLineLabelsOn = True cnres.cnInfoLabelOn = False cnres.sfXArray = lon cnres.sfYArray = lat cnres.cnLevelSelectionMode = "ExplicitLevels" cnres.cnLevels = np.arange(500, 600, 4) cnres.cnLineColor = "black" cnres.cnLineThicknessF = 5 plot2 = Ngl.contour(wks, h_cur, cnres) Ngl.overlay(plot_map, plot_cn) Ngl.overlay(plot_map, plot2) # txres = Ngl.Resources() txres.txFontHeightF = 0.024 # Ngl.text_ndc(wks, leftString, 0.3, 0.83, txres) Ngl.text_ndc(wks, rightString, 0.85, 0.83, txres) # Ngl.maximize_plot(wks, plot_map) Ngl.draw(plot_map) Ngl.frame(wks) Ngl.end() print("Finish darwing 500hPa gh plot plot for " + str(sel_month).zfill(2) + " " + str(sel_year))
def main(): import numpy import Ngl options = parse_input() u_array2, v_array2, s_array2, x_min, x_max, y_min, y_max = read_data(options) wks_type = 'ps' wks = Ngl.open_wks(wks_type, options.data) color_res = Ngl.Resources() gs_res = Ngl.Resources() text_res = Ngl.Resources() rgb_min = [] for s in options.rgb_min.split(): rgb_min.append(float(s)) rgb_max = [] for s in options.rgb_max.split(): rgb_max.append(float(s)) l = [] l.append([1.00, 1.00, 1.00]) l.append([0.00, 0.00, 0.00]) f_l = [] n = 100 for f in range(n): f_l.append(float((f + 1) * (1.0 / n))) for f in f_l: r = rgb_min[0] + f * (rgb_max[0] - rgb_min[0]) g = rgb_min[1] + f * (rgb_max[1] - rgb_min[1]) b = rgb_min[2] + f * (rgb_max[2] - rgb_min[2]) l.append([r, g, b]) rgb_map = numpy.array(l, 'f') color_res.wkColorMap = rgb_map Ngl.set_values(wks, color_res) vector_res = get_vector_res(options, x_min, x_max, y_min, y_max) plot = Ngl.vector_scalar(wks, u_array2, v_array2, s_array2, vector_res) color_res.wkColorMap = "default" Ngl.set_values(wks, color_res) line_thickness = 2.0 gs_res.gsMarkerSizeF = 10.0 gs_res.gsMarkerThicknessF = 2.0 gs_res.gsLineDashPattern = 2 gs_res.gsLineThicknessF = line_thickness text_res.txFont = 21 text_res.txFontHeightF = 0.015 text_res.txFontColor = options.text_color for atom in read_molecule(options): gs_res.gsMarkerIndex = 16 gs_res.gsMarkerColor = "White" Ngl.polymarker(wks, plot, [atom[2]], [atom[1]], gs_res) gs_res.gsMarkerIndex = 4 gs_res.gsMarkerColor = options.text_color Ngl.polymarker(wks, plot, [atom[2]], [atom[1]], gs_res) Ngl.text(wks, plot, atom[0], [atom[2] + 1.0], [atom[1]], text_res) Ngl.frame(wks) del plot Ngl.end()
def main(): import numpy import Ngl options = parse_input() u_array2, v_array2, s_array2, x_min, x_max, y_min, y_max = read_data( options) wks_type = 'ps' wks = Ngl.open_wks(wks_type, options.data) color_res = Ngl.Resources() gs_res = Ngl.Resources() text_res = Ngl.Resources() rgb_min = [] for s in options.rgb_min.split(): rgb_min.append(float(s)) rgb_max = [] for s in options.rgb_max.split(): rgb_max.append(float(s)) l = [] l.append([1.00, 1.00, 1.00]) l.append([0.00, 0.00, 0.00]) f_l = [] n = 100 for f in range(n): f_l.append(float((f + 1) * (1.0 / n))) for f in f_l: r = rgb_min[0] + f * (rgb_max[0] - rgb_min[0]) g = rgb_min[1] + f * (rgb_max[1] - rgb_min[1]) b = rgb_min[2] + f * (rgb_max[2] - rgb_min[2]) l.append([r, g, b]) rgb_map = numpy.array(l, 'f') color_res.wkColorMap = rgb_map Ngl.set_values(wks, color_res) vector_res = get_vector_res(options, x_min, x_max, y_min, y_max) plot = Ngl.vector_scalar(wks, u_array2, v_array2, s_array2, vector_res) color_res.wkColorMap = "default" Ngl.set_values(wks, color_res) line_thickness = 2.0 gs_res.gsMarkerSizeF = 10.0 gs_res.gsMarkerThicknessF = 2.0 gs_res.gsLineDashPattern = 2 gs_res.gsLineThicknessF = line_thickness text_res.txFont = 21 text_res.txFontHeightF = 0.015 text_res.txFontColor = options.text_color for atom in read_molecule(options): gs_res.gsMarkerIndex = 16 gs_res.gsMarkerColor = "White" Ngl.polymarker(wks, plot, [atom[2]], [atom[1]], gs_res) gs_res.gsMarkerIndex = 4 gs_res.gsMarkerColor = options.text_color Ngl.polymarker(wks, plot, [atom[2]], [atom[1]], gs_res) Ngl.text(wks, plot, atom[0], [atom[2] + 1.0], [atom[1]], text_res) Ngl.frame(wks) del plot Ngl.end()
def cwrf_contour(fname, vname, days=None): if not pth.exists(fname): print_("You do not have the necessary '%s' file to run this script." % fname) sys.exit(1) dset = Nio.open_file(fname + ".nc") lat = dset.variables["XLAT"][0, :, :] lon = dset.variables["XLONG"][0, :, :] region, subm = re.split(os.sep, pth.dirname(fname))[-2:] cur_date = get_date(dset.START_DATE) dates = get_list_times(dset) if days is None: days = len(dates) / 10 * 10 elif days in ('30', '60', '90'): days = int(days) else: print_("%s invalid, between 30, 60 and 90" % days) sys.exit(1) if vname == "RAINC": vdat, base = get_rain_data(dset, cur_date.month - 1, days) blon, blat = get_coordinates("rainc") title = "Precipitacion Total" unit = "mm" levels = (30, 1200, 150) blevels = [-300., -180., -90., -30., 30., 90., 180., 300.] palete = 'WhBlGrYeRe' bpalete = 'precip_diff_12lev' elif vname == "T2": vdat, base = get_temp_data(dset, cur_date.month - 1, days) blon, blat = get_coordinates("t2ave") title = "Temperatura Media a 2 m" unit = "~S~o~N~C" levels = (-5, 35, 5) blevels = [-3, -2, -1, -0.3, 0.3, 1, 2, 3] palete = 'MPL_coolwarm' bpalete = 'temp_diff_18lev' else: print_("%s not supported" % vname) sys.exit(1) rbase = regrid((blon, blat), (lon, lat), base) wks_type = "png" wks_res = Ngl.Resources() wks_res.wkHeight = 600 wks_res.wkWidth = 650 wks = Ngl.open_wks( wks_type, DEFAULT_FILE_FORMAT % (cur_date.year, cur_date.month, days, VARIABLES[vname]), wks_res) panelres = Ngl.Resources() panelres.nglMaximize = True panelres.nglPanelBottom = 0.03 res = Ngl.Resources() res.nglDraw = False res.nglFrame = False # Mapa set_map(res, (np.min(lon), np.min(lat)), (np.max(lon), np.max(lat))) #set_map(res, (REGIONS["SA"][0][0], REGIONS["SA"][0][1]), # (REGIONS["SA"][1][0], REGIONS["SA"][1][1])) set_labelbar(res, unit) res.tiMainFontHeightF = 0.025 res.tiMainString = "Totales" res.sfXArray = lon res.sfYArray = lat set_contour(res, levels, cnFillPalette=palete) plot1 = Ngl.contour_map(wks, vdat, res) #res.tmYLOn = False #res.tmYROn = True #res.tmYRLabelsOn = True res.tiMainString = "Anomalias" #res.sfXArray = blon #res.sfYArray = blat set_contour(res, blevels, cnFillPalette=bpalete) plot2 = Ngl.contour_map(wks, vdat - rbase, res) txres = Ngl.Resources() txres.txFontHeightF = 0.03 Ngl.text_ndc(wks, title, 0.5, 0.97, txres) txres.txFontHeightF = 0.02 last = days - 1 if days > 89: last = days + 1 Ngl.text_ndc( wks, "Promedio %d dias desde %s hasta %s" % (days, dates[0].strftime("%d%b%Y"), dates[last].strftime("%d%b%Y")), 0.5, 0.91, txres) txres.txFontHeightF = 0.015 y1 = 0.120 y2 = 0.090 if region == "PARAGUAY": y1 = 0.190 y2 = 0.160 Ngl.text_ndc(wks, "CWRF-CAM-%s OLE~S~2~N~ (clima.pol.una.py) " % subm, 0.8, y1, txres) txres.txFontHeightF = 0.013 Ngl.text_ndc( wks, "Proyecto 14-INV-054 / GUYRA Paraguay / Facultad " "Politecnica", 0.75, y2, txres) Ngl.panel(wks, [plot1, plot2], [1, 2], panelres) Ngl.end()
def main(): print('') #-- open file and read variable and time home = os.environ.get('HOME') fname = os.path.join(home,'NCL/PyNGL/User_Guide_examples/rectilinear_grid_2D.nc') ds = xr.open_dataset(fname) var = ds.tsurf time = ds.time #-- xarray deletes the units and long_name attributes, so we have to get #-- them on another way print('--> time attributes:', ds.time.attrs) print('') units = var.attrs['units'] lname = var.attrs['long_name'] #-- print some information about the variable and the time coordinate print('--> var: ',var) print('') #-- convert the time values to date strings using a user defined function date_labels = conv_time_netcdf(ds) print('--> date_labels ',type(date_labels)) print('') #-- for explicit x-axis generate simple time array time = np.arange(0,len(ds.time),1) #-- compute the area mean without weighting areamean = np.average(var,axis=(1,2)) print('--> areamean: ',areamean) print('') #-- open a workstation wks = Ngl.open_wks('png','plot_xy_plot_timeseries') #-- graphics output #-- set resources/attributes res = Ngl.Resources() #-- generate an res object for plot res.tiMainString = 'DKRZ Example: xy-plot timeseries' #-- draw a title res.tiMainOffsetYF = 0.02 res.nglMaximize = False res.nglPointTickmarksOutward = True #-- point tickmarks outward res.nglDraw = False res.nglFrame = False res.vpWidthF = 0.7 res.vpHeightF = 0.7 res.vpXF = 0.2 res.vpYF = 0.85 res.tmXBMode = 'Explicit' #-- use explicit values res.tmXBValues = time res.tmXBLabels = list(date_labels) res.tmXBLabelFontHeightF = 0.006 res.tmXBLabelJust = 'CenterRight' res.tmXBLabelDeltaF = 0.2 res.tmXBLabelAngleF = 40.0 res.tmXBLabelStride = 4 #-- draw the plot plot = Ngl.xy(wks,time,areamean,res) #-- add additional strings to plot (like NCL's gsnLeftString and gsnRightString) ngl_Strings(wks, plot, left=lname, right=units, ytitle=lname) #-- done Ngl.draw(plot) Ngl.frame(wks) Ngl.end()
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()
def draw_sst(sel_year, sel_month): st = time.time() np.seterr(divide='ignore', invalid='ignore') print("darwing sst plot for " + str(sel_month).zfill(2) + " " + str(sel_year)) files_cli = sorted( glob.glob( os.path.join( '/home/alley/work/Dong/mongo/seasonal_analysis/data/data/download_from_mongo/cli', 'sst_*.grb'))) f_cli = xr.open_mfdataset(files_cli, concat_dim="time", combine="nested", engine="cfgrib", parallel=True) h_cli = f_cli["sst"] h_cli_ori = h_cli.mean(dim="time").values file_cur = "/home/alley/new_disk/data/sst_" + str(sel_year) + str( sel_month).zfill(2) + ".grb" f_cur = xr.open_mfdataset(file_cur, engine="cfgrib", parallel=True) h_cur_ori = f_cur["sst"] h_cur = (h_cur_ori.values - 273.15) h_cur = np.nan_to_num(h_cur, nan=-999) lat = f_cur["latitude"].values lon = f_cur["longitude"].values h_ano = h_cur_ori - h_cli_ori h_ano = np.nan_to_num(h_ano.values, nan=-999) # print(h_ano) et1 = time.time() # print(et1 - st) # leftString = "SST in " + str(sel_month) + str(sel_year) # rightString = "~S~o~N~C" wks_type = 'png' wks = Ngl.open_wks( wks_type, '/home/alley/work/Dong/mongo/seasonal_analysis/images/sst_' + str(sel_year) + str(sel_month).zfill(2) + '.png') res = Ngl.Resources() res.nglFrame = False res.nglDraw = False res.mpLimitMode = "LatLon" # res.mpFillOn = True #-- turn on map fill # res.mpLandFillColor = "gray" #-- change land color to gray # res.mpMinLonF= 50 # res.mpMaxLonF = 280 res.mpMinLatF = -45 res.mpMaxLatF = 45 res.cnFillOn = True res.mpCenterLonF = 120 res.sfMissingValueV = -999 res.sfXArray = lon res.sfYArray = lat res.lbOrientation = "Horizontal" # horizontal labelbar res.cnLinesOn = False res.tiMainFontHeightF = 0.015 res.cnLineLabelsOn = False res.cnFillDrawOrder = "Predraw" res.cnFillPalette = "BlAqGrYeOrRe" res.pmLabelBarDisplayMode = "Always" #-- turn on a labelbar res.tiMainString = "SST in " + str(sel_month).zfill(2) + " " + str( sel_year) + " (degC)" res.cnLevelSelectionMode = "ExplicitLevels" res.cnLevels = np.arange(20, 35, 1) plot_cur = Ngl.contour_map(wks, h_cur, res) res.cnLevelSelectionMode = "ExplicitLevels" res.tiMainString = "SST anomaly in " + str(sel_month).zfill(2) + " " + str( sel_year) + " (degC)" res.cnFillPalette = "GMT_polar" res.cnLevels = np.arange(-3, 4, 1) res.pmLabelBarHeightF = 0.3 plot_ano = Ngl.contour_map(wks, h_ano, res) Ngl.panel(wks, [plot_cur, plot_ano], [2, 1], False) Ngl.end() et2 = time.time() # print(et2 - et1) print("Finish darwing sst plot for " + str(sel_month).zfill(2) + " " + str(sel_year))