def plot(filename, outputname): # set up parameters f = Nio.open_file(filename) q = f.variables['q'][:, 0, :] qY = f.variables['qY'][:, 0, :] ae = 6.371229e6 r2d = 57.2957795 lat = f.variables['lat'][:, :] * r2d lon = f.variables['lon'][:, :] * r2d vertx = f.variables['vertx'][:, :, :] * r2d verty = f.variables['verty'][:, :, :] * r2d ncols = f.variables['nCols'][:] # Open a workstation. wks_type = "pdf" wks = Ngl.open_wks(wks_type, outputname) # Create contour and map resource lists. for it in range(1, 2): cnres = Ngl.Resources() cnres.nglFrame = False cnres.nglDraw = False cnres.mpGridAndLimbOn = False cnres.mpOutlineOn = False cnres.mpPerimOn = False # ; turn off box around plot cnres.nglMaximize = True cnres.mpProjection = "Orthographic" # Change the map projection. x_c, y_c = qmoving(it * 24. * 3600., 12. * 24. * 3600., 0. * np.pi, ae) cnres.mpCenterLonF = x_c * r2d cnres.mpCenterLatF = y_c * r2d cnres.mpOutlineOn = False cnres.sfXArray = lon[it, 0:ncols[it]] cnres.sfYArray = lat[it, 0:ncols[it]] cnres.cnLinesOn = True cnres.cnFillOn = False cnres.cnLineLabelsOn = False cnres.cnInfoLabelOn = False cnres.cnLevelSelectionMode = "ExplicitLevels" # Set explicit contour levels cnres.cnLevels = np.arange(0.1, 1., 0.1) # 0,5,10,...,70 cnres.cnLineThicknessF = 3. cnres.pmTickMarkDisplayMode = "Never" contour1 = Ngl.contour_map(wks, q[it, 0:ncols[it]], cnres) cnres.cnLineColor = "red" contour2 = Ngl.contour_map(wks, qY[it, 0:ncols[it]], cnres) Ngl.draw(contour1) Ngl.draw(contour2) # Ngl.draw(vc) Ngl.frame(wks) Ngl.end()
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_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 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 print_cape_for_timestamp(wrf_data, timestamp, filepath): slp = pressure_lib.get_sea_level_pressure(wrf_data) cinfo = getvar(wrf_data, "cape_2d", missing=0.0) cape = cinfo[0, :, :].fillna(0) lat, lon = latlon_coords(slp) lat_normal = to_np(lat) lon_normal = to_np(lon) # rain sum cape_res = get_pyngl(cinfo) cape_res.nglDraw = False # don't draw plot cape_res.nglFrame = False # don't advance frame cape_res.cnFillOn = True # turn on contour fill cape_res.cnLinesOn = False # turn off contour lines cape_res.cnLineLabelsOn = False # turn off line labels cape_res.cnFillMode = "RasterFill" # These two resources cape_res.cnLevelSelectionMode = "ExplicitLevels" cape_res.cnFillColors = numpy.array([ [255,255,255], [ 0,255, 0], [ 0,128, 0], \ [240,230,140], [255,255, 0], [255,140, 0], \ [255, 0, 0], [139, 0, 0], [186, 85,211],\ [153, 50,204], [139, 0,139], ],'f') / 255. cape_res.cnLevels = numpy.array( [.1, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500]) cape_res = geography_lib.initialize_geography(cape_res, "gray50") cape_res.lbTitleString = "Convective available potential energy [CAPE] in (J/kg)" cape_res.lbOrientation = "horizontal" cape_res.lbTitleFontHeightF = 0.015 cape_res.lbLabelFontHeightF = 0.015 cape_res.tiMainString = "Thunderstorm probability (%s)" % timestamp.strftime( "%b %d %Y %HUTC") cape_res.trGridType = "TriangularMesh" # can speed up plotting. cape_res.tfDoNDCOverlay = True # required for native projection # pressure p_res = pressure_lib.get_pressure_resource(lat_normal, lon_normal) wk_res = Ngl.Resources() wk_res.wkWidth = 2500 wk_res.wkHeight = 2500 output_path = "%scape_%s" % (filepath, timestamp.strftime("%Y_%m_%d_%H")) wks_comp = Ngl.open_wks("png", output_path, wk_res) # creating plots for the measurands capeplot = Ngl.contour_map(wks_comp, cape, cape_res) pplot = Ngl.contour(wks_comp, slp, p_res) Ngl.overlay(capeplot, pplot) Ngl.maximize_plot(wks_comp, capeplot) Ngl.draw(capeplot) Ngl.frame(wks_comp) Ngl.delete_wks(wks_comp) # delete currently used workstation
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 plot(filename, outputend): # set up parameters f = Nio.open_file(filename) q = f.variables['q'][:, 0, :] r2d = 57.2957795 lat = f.variables['lat'][:, :]*r2d lon = f.variables['lon'][:, :]*r2d vertx = f.variables['vertx'][:, :, :]*r2d verty = f.variables['verty'][:, :, :]*r2d ncols = f.variables['nCols'][:] ae = 6.371229e6 # Open a workstation. wks_type = "pdf" rlist = Ngl.Resources() rlist.wkColorMap = "WhBlReWh" # Create contour and map resource lists. for it in range(13): wks = Ngl.open_wks(wks_type,"Moving_"+str(it)+outputend, rlist) cnres = Ngl.Resources() cnres.nglFrame = False # cnres.nglDraw = False cnres.mpGridAndLimbOn = False cnres.mpOutlineOn = False cnres.mpPerimOn = False# ; turn off box around plot cnres.nglMaximize = True cnres.mpProjection = "Orthographic" # Change the map projection. # x_c, y_c = 0, 90.#qmoving(it*24.*3600., 12.*24.*3600., 0.25*np.pi, ae) cnres.mpCenterLonF = x_c*r2d # Rotate the projection. cnres.mpCenterLatF = y_c*r2d # Rotate the projection. cnres.mpOutlineOn = False cnres.sfXArray = lon[it, 0:ncols[it]] cnres.sfYArray = lat[it, 0:ncols[it]] cnres.cnLinesOn = False cnres.cnFillOn = True cnres.cnLineLabelsOn = False cnres.cnInfoLabelOn = False cnres.lbLabelBarOn = True cnres.cnLevelSelectionMode = "ManualLevels" cnres.cnMinLevelValF = 0.4 cnres.cnMaxLevelValF = 1.6 cnres.cnLevelSpacingF = 0.05 cnres.pmTickMarkDisplayMode = "Never" contour1 = Ngl.contour_map(wks,q[it, 0:ncols[it]],cnres) gsres = Ngl.Resources() gsres.gsLineColor = "Gray25" gsres.gsLineThicknessF = 3.0 # print(vertx[0, :, 0],verty[0, :, 0]) for nc in range(ncols[it]): Ngl.polyline(wks,contour1,vertx[it, :, nc],verty[it, :, nc],gsres) # Ngl.draw(contour1) Ngl.frame(wks) Ngl.destroy(wks) 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 range(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_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 plot(filename, outputname, centerlon, centerlat): # set up parameters f = Nio.open_file(filename) q = f.variables['q'][:, 0, :] r2d = 57.2957795 lat = f.variables['lat'][:, :] * r2d lon = f.variables['lon'][:, :] * r2d vertx = f.variables['vertx'][:, :, :] * r2d verty = f.variables['verty'][:, :, :] * r2d ncols = f.variables['nCols'][:] # Open a workstation. wks_type = "pdf" wks = Ngl.open_wks(wks_type, outputname) # Create contour and map resource lists. for it in range(13): cnres = Ngl.Resources() cnres.nglFrame = False cnres.nglDraw = False cnres.mpGridAndLimbOn = False cnres.mpOutlineOn = False cnres.mpPerimOn = False # ; turn off box around plot cnres.nglMaximize = True cnres.mpProjection = "Orthographic" # Change the map projection. cnres.mpCenterLonF = centerlon cnres.mpCenterLatF = centerlat cnres.mpOutlineOn = False cnres.sfXArray = lon[it, 0:ncols[it]] cnres.sfYArray = lat[it, 0:ncols[it]] cnres.cnLinesOn = True cnres.cnFillOn = False cnres.cnLineLabelsOn = False cnres.cnInfoLabelOn = False cnres.cnLevelSelectionMode = "ExplicitLevels" # Set explicit contour levels cnres.cnLevels = np.arange(0.1, 1., 0.1) # 0,5,10,...,70 cnres.cnLineThicknessF = 3. cnres.cnLineColor = "red" cnres.pmTickMarkDisplayMode = "Never" contour1 = Ngl.contour_map(wks, q[it, 0:ncols[it]], cnres) gsres = Ngl.Resources() gsres.gsLineColor = "Gray25" gsres.gsLineThicknessF = 2.0 for nc in range(ncols[it]): Ngl.polyline(wks, contour1, vertx[it, :, nc], verty[it, :, nc], gsres) Ngl.draw(contour1) Ngl.frame(wks) Ngl.end()
def draw_contour(colorBarName, data, endLat, endLon, imgOutputPaths, lat, lon, startLat, startLon, wks): res = Ngl.Resources() res.nglFrame = False res.nglDraw = False resource_map_setting(endLat, endLon, lon, res, startLat, startLon) resource_Axises_setting(imgOutputPaths, res) resource_cn_setting(colorBarName, res) # 其他相关配置 resource_other_setting(lat, lon, res) # 绘等高线图 plot = Ngl.contour_map(wks, data, res) return 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()
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 get_3h_rainsum(previous_data, current_data, timestamp, filepath): slp = pressure_lib.get_sea_level_pressure(current_data) previous_sum, rain_con = get_cumulated_rain_sum(previous_data) current_sum, rain_con = get_cumulated_rain_sum(current_data) rain_sum = current_sum - previous_sum lat, lon = latlon_coords(rain_con) lat_normal = to_np(lat) lon_normal = to_np(lon) # rain sum rr_res = initialize_rain_resource(rain_con) rr_res.lbTitleString = "3h rainsum in (mm)" rr_res.lbOrientation = "horizontal" rr_res.lbTitleFontHeightF = 0.015 rr_res.lbLabelFontHeightF = 0.015 rr_res.tiMainString = "3h rainsum (%s)" % timestamp.strftime( "%b %d %Y %HUTC") rr_res.trGridType = "TriangularMesh" # can speed up plotting. rr_res.tfDoNDCOverlay = True # required for native projection # pressure p_res = pressure_lib.get_pressure_resource(lat_normal, lon_normal) wk_res = Ngl.Resources() wk_res.wkWidth = 2500 wk_res.wkHeight = 2500 output_path = "%srain_3h_%s" % (filepath, timestamp.strftime("%Y_%m_%d_%H")) wks_comp = Ngl.open_wks("png", output_path, wk_res) # creating plots for the measurands rrplot = Ngl.contour_map(wks_comp, rain_sum, rr_res) pplot = Ngl.contour(wks_comp, slp, p_res) Ngl.overlay(rrplot, pplot) Ngl.maximize_plot(wks_comp, rrplot) Ngl.draw(rrplot) Ngl.frame(wks_comp) Ngl.delete_wks(wks_comp) # delete currently used workstation
def contour_map(self): params_dict = self.params_dict color_levels = self.color_levels cn_fill_colors = np.arange(0, len(color_levels), 1) # 1.绘制南海底板 south_sea_baseboard = params_dict.pop('south_sea_baseboard') south_sea_baseboard['cnLevels'] = color_levels south_sea_baseboard['cnFillColors'] = cn_fill_colors resource = create_or_update_resource(params_dict=south_sea_baseboard) south_sea_plot = Ngl.contour_map(self.workstation, self.input_data, resource) # 2.绘制南海相关地理线 south_sea_geoline = params_dict.pop('south_sea_geoline') # 多级 for key, params_dict in south_sea_geoline.items(): file_name = params_dict.pop('file_name') type = params_dict.pop('type') shape = Nio.open_file(shape_file_path + file_name, "r") lon = np.ravel(shape.variables["x"][:]) lat = np.ravel(shape.variables["y"][:]) params_dict['gsSegments'] = shape.variables["segments"][:, 0] resource = create_or_update_resource(params_dict=params_dict) # 2.绘制曲线图 if type == 'polyline': Ngl.add_polyline(self.workstation, south_sea_plot, lon, lat, resource) else: pass #polygon/point 处理待定 # 3. 南海加比例尺 south_sea_scale = params_dict.pop('south_sea_scale') scala_figure = south_sea_scale.pop('scala_figure') x, y = south_sea_scale.pop('location').split('x') resource = create_or_update_resource(params_dict=south_sea_scale) Ngl.add_text(self.workstation, south_sea_plot, scala_figure, x, y, resource) # 4.南海放在中国的位置 south_sea_location = params_dict.pop('south_sea_location') resource = create_or_update_resource(params_dict=south_sea_location) Ngl.add_annotation(self.plot, south_sea_plot, resource)
def contour_map(self): resource_config = {} # 是否有色板配置文件 if self.color_levels: cn_params_dict = { "cnLevels": self.color_levels , "cnFillColors":np.arange(0,len(self.color_levels),1).tolist() } resource_config.update(cn_params_dict) # 是否有用户自定义配置 if self.params_dict: resource_config.update(self.params_dict) # 构造resource对象 self.resource = create_or_update_resource(params_dict=resource_config) # 绘图 map_plot = Ngl.contour_map(self.workstation, self.input_data, self.resource) return map_plot
ys = Ngl.get_float(contour.sffield,"sfYCActualStartF") ye = Ngl.get_float(contour.sffield,"sfYCActualEndF") resources.nglDraw = True # Now we want to draw the plot resources.nglFrame = True # and advance the frame. resources.mpGridAndLimbOn = False resources.mpProjection = "Orthographic" resources.mpDataBaseVersion = "MediumRes" resources.mpLimitMode = "LatLon" resources.mpMinLonF = xs resources.mpMaxLonF = xe resources.mpMinLatF = ys resources.mpMaxLatF = ye resources.mpCenterLatF = 40 resources.mpCenterLonF = -100 map = Ngl.contour_map(wks,ke,resources) resources.cnRasterSmoothingOn = True resources.tiMainString = "Smooth raster contouring" map = Ngl.contour_map(wks,ke,resources) resources.cnFillMode = "AreaFill" resources.tiMainString = "Area fill contouring" map = Ngl.contour_map(wks,ke,resources) Ngl.end()
res.cnMinLevelValF = -0.1#0.45#-0.1 #-- contour min. value res.cnMaxLevelValF = 2.0#1.5#2.0 #-- contour max. value res.cnLevelSpacingF = 0.1#0.05#0.1 #-- contour interval colors00 = Ngl.read_colormap_file("MPL_RdBu") ncolors00= colors00.shape[0] colors0 = colors00[np.linspace(2,ncolors00-1,int((res.cnMaxLevelValF-res.cnMinLevelValF)/res.cnLevelSpacingF),dtype=int),:] grey_color = np.expand_dims(np.array([0.85, 0.85, 0.85, 1]), axis=0) colors = np.append(grey_color,colors0[::-1,:],axis=0) res.cnFillPalette = colors#'BlWhRe' #'MPL_YlOrRd' #-- choose color map plot = [] title = 'CESM all forcing vs '+sf+' foricng~C~FWI >= p'+str(pxx)+' risk ratio' for pp in range(2,nperiods,1): print('period '+str(pp+1)) res.tiMainString = str(pyear0[pp])+'-'+str(pyear1[pp]) riskratio_cyc, lon_cyc = Ngl.add_cyclic(riskratio_ens_agree_masked[pp,:,:], lon) res.sfXArray = lon_cyc p = Ngl.contour_map(wks,riskratio_cyc,res) if pp==(nperiods-1): for rr in range(0,n_reg,1): poly_y = [df_reg['reg_N'][rr],df_reg['reg_S'][rr],df_reg['reg_S'][rr],df_reg['reg_N'][rr],df_reg['reg_N'][rr]] poly_x = [df_reg['reg_E'][rr],df_reg['reg_E'][rr],df_reg['reg_W'][rr],df_reg['reg_W'][rr],df_reg['reg_E'][rr]] poly_reg = Ngl.add_polygon(wks,p,poly_x,poly_y,gsres) plot.append(p) Ngl.panel(wks,plot,[4,1],pres) Ngl.text_ndc(wks,title,0.5,0.92,txres) Ngl.frame(wks) Ngl.delete_wks(wks)
res.sfXArray = lon res.sfYArray = lat # # Set some contour resources # res.cnFillOn = True res.cnLinesOn = False res.cnLineLabelsOn = False res.cnLevelSelectionMode = "ManualLevels" res.cnMinLevelValF = 195. res.cnMaxLevelValF = 328. res.cnLevelSpacingF = 5. # # Set title resources. # res.tiMainString = "January Global Surface Temperature (K)" # # Set labelbar resources. # res.lbOrientation = "Horizontal" nt = 30 # Pick a time for a single plot. res.lbTitleString = "Day " + str(nt+1) map = Ngl.contour_map(wks,T[nt,:,:],res) Ngl.end()
resources.nglSpreadColorStart = -1 resources.nglSpreadColorEnd = 2 #resources.vpXF = 0.05 # Change Y location of plot. #resources.vpYF = 0.95 # Change Y location of plot. #resources.vpHeightF = 0.2 #resources.vpWidthF = 0.2 #resources.vpXF = 0.1 #resources.vpYF = 0.9 #resources.nglMaximize = True #resources.tiMainString = "%% of normal %s - %s" % (t0.strftime("%b %d %Y"), ts.strftime("%b %d %Y"), ) resources.tiMainString = "Departure from normal %s - %s" % (t0.strftime("%b %d %Y"), ts.strftime("%b %d %Y"), ) zdiff = numpy.transpose(zdiff) contour = Ngl.contour_map(xdiff,zdiff,resources) del contour resources.cnLevelSelectionMode = 'AutomaticLevels' resources.cnLevelSpacingF = 0.5 resources.tiMainString = "Normal Precipitation %s - %s" % (t0.strftime("%b %d"), ts.strftime("%b %d"), ) zavg = numpy.transpose(zavg) contour = Ngl.contour_map(xavg,zavg,resources) del contour resources.tiMainString = "Observed Precipitation %s - %s" % (t0.strftime("%b %d %Y"), ts.strftime("%b %d %Y"), ) resources.cnLevelSpacingF = 5. zobs = numpy.transpose(zobs) contour = Ngl.contour_map(xobs,zobs,resources) del contour
def simple_contour(lons, lats, vals, cfg): """ Generate a simple contour plot, okay """ tmpfp = tempfile.mktemp() rlist = Ngl.Resources() if cfg.has_key("wkColorMap"): rlist.wkColorMap = cfg['wkColorMap'] #rlist.wkOrientation = "landscape" # Create Workstation wks = Ngl.open_wks( "ps",tmpfp,rlist) # Create Analysis if cfg.has_key("_conus"): analysis, res = grid_conus(lons, lats, vals) elif cfg.get("_northeast", False): analysis, res = grid_northeast(lons, lats, vals) elif cfg.get("_midwest", False): analysis, res = grid_midwest(lons, lats, vals) else: analysis, res = grid_iowa(lons, lats, vals) analysis = numpy.transpose(analysis) for key in cfg.keys(): if key == 'wkColorMap' or key[0] == "_": continue setattr(res, key, cfg[key]) if cfg.has_key("_MaskZero"): mask = numpy.where( analysis <= 0.02, True, False) analysis = numpy.ma.array(analysis, mask=mask) # Generate Contour if numpy.min(analysis) == numpy.max(analysis): if cfg.has_key("_conus"): res = conus() elif cfg.has_key("_midwest"): res = midwest() else: res = iowa() contour = Ngl.map(wks, res) else: contour = Ngl.contour_map(wks,analysis,res) if cfg.has_key("_showvalues") and cfg['_showvalues']: txres = Ngl.Resources() txres.txFontHeightF = 0.012 for i in range(len(lons)): if cfg.has_key("_valuemask") and cfg['_valuemask'][i] is False: continue Ngl.add_text(wks, contour, cfg["_format"] % vals[i], lons[i], lats[i],txres) Ngl.draw( contour ) watermark(wks) manual_title(wks, cfg) vpbox(wks) Ngl.frame(wks) del wks return tmpfp
def plot_contourmap(path, date, fcst_hours, variable, stat_processing_methods): ##### generate subpath and filename ##### subpath = 'run_{}{:02}{:02}{:02}/{}/'.format(\ date['year'], date['month'], date['day'], date['hour'], variable) filename1 = 'icon-eu-eps_europe_icosahedral_single-level_{}{:02}{:02}{:02}_{:03}_{}.grib2'.format(\ date['year'], date['month'], date['day'], date['hour'], fcst_hours[0], variable) filename2 = 'icon-eu-eps_europe_icosahedral_single-level_{}{:02}{:02}{:02}_{:03}_{}.grib2'.format(\ date['year'], date['month'], date['day'], date['hour'], fcst_hours[1], variable) ######################################################################## ### read data ### ######################################################################## ##### create empty numpy arrays ##### ##### 2 fcst_hours, 40 members, 75948 eu gridpoints ##### data_raw = np.empty((2, 40, 75948)) data_members = np.empty((40, 75948)) ##### every time in loop open next grib msg from grib file ##### ##### grib messages in dwd file are sorted by increasing member number ##### with open(path['base'] + path['data'] + subpath + filename1, 'rb') as file: for member in range(1, 41): print('read data from member {}'.format(member)) grib_msg_id = eccodes.codes_grib_new_from_file(file) data_raw[0, member - 1, :] = eccodes.codes_get_array( grib_msg_id, 'values') eccodes.codes_release(grib_msg_id) with open(path['base'] + path['data'] + subpath + filename2, 'rb') as file: for member in range(1, 41): print('read data from member {}'.format(member)) grib_msg_id = eccodes.codes_grib_new_from_file(file) data_raw[1, member - 1, :] = eccodes.codes_get_array( grib_msg_id, 'values') eccodes.codes_release(grib_msg_id) ##### take the difference of the two accumulated total precipitation arrays ##### data_members = data_raw[1, :, :] - data_raw[0, :, :] del data_raw ##### open icon-eps grid file ##### icongrid_file = nc.Dataset( path['base'] + path['grid'] + 'icon_grid_0028_R02B07_N02.nc', 'r') vlat = icongrid_file.variables['clat_vertices'][:].data * 180. / np.pi vlon = icongrid_file.variables['clon_vertices'][:].data * 180. / np.pi clat = icongrid_file.variables['clat'][:].data * 180. / np.pi clon = icongrid_file.variables['clon'][:].data * 180. / np.pi icongrid_file.close() for stat_processing in stat_processing_methods: ######################################################################## ### statistically process data ### ######################################################################## if stat_processing == 'mean': data_processed = data_members.mean(axis=0) elif stat_processing == 'max': data_processed = data_members.max(axis=0) elif stat_processing == 'min': data_processed = data_members.min(axis=0) elif stat_processing == '90p': data_processed = np.percentile(data_members, 90, axis=0) elif stat_processing == '75p': data_processed = np.percentile(data_members, 75, axis=0) elif stat_processing == '50p': data_processed = np.percentile(data_members, 50, axis=0) elif stat_processing == '25p': data_processed = np.percentile(data_members, 25, axis=0) elif stat_processing == '10p': data_processed = np.percentile(data_members, 10, axis=0) #print('shape of data_members: {}'.format(np.shape(data_members))) #print('shape of data_processed: {}'.format(np.shape(data_processed))) ######################################################################## ### plot data on world map ### ######################################################################## ##### set domain due to center point and radius ##### center_point = dict(lat=48.5, lon=9.0) radius = 1800 # domain radius in km around center_point domain = dict( lat_min=center_point['lat'] - radius / 111.2, lat_max=center_point['lat'] + radius / 111.2, lon_min=center_point['lon'] - radius / (111.2 * np.cos(center_point['lat'] * np.pi / 180)), lon_max=center_point['lon'] + radius / (111.2 * np.cos(center_point['lat'] * np.pi / 180)), ) ##### or set domain manually in deg N/E ##### '''domain = dict( lat_min = 0.0, lat_max = 20.0, lon_min = 0.0, lon_max = 20.0, )''' ##### set image size (should be squared) ##### ##### plotting area in pyngl can not exceed squared area even if plotting on rectangular images ##### ##### for obtaining rectangular plots on has to cut manually afterwards e.g. with pillow package ##### x_resolution = 800 y_resolution = 800 wks_res = Ngl.Resources() wks_res.wkWidth = x_resolution wks_res.wkHeight = y_resolution plot_name = 'contourplot_icon-eu-eps_tot_prec_{:02d}-{:02d}h_{}'.format(\ fcst_hours[0], fcst_hours[1], stat_processing) wks_type = 'png' wks = Ngl.open_wks(wks_type, path['base'] + path['plots'] + plot_name, wks_res) resources = Ngl.Resources( ) # create resources object containing all the plot settings resources.mpProjection = 'Hammer' # projection type resources.mpCenterLonF = (domain['lon_max'] + domain['lon_min'] ) / 2 # projection center point resources.mpCenterLatF = (domain['lat_max'] + domain['lat_min']) / 2 resources.mpLimitMode = 'latlon' resources.mpMinLonF = domain['lon_min'] resources.mpMaxLonF = domain['lon_max'] resources.mpMinLatF = domain['lat_min'] resources.mpMaxLatF = domain['lat_max'] ##### set plot area ##### resources.nglMaximize = False resources.vpXF = 0.05 resources.vpYF = 0.9 resources.vpWidthF = 0.7 resources.vpHeightF = 0.7 ##### set all map plot settings ##### resources.mpFillOn = True # turn on filled map areas resources.mpFillColors = [ 'pink', 'blue', 'white', 'white' ] # set colors for [FillValue, Ocean, Land , InlandWater] resources.mpDataBaseVersion = 'MediumRes' # quality of national borders resources.mpDataSetName = 'Earth..4' resources.mpOutlineBoundarySets = 'national' #resources.mpDataBaseVersion = 'HighRes' #resources.mpDataResolution = 'Fine' resources.mpGeophysicalLineThicknessF = 7.0 * x_resolution / 1000 # keep borders thickness resolution-independent resources.mpNationalLineThicknessF = 7.0 * x_resolution / 1000 #resources.mpGridAndLimbDrawOrder = 'postdraw' resources.mpGridAndLimbOn = False # turn off geographic coordinates grid #resources.mpLimbLineColor = 'black' #resources.mpLimbLineThicknessF = 10 #resources.mpGridLineColor = 'black' #resources.mpGridLineThicknessF = 1.0 #resources.mpGridSpacingF = 1 resources.mpPerimOn = True # turn on perimeter around plot resources.mpPerimLineColor = 'black' resources.mpPerimLineThicknessF = 8.0 * x_resolution / 1000 # keep perimeter thickness resolution-independent resources.tmXBOn = False # turn off location ticks around plot resources.tmXTOn = False resources.tmYLOn = False resources.tmYROn = False resources.sfDataArray = data_processed # data input file to plot resources.sfXArray = clon # array with cell center locations resources.sfYArray = clat resources.sfXCellBounds = vlon # array with cell vertices locations resources.sfYCellBounds = vlat resources.sfMissingValueV = 9999 # in case you want to mask values resources.cnFillOn = True resources.cnFillMode = 'CellFill' #resources.cnCellFillEdgeColor = 'black' # uncomment this for plotting the cell edges resources.cnMissingValFillColor = 'black' resources.cnFillPalette = 'WhiteBlueGreenYellowRed' # color palette resources.cnLevelSelectionMode = 'ManualLevels' minlevel = 0.0 # min level of colorbar maxlevel = 50.0 # max level of colorbar numberoflevels = 250 # number of levels of colorbar, max. 250 with this color palette resources.cnMinLevelValF = minlevel resources.cnMaxLevelValF = maxlevel resources.cnLevelSpacingF = (maxlevel - minlevel) / numberoflevels resources.cnLinesOn = False # turn off contour lines resources.cnLineLabelsOn = False # turn off contour labels ##### set resources for a nice colorbar ##### resources.lbLabelBarOn = True resources.lbAutoManage = False resources.lbOrientation = 'vertical' resources.lbLabelOffsetF = 0.05 #resources.lbBoxMinorExtentF = 0.2 resources.lbLabelStride = 25 # print a tick every 25 levels resources.lbLabelFontHeightF = 0.016 resources.lbBoxSeparatorLinesOn = False resources.lbBoxLineThicknessF = 4.0 #resources.lbBoxEndCapStyle = 'TriangleBothEnds' resources.lbLabelAlignment = 'BoxCenters' resources.lbTitleString = 'mm' resources.lbTitleFontHeightF = 0.016 resources.lbTitlePosition = 'Right' resources.lbTitleDirection = 'Across' resources.lbTitleAngleF = 90.0 resources.lbTitleExtentF = 0.1 resources.lbTitleOffsetF = -0.15 resources.nglFrame = False # hold on frame because will plot text afterwards on same plot Ngl.contour_map(wks, data_processed, resources) # plot the actual plot ##### plot title text ##### text = '{:02d}-{:02d}h Total Precipitation {}, ICON-EPS run {:02}.{:02}.{} {:02}Z'.format(\ fcst_hours[0], fcst_hours[1], stat_processing,\ date['day'], date['month'], date['year'], date['hour']) x = 0.5 y = 0.95 text_res_1 = Ngl.Resources() text_res_1.txFontHeightF = 0.018 text_res_1.txJust = 'TopCenter' Ngl.text_ndc(wks, text, x, y, text_res_1) Ngl.frame(wks) # advance frame Ngl.destroy( wks ) # delete workspace to free memory, relevant if plotting various plots in one script print('plotted "{}.png"'.format(plot_name)) return
res.tiMainFontHeightF = 0.02 res.nglSpreadColorEnd = -2 res.lbTitleString = "Sea Ice Concentration" res.lbTitleFontHeightF = 0.012 res.lbLabelFontHeightF = 0.015 res.pmLabelBarOrthogonalPosF = +0.02 #res.lbOrientation = "Horizontal" #res.pmLabelBarHeightF = 0.1 #res.pmLabelBarWidthF = 0.6 res.pmLabelBarHeightF = 0.6 res.pmLabelBarWidthF = 0.1 txres = Ngl.Resources() # Text resources desired txres.txFontHeightF = 0.015 for file in lst_file: print("Plotting "+file) nc = netCDF4.Dataset(file, "r") aice = nc.variables["aice"][0,:,:] time = nc.variables["ocean_time"][0] myday = jday2date(time/86400.) date_tag = myday.strftime('%d %B %Y') print(date_tag) plot = Ngl.contour_map(wks, aice, res) Ngl.text_ndc(wks, date_tag, 0.85, 0.94, txres) nc.close() Ngl.frame(wks) Ngl.end()
resources.mpLimitMode = "LatLon" # Limit portion of map that is viewed. resources.mpMinLatF = float(min(lat)) resources.mpMaxLatF = float(max(lat)) resources.mpMinLonF = float(min(lon)) resources.mpMaxLonF = float(max(lon)) resources.pmLabelBarDisplayMode = "Never" # Turn off labelbar, since we # will use a global labelbar # in the panel. resources.mpPerimOn = True # Turn on map perimeter. resources.mpGridAndLimbOn = False # Turn off map grid. plot = [] for i in range(0,nplots): plot.append(Ngl.contour_map(wks,temp[i,:,:],resources)) # # Draw two titles at the top. Draw these before the panel stuff, # so that the maximization works properly. # textres = Ngl.Resources() textres.txFontHeightF = 0.025 # Size of title. Ngl.text_ndc(wks,"~F22~Temperature (K) at every six hours",0.5,.97,textres) textres.txFontHeightF = 0.02 # Make second title slightly smaller. Ngl.text_ndc(wks,"~F22~January 1996",0.5,.935,textres) #
resources.mpLimitMode = "LatLon" # Limit the map view. resources.mpMinLonF = -97. resources.mpMaxLonF = -90. resources.mpMinLatF = 40. resources.mpMaxLatF = 44. resources.mpPerimOn = True resources.mpOutlineBoundarySets = "geophysicalandusstates" resources.mpDataBaseVersion = "mediumres" resources.mpDataSetName = "Earth..2" resources.mpGridAndLimbOn = False resources.mpUSStateLineThicknessF = 2 resources.cnFillOn = True # Turn on contour fill. resources.cnInfoLabelOn = False # Turn off info label. resources.cnLineLabelsOn = False # Turn off line labels. resources.lbOrientation = "Horizontal" # Draw it horizontally. # label bar. resources.nglSpreadColors = True # Do not interpolate color space. resources.vpYF = 0.9 # Change Y location of plot. zt = Numeric.transpose(zo) contour = Ngl.contour_map(pswks,zt,resources) del contour
resources.nglDraw = True # Turn these resources back on. resources.nglFrame = True resources.mpProjection = "Orthographic" resources.mpDataBaseVersion = "MediumRes" resources.mpLimitMode = "LatLon" resources.mpMinLonF = xs resources.mpMaxLonF = xe resources.mpMinLatF = ys resources.mpMaxLatF = ye resources.mpPerimOn = False resources.mpCenterLatF = 40 resources.mpCenterLonF = -130 map = Ngl.contour_map(wks,ps,resources) resources.cnFillMode = "RasterFill" resources.cnMaxLevelCount = 255 map = Ngl.contour_map(wks,ps,resources) resources.lbOrientation = "Horizontal" #resources.lbLabelFontHeightF = 0.015 resources.mpProjection = "CylindricalEquidistant" resources.mpCenterLatF = 0 map = Ngl.contour_map(wks,ps,resources) resources.cnRasterSmoothingOn = True resources.tiMainString = "HOMME grid: Surface pressure w/smoothing"
#ys = Ngl.get_float(contour.sffield,"sfYCActualStartF") #ye = Ngl.get_float(contour.sffield,"sfYCActualEndF") actual_lons = lons[~to_plot.mask] actual_lats = lats[~to_plot.mask] xs = np.min(actual_lons) xe = np.max(actual_lons) ys = np.min(actual_lats) ye = np.max(actual_lats) resources.mpLimitMode = "LatLon" resources.mpMinLonF = xs # -77.3244 resources.mpMaxLonF = xe # -75.5304 resources.mpMinLatF = ys # 36.6342 resources.mpMaxLatF = ye # 39.6212 # # In PyNGL, the "~" character represents a function code. A function # code signals an operation you want to apply to the following text. # In this case, ~H10Q~ inserts 10 horizontal spaces before the text, # and ~C~ causes a line feed (carriage return). # resources.tiMainString = "~H10Q~Chesapeake Bay~C~Bathymetry~H16Q~meters" resources.lbLabelFontHeightF = 0.02 map = Ngl.contour_map(wks,to_plot,resources) Ngl.end()
wks = Ngl.open_wks(wks_type,"plot_contour_ngl",wkres) #-- open workstation #-- set resources res = Ngl.Resources() #-- generate an resource object for plot if hasattr(f.variables["tsurf"],"long_name"): res.tiMainString = f.variables["tsurf"].long_name #-- set main title res.cnFillOn = True #-- turn on contour fill. res.cnLinesOn = False #-- turn off contour lines res.cnLineLabelsOn = False #-- turn off line labels. res.cnInfoLabelOn = False #-- turn off info label. res.cnLevelSelectionMode = "ManualLevels" #-- select manual level selection mode res.cnMinLevelValF = minval #-- minimum contour value res.cnMaxLevelValF = maxval #-- maximum contour value res.cnLevelSpacingF = inc #-- contour increment res.cnFillPalette = "rainbow" #-- choose color map res.mpGridSpacingF = 30 #-- map grid spacing res.sfXArray = lon #-- longitude locations of data res.sfYArray = lat #-- latitude locations of data res.lbOrientation = "Horizontal" #-- labelbar orientation map = Ngl.contour_map(wks,tempac,res) #-- draw contours over a map. #-- end Ngl.end()
res.cnFillMode = "CellFill" #-- change contour fill mode res.cnCellFillEdgeColor = "black" #-- edges color res.cnCellFillMissingValEdgeColor = "gray50" #-- missing value edges color res.cnMissingValFillColor = "gray50" #-- missing value fill color res.lbOrientation = "Horizontal" #-- labelbar orientation res.tiMainString = "Curvilinear grid: MPI-ESM-LR (2D lat/lon arrays)" #-- title string res.tiMainFontHeightF = 0.022 #-- main title font size res.sfXArray = lon2d #-- longitude grid cell center res.sfYArray = lat2d #-- latitude grid cell center res.mpFillOn = False #-- don't draw filled map res.mpGridLatSpacingF = 10. #-- grid lat spacing res.mpGridLonSpacingF = 10. #-- grid lon spacing res.mpDataBaseVersion = "MediumRes" #-- map database res.mpLimitMode = "LatLon" #-- must be set using minLatF/maxLatF/minLonF/maxLonF res.mpMinLatF = -10. #-- sub-region minimum latitude res.mpMaxLatF = 80. #-- sub-region maximum latitude res.mpMinLonF = -120. #-- sub-region minimum longitude res.mpMaxLonF = 60. #-- sub-region maximum longitude #-- create the plot plot = Ngl.contour_map(wks, var, res) #-- create the contour plot #-- end Ngl.end()
mpres.cnMinLevelValF = -7. # set min contour level mpres.cnMaxLevelValF = 1. # set max contour level mpres.cnLevelSpacingF = 1. # set contour spacing mpres.cnFillColors = [8,17,30,50,65,95,120,134,152,161] mpres.pmTickMarkDisplayMode = "Never" # Don't draw tickmark border. mpres.lbOrientation = "Horizontal" # put labelbar at bottom mpres.pmLabelBarSide = "Bottom" # and horizontal mpres.lbTitleString = "Sea Surface Temperature Change (~S~o~N~C)" mpres.lbTitlePosition = "Bottom" mpres.lbTitleFontHeightF = 0.015 mpres.lbLabelFontHeightF = 0.015 mpres.pmLabelBarOrthogonalPosF = 0.025 map = Ngl.contour_map(wks,sst,mpres) # Draw the first contours/map. Ngl.define_colormap(wks,"WhViBlGrYeOrRe") # set colormap for 2nd contours igray = Ngl.new_color(wks,0.8,0.8,0.8) # add gray # Set up new contour resources mpres.sfXArray = Lon mpres.sfYArray = Lat mpres.cnMinLevelValF = 500. # min contour level mpres.cnMaxLevelValF = 3500. # max contour level mpres.cnLevelSpacingF = 500. # contour spacing mpres.cnFillColors = [20,17,14,12,10,8,6,4] mpres.lbOrientation = "Vertical" # vertical labelbar on
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 res.mpPerimOn = False # Not sure why I need this. res.pmTickMarkDisplayMode = "Never" # Main Title res.tiMainString = "%s (%s) (%d cells)" % \ (data.long_name,data.units,ncells) res.tiMainFontHeightF = 0.018 # Labelbar options res.lbLabelFontHeightF = 0.01 #---Additional resources needed for putting contours on map res.sfXArray = lon res.sfYArray = lat plot = Ngl.contour_map(wks,data[0,:],res) Ngl.end()
res.mpLimitMode = "LatLon" res.mpMinLatF = numpy.min(lat2d)-1 # min lat res.mpMaxLatF = numpy.max(lat2d)+1 # max lat res.mpMinLonF = numpy.min(lon2d)-1 # min lon res.mpMaxLonF = numpy.max(lon2d)+1 # max lon res.tiMainString = "Unobstructed FOV Quality Flag" res.trGridType = "TriangularMesh" # faster graphic rendering res.sfXArray = lon2d # 5 km 2D lat/lon arrays res.sfYArray = lat2d #---Create plot (it won't get drawn yet) plot = Ngl.contour_map(wks,cmfov,res) #---Resources for creating a labelbar lbres = Ngl.Resources() lbres.nglDraw = False lbres.lbPerimOn = False # turn off perimeter. lbres.vpWidthF = 0.60 # width and height lbres.vpHeightF = 0.15 lbres.lbOrientation = "Horizontal" lbres.lbLabelPosition = "Center" # label position lbres.lbFillColors = colors[2:] lbres.lbMonoFillPattern = True # solid color fill lbres.lbLabelFontHeightF = 0.02
# Chukchi plot parameters res.mpProjection = "Stereographic" res.mpCenterLatF = 90 res.mpCenterLonF = 205 res.mpLimitMode = "Corners" res.mpLeftCornerLatF = 60.0 res.mpLeftCornerLonF = 180.0 res.mpRightCornerLatF = 74. res.mpRightCornerLonF = 250.0 res.mpLandFillColor = "Tan1" res.mpOceanFillColor = "SkyBlue" res.mpInlandWaterFillColor = "SkyBlue" plot = Ngl.contour_map(wks, hice, res) res.cnFillOn = True res.cnLinesOn = False res.cnLineLabelsOn = False res.cnFillMode = "CellFill" res.cnCellFillEdgeColor = "Black" res.cnMonoFillColor = True res.cnFillColor = "Transparent" res.cnCellFillMissingValEdgeColor = "Red" plot = Ngl.contour_map(wks, hice, res) #plot = Ngl.contour_map(wks, hice[:-2,:-2], res) Ngl.end()
res.cnFillMode = "CellFill" #-- change contour fill mode res.cnCellFillEdgeColor = "black" #-- edges color res.cnCellFillMissingValEdgeColor = "gray50" #-- missing value edges color res.cnMissingValFillColor = "gray50" #-- missing value fill color res.lbOrientation = "Horizontal" #-- labelbar orientation res.tiMainString = "Curvilinear grid: MPI-ESM-LR (2D lat/lon arrays)" #-- title string res.tiMainFontHeightF = 0.022 #-- main title font size res.sfXArray = lon2d #-- longitude grid cell center res.sfYArray = lat2d #-- latitude grid cell center res.mpFillOn = False #-- don't draw filled map res.mpGridLatSpacingF = 10. #-- grid lat spacing res.mpGridLonSpacingF = 10. #-- grid lon spacing res.mpDataBaseVersion = "MediumRes" #-- map database res.mpLimitMode = "LatLon" #-- must be set using minLatF/maxLatF/minLonF/maxLonF res.mpMinLatF = -10. #-- sub-region minimum latitude res.mpMaxLatF = 80. #-- sub-region maximum latitude res.mpMinLonF = -120. #-- sub-region minimum longitude res.mpMaxLonF = 60. #-- sub-region maximum longitude #-- create the plot plot = Ngl.contour_map(wks,var,res) #-- create the contour plot #-- end Ngl.end()
def simple_grid_fill(xaxis, yaxis, grid, cfg): """ Generate a simple plot, but we already have the data! """ tmpfp = tempfile.mktemp() rlist = Ngl.Resources() if cfg.has_key("wkColorMap"): rlist.wkColorMap = cfg['wkColorMap'] #rlist.wkOrientation = "landscape" # Create Workstation wks = Ngl.open_wks( "ps",tmpfp,rlist) if cfg.has_key("_conus"): res = conus() elif cfg.get("_midwest", False): res = midwest() elif cfg.get("_louisiana", False): res = louisiana2() else: res = iowa2() if cfg.has_key("_MaskZero"): mask = numpy.where( grid <= 0.01, True, False) grid = numpy.ma.array(grid, mask=mask) for key in cfg.keys(): if key == 'wkColorMap' or key[0] == "_": continue setattr(res, key, cfg[key]) res.sfXArray = xaxis res.sfYArray = yaxis # Generate Contour contour = Ngl.contour_map(wks,grid,res) # if cfg.has_key("_showvalues") and cfg['_showvalues']: # txres = Ngl.Resources() # txres.txFontHeightF = 0.012 # for i in range(len(xaxis)): # if cfg.has_key("_valuemask") and cfg['_valuemask'][i] is False: # continue # Ngl.add_text(wks, contour, cfg["_format"] % vals[i], # lons[i], lats[i],txres) if cfg.has_key('_drawx'): for lo, la in zip(cfg['_drawx'], cfg['_drawy']): #print 'Adding Polygon!' plres = Ngl.Resources() plres.gsEdgesOn = True plres.gsEdgeColor = "black" plres.gsFillColor = -1 Ngl.add_polygon(wks, contour, lo, la, plres) if cfg.get("_showvalues", False): txres = Ngl.Resources() txres.txFontHeightF = 0.012 (rows, cols) = numpy.shape(xaxis) for row in range(rows): for col in range(cols): if xaxis[row,col] > res.mpMinLonF and xaxis[row,col] < res.mpMaxLonF and yaxis[row,col] > res.mpMinLatF and yaxis[row,col] < res.mpMaxLatF: Ngl.add_text(wks, contour, cfg["_format"] % grid[row, col], xaxis[row, col], yaxis[row, col], txres) Ngl.draw(contour) if cfg.get('_watermark', True): watermark(wks) manual_title(wks, cfg) Ngl.frame(wks) del wks return tmpfp
#---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()
res.tiMainFontHeightF = 0.02 res.nglSpreadColorEnd = -2 res.lbTitleString = "Sea Ice Concentration" res.lbTitleFontHeightF = 0.012 res.lbLabelFontHeightF = 0.015 res.pmLabelBarOrthogonalPosF = +0.02 #res.lbOrientation = "Horizontal" #res.pmLabelBarHeightF = 0.1 #res.pmLabelBarWidthF = 0.6 res.pmLabelBarHeightF = 0.6 res.pmLabelBarWidthF = 0.1 txres = Ngl.Resources() # Text resources desired txres.txFontHeightF = 0.015 for file in lst_file: print "Plotting "+file nc = netCDF4.Dataset(file, "r") aice = nc.variables["aice"][0,:,:] time = nc.variables["ocean_time"][0] myday = jday2date(time/86400.) date_tag = myday.strftime('%d %B %Y') print date_tag plot = Ngl.contour_map(wks, aice, res) Ngl.text_ndc(wks, date_tag, 0.85, 0.94, txres) nc.close() Ngl.frame(wks) Ngl.end()
resources.mpDataBaseVersion = "MediumRes" # # 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.mpLimitMode = "LatLon" resources.mpMinLonF = xs # -77.3244 resources.mpMaxLonF = xe # -75.5304 resources.mpMinLatF = ys # 36.6342 resources.mpMaxLatF = ye # 39.6212 # # In PyNGL, the "~" character represents a function code. A function # code signals an operation you want to apply to the following text. # In this case, ~H10Q~ inserts 10 horizontal spaces before the text, # and ~C~ causes a line feed (carriage return). # resources.tiMainString = "~H10Q~Chesapeake Bay~C~Bathymetry~H16Q~meters" resources.lbLabelFontHeightF = 0.02 map = Ngl.contour_map(wks, depth, resources) Ngl.end()
res.cnMaxLevelValF = 1040 res.cnLevelSpacingF = 5 #---Map resources res.mpGridAndLimbOn = False #---Labelbar resources res.pmLabelBarOrthogonalPosF = -0.05 res.lbOrientation = "Horizontal" #---Main title res.tiMainString = "Default map tickmarks w/degree symbols" res.tiMainFontHeightF = 0.02 # Create and draw contour-over-map plot map = Ngl.contour_map(wks,psl,res) # Turn off map tickmarks and recreate plot, but don't draw it. res.nglDraw = False res.nglFrame = False res.pmTickMarkDisplayMode = "Never" res.tiMainString = "Customized map tickmarks w/o degree symbols" map = Ngl.contour_map(wks,psl,res) #---------------------------------------------------------------------- # This section creates the lat/lon labels we want for the customized # map tickmarks. #----------------------------------------------------------------------
def main(): start_year = 1981 end_year = 2008 #mean alt path_to_yearly = "alt_era_b1_yearly.nc" ds = Dataset(path_to_yearly) hm = ds.variables["alt"][:] years = ds.variables["year"][:] years_sel = np.where(( start_year <= years ) & (years <= end_year))[0] print(years_sel) hm = hm[np.array(years_sel),:,:] print(hm.shape) good_points = ~np.any(hm < 0, axis = 0) hm2d = np.ma.masked_all(good_points.shape) hm2d[good_points] = np.mean( hm[ : , good_points], axis = 0) #alt from climatology sim_data_folder = "/home/huziy/skynet1_rech3/cordex/CORDEX_DIAG/era40_driven_b1" # dm = CRCMDataManager(data_folder=sim_data_folder) # hc = dm.get_alt_using_monthly_mean_climatology(xrange(start_year,end_year+1)) coord_file = os.path.join(sim_data_folder, "pmNorthAmerica_0.44deg_ERA40-Int_B1_200812_moyenne") basemap, lons2d, lats2d = draw_regions.get_basemap_and_coords(resolution="c", file_path = coord_file#, llcrnrlat=40.0, llcrnrlon=-145, urcrnrlon=-10 ) #basemap.transform_scalar() #basemap = Basemap() lons2d[lons2d > 180] -= 360 x, y = basemap(lons2d, lats2d) print(x.min(), x.max()) permafrost_mask = draw_regions.get_permafrost_mask(lons2d, lats2d) mask_cond = (permafrost_mask <= 0) | (permafrost_mask >= 3) #plot_utils.apply_plot_params(width_pt=None, width_cm=25,height_cm=35, font_size=12) #fig = plt.figure() #assert isinstance(fig, Figure) h_max = 10 #cmap = cm.get_cmap("jet",10) #cmap.set_over(cmap(1.0)) clevels = np.arange(0,h_max+1,1) #gs = gridspec.GridSpec(1,1) all_axes = [] all_img = [] #ax = fig.add_subplot(gs[0,0]) hm2d = np.ma.masked_where(mask_cond | (hm2d > h_max), hm2d) wks_res = Ngl.Resources() assert isinstance(wks_res, Ngl.Resources) wks = Ngl.open_wks("x11", "ALT mean", wks_res) wks_res.cnFillOn = True wks_res.sfXArray = lons2d wks_res.sfYArray = lats2d #---Create contours over map. map = Ngl.contour_map(wks,hm2d,wks_res) #---Draw plot and advance frame. MRB outlines will be included. Ngl.draw(map) Ngl.frame(wks)
dirc = "/mnt/c/Users/Yingqi Fan" f = os.path.join(dirc, "20130601_wind_temp_pres.cdf") data = netCDF4.Dataset(f, "r", format="NETCDF3_CLASSIC") # Open netCDF file. T = data.variables["T"] lat = data.variables["lat"][:, :] lon = data.variables["lon"][:, :] T0 = T[5, 1, :, :] wks_type = "png" wks = Ngl.open_wks(wks_type, "figure") resources = Ngl.Resources() resources.sfXArray = lon resources.sfYArray = lat map = Ngl.contour_map(wks, T0, resources) del T del T0 del lat del lon Ngl.end() #PART2 from __future__ import print_function import numpy import os import netCDF4 import Ngl dirc = "/mnt/c/Users/Yingqi Fan" f = os.path.join(dirc, "20130601_wind_temp_pres.cdf") # Open netCDF file. data = netCDF4.Dataset(f, "r", format="NETCDF3_CLASSIC")
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. nmos = 12 # Specify the number of months in the loop (max 120). for nmo in range(1,nmos): month = nmo+1 for i in xrange(fice_masked.shape[0]): for j in xrange(fice_masked.shape[1]): icemon[i,j] = MA.average(fice_masked[i,j,nmo:ntime:12]) icemon = MA.masked_values(icemon,0.,rtol=0.,atol=1.e-15) icemon = MA.filled(icemon,fill_value) resources.tiMainString = "CSM Y00-99 Mean Ice Fraction Month =" + str(month) map = \ Ngl.contour_map(wks,Ngl.add_cyclic(icemon[0:nsub+1,:]),resources)
mstart = numpy.random.uniform(10, 25, 1).astype(int) mend = numpy.random.uniform(10, 25, 1).astype(int) xstart = numpy.random.uniform(dmin, dmin + 2, 1) xend = numpy.random.uniform(dmax - 2, dmax, 1) #---This is a new resource added in PyNGL 1.5.0 res.cnFillPalette = colormaps[n // 3] res.cnMinLevelValF = dmin res.cnMaxLevelValF = dmax res.cnLevelSpacingF = dspa data = Ngl.generate_2d_array([nlat, nlon], mstart[0], mend[0], xstart[0], xend[0]) plots.append(Ngl.contour_map(wks, data, res)) # Resources for panelling pres = Ngl.Resources() pres.nglFrame = False pres.nglPanelLabelBar = True # Calculate start Y position for first row of plots height = 0.15 # we know this will be height of small plots extra = 1.0 - (3 * height) top = 1.0 - (extra / 2.) # Draw a title before we draw plots title = "Multiple panels on one page, 3 different colormaps" txres = Ngl.Resources() txres.txJust = "BottomCenter"
# # Open a workstation. # wks_type = "ps" 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 ----------------------------------------- ic = Ngl.new_color(wks,0.75,0.75,0.75) # Add gray to the color map resources.mpProjection = "Orthographic" # Change the map projection. resources.mpCenterLonF = 180. # Rotate the projection. resources.mpFillOn = True # Turn on map fill. resources.mpFillColors = [0,-1,ic,-1] # Fill land and leave oceans # and inland water transparent. resources.vpXF = 0.1 # Change the size and location of the resources.vpYF = 0.9 # plot on the viewport. resources.vpWidthF = 0.7 resources.vpHeightF = 0.7
# use colormap and type information to setup output background wks_type = "pdf" wks = Ngl.open_wks(wks_type,"HighRes"+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 #Level selection res.cnLevelSelectionMode = "ExplicitLevels" # Set explicit contour levels res.cnLevels = np.arange(1e-5,8.e-4, 4e-5) # 0,5,10,...,70 # maximize the plot contour = [] res.nglMaximize = True res.nglFrame = False # coordinate settings NewTracerPlot, LonPlot = Ngl.add_cyclic(NewTracer_AI_High[it, lev, :, :], lon_high) res.sfXArray = LonPlot res.sfYArray = lat_high[:] res.vpWidthF = 1 res.vpHeightF = 0.5 Ngl.contour_map(wks,NewTracerPlot,res) Ngl.frame(wks) Ngl.destroy(wks) Ngl.end()
#---Map resources res.mpDataBaseVersion = "MediumRes" # slightly better resolution res.mpOutlineBoundarySets = "USStates" res.mpGridAndLimbOn = False # Turn off lat/lon grid res.pmTickMarkDisplayMode = "Never" # Turn off map tickmarks #---Zoom in on North America. res.mpLimitMode = "LatLon" res.mpMinLatF = min(lat1d) res.mpMaxLatF = max(lat1d) res.mpMinLonF = min(lon1d) res.mpMaxLonF = max(lon1d) #---Create contours over map. map = Ngl.contour_map(wks,data,res) #---Open shapefile with Mississippi River Basin outlines dir = Ngl.pynglpath("data") filename = os.path.join(dir,"shp","mrb.shp") if(not os.path.exists(filename)): print("You do not have the necessary shapefiles to run this example.") print("The comments at the top of this script tell you how to get the files.") sys.exit() f = Nio.open_file(filename, "r") #---Read data off shapefile mrb_lon = f.variables["x"][:] mrb_lat = f.variables["y"][:]
def draw_3D_plot(ptype, clevel, 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 mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = "Red" mkres.gsMarkerSizeF = 15. infiles = ["" for x in range(ncases)] ncdfs = ["" for x in range(ncases)] varis = ["T", "OMEGA", "Z3"] varisobs = ["T", "OMEGA", "Z3"] alpha = ["A", "B", "C", "D", "E", "F"] nvaris = len(varis) cunits = [""] cscale = [1, 864, 1, 1, 1, 1] cscaleobs = [1, 1, 1, 1, 0.04] cntrs = np.zeros((nvaris, 11), np.float32) obsdataset = ["ERAI", "ERAI", "ERAI", "ERAI", "ERAI"] level = [ 1000., 925., 850., 700., 600., 500., 400., 300., 250., 200., 150., 100. ] plot3d = ["" for x in range(nvaris)] for iv in range(0, nvaris): # make plot for each field # 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' inptrobs = Dataset(fileobs, 'r') latobs = inptrobs.variables['lat'][:] lonobs = inptrobs.variables['lon'][:] levobs = inptrobs.variables['lev'][:] levobs_idx = np.abs(levobs - clevel).argmin() B = inptrobs.variables[varisobs[iv]][0, levobs_idx, :, :] B = B * cscaleobs[iv] # cntrs= np.arange(np.min(B),np.max(B),12) if (varis[iv] == "OMEGA"): cntrs[iv, :] = [-50, -40, -30, -20, -10, 0, 10, 20, 30, 40, 50] if (varis[iv] == "Z3"): if (clevel == 500): cntrs[iv, :] = [ 5300, 5400, 5500, 5600, 5700, 5800, 5900, 6000, 6100, 6200, 6300 ] else: cntrs[iv, :] = [ 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300 ] if (varis[iv] == "T"): if (clevel == 500): cntrs[iv, :] = [ 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 310 ] else: cntrs[iv, :] = [ 292, 294, 296, 298, 300, 302, 304, 306, 308, 310, 312 ] if (varis[iv] == "Q"): if (clevel == 500): cntrs[iv, :] = [ 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 310 ] else: cntrs[iv, :] = [ 292, 294, 296, 298, 300, 302, 304, 306, 308, 310, 312 ] #************************************************ # create plot #************************************************ plotname = casedir + '/2D/Horizontal_' + varis[ iv] + '_' + cseason + str(clevel) plot3d[iv] = 'Horizontal_' + varis[iv] + '_' + cseason + str(clevel) wks = Ngl.open_wks(ptype, plotname) Ngl.define_colormap(wks, "amwg256") 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.nglFrame = False pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelBottom = 0.2 pres.nglPanelTop = 0.9 pres.nglPanelLabelBar = True 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.93 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.nglStringFont = _Font # res.nglStringFontHeightF = 0.04 # res.nglRightString = ""#"Cloud Fraction" # res.nglScalarContour = True 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] + '_' + 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'][:] lev = inptrs.variables['lev'][:] lev_idx = np.abs(lev - clevel).argmin() area_wgt = np.zeros(nlat) # area_wgt[:] = gw[:] sits = np.linspace(0, nsite - 1, nsite) ncdf = Dataset(ncdfs[im], 'r') n = ncdf.variables['n'][:] idx_cols = ncdf.variables['idx_cols'][:] A = inptrs.variables[varis[iv]][0, lev_idx, :] 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))) res.tiMainString = "GLB=" 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] 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( sum1 / sum2) #Common_functions.area_avg(B, area_wgt,is_SE)) p = Ngl.contour_map(wks, B, 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) return plot3d
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 res.mpFillOn = False #-- don't use filled map res.mpGridAndLimbOn = False #-- don't draw grid lines res.sfXArray = x #-- transform x to mesh scalar field res.sfYArray = y #-- transform y to mesh scalar field res.sfXCellBounds = vlon #-- needed if set cnFillMode = "CellFill" res.sfYCellBounds = vlat #-- needed if set cnFillMode = "CellFill" res.tiMainString = "Unstructured grid: ICON" #-- title string res.tiMainOffsetYF = 0.03 #-- move main title towards plot #-- create the plot plot = Ngl.contour_map(wks,var,res) #-- draw the plot and advance the frame Ngl.draw(plot) Ngl.frame(wks) #-- get wallclock time t2 = time.time() print "Wallclock time: %0.3f seconds" % (t2-t1) print "" Ngl.end()
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" res.cnMinLevelValF = 55 res.cnMaxLevelValF = 100 res.cnLevelSpacingF = 2.5 res.mpFillOn = False res.mpGridAndLimbOn = False res.sfXArray = lonCell res.sfYArray = latCell res.cnFillMode = "RasterFill" # turn raster on res.tiMainString = "Surface pressure on MPAS grid ({} cells)".format(sp.shape[0]) res.tiMainFontHeightF = 0.018 plot = Ngl.contour_map(wks,sp,res) Ngl.end()
res.lbTitleOffsetF = -0.27 res.lbBoxMinorExtentF = 0.15 res.pmLabelBarOrthogonalPosF = -0.01 res.lbOrientation = "Horizontal" # # Title resources # res.tiMainString = "USGS DEM TRINIDAD (1 x 2 degrees)" res.tiMainFont = "Helvetica-bold" res.tiMainOffsetYF = 0.025 res.tiMainFontHeightF = 0.015 res.nglFrame = False plot = Ngl.contour_map(wks,data,res) # # Draw three text strings after the plot is drawn to make sure plot # gets maximized properly. # txres = Ngl.Resources() txres.txFontHeightF = 0.015 Ngl.text_ndc(wks,"Min Elevation: 1359", 0.22, 0.775, txres) Ngl.text_ndc(wks,"Scale 1:250,000", 0.50, 0.775, txres) Ngl.text_ndc(wks,"Max Elevation: 4322", 0.85, 0.775, txres) Ngl.frame(wks) Ngl.end()
"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) del resources 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()
res.lbTitleOffsetF = -0.27 res.lbBoxMinorExtentF = 0.15 res.pmLabelBarOrthogonalPosF = -0.01 res.lbOrientation = "Horizontal" # # Title resources # res.tiMainString = "USGS DEM TRINIDAD (1 x 2 degrees)" res.tiMainFont = "Helvetica-bold" res.tiMainOffsetYF = 0.025 res.tiMainFontHeightF = 0.015 res.nglFrame = False plot = Ngl.contour_map(wks, data, res) # # Draw three text strings after the plot is drawn to make sure plot # gets maximized properly. # txres = Ngl.Resources() txres.txFontHeightF = 0.015 Ngl.text_ndc(wks, "Min Elevation: 1359", 0.22, 0.775, txres) Ngl.text_ndc(wks, "Scale 1:250,000", 0.50, 0.775, txres) Ngl.text_ndc(wks, "Max Elevation: 4322", 0.85, 0.775, txres) Ngl.frame(wks) Ngl.end()
res.mpOutlineBoundarySets = "AllBoundaries" res.mpNationalLineColor = "gray40" res.mpNationalLineThicknessF = 1.5 res.mpGeophysicalLineColor = "gray40" res.mpGeophysicalLineThicknessF = 1.5 res.cnMonoLineColor = True res.cnLevelSelectionMode = "ManualLevels" res.cnMinLevelValF = 1000.0 res.cnMaxLevelValF = 6000.0 res.cnLevelSpacingF = 250.0 res.cnLineThicknessF = 2.5 # create PWAT plot for analysis data MD_plot = ngl.contour_map(wks,MD,res) ngl.maximize_plot(wks, MD_plot) ngl.draw(MD_plot) ngl.frame(wks) ngl.destroy(wks) del res del MD #del CIN ################################################################################################### # open forecast file f_fili = "GFS_forecast_%s_%s.nc" % (init_dt[:8], init_dt[8:10])
cnres.mpDataBaseVersion = "MediumRes" cnres.cnFillOn = True cnres.cnLinesOn = False cnres.cnLineLabelsOn = False cnres.cnFillMode = "CellFill" cnres.cnCellFillEdgeColor = "Black" cnres.cnMonoFillColor = True cnres.cnFillColor = "Transparent" cnres.cnCellFillMissingValEdgeColor = "Red" cnres.lbLabelBarOn = False cnres.tiMainString = "Pop Grid cells -- grid stride [::3,::3]" plot = Ngl.contour_map(wks,temp[:-2:3,:-2:3],cnres) Ngl.frame(wks) # # Now set up a vector resource variable. # vcres = Ngl.Resources() # # Set coordinate arrays for data. This is necessary in order to overlay # the vectors on a map. # vcres.vfXArray = lon vcres.vfYArray = lat
# Contour options res.cnFillOn = True # turn on contour fill res.cnLinesOn = False # turn off contour lines res.cnLineLabelsOn = False # turn off line labels res.cnFillPalette = "BlGrYeOrReVi200" res.lbLabelFontHeightF = 0.015 # default is a bit large # Set resources necessary to get map projection correct. res.mpLimitMode = "Corners" res.mpLeftCornerLatF = lat[nlat - 1][0] res.mpLeftCornerLonF = lon[nlat - 1][0] res.mpRightCornerLatF = lat[0][nlon - 1] res.mpRightCornerLonF = lon[0][nlon - 1] res.mpCenterLonF = lon.Longitude_of_southern_pole res.mpCenterLatF = lon.Latitude_of_southern_pole + 90 res.trYReverse = True res.tfDoNDCOverlay = True # Set other map resources res.mpGridAndLimbOn = False res.mpDataBaseVersion = "MediumRes" res.mpDataSetName = "Earth..2" res.mpOutlineBoundarySets = "AllBoundaries" # Main Title res.tiMainString = sbt.long_name plot = Ngl.contour_map(wks, sbt[:], res) 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
res.lbLabelBarOn = False # Filled contour/labels/labelinfos res.cnLinesOn = False res.cnFillOn = True res.cnLineLabelsOn = False res.cnInfoLabelOn = False res.mpGridAndLimbOn = False #Level selection # res.lbBoxLinesOn = False res.cnLevelSelectionMode = "ExplicitLevels" # Set explicit contour levels res.cnLevels = np.arange(1e-5, 8.e-4, 4e-5) # maximize the plot res.nglMaximize = True res.nglFrame = False # coordinate settings res.sfXArray = lonAdapt[it, 0:ncolsAdapt[it]] res.sfYArray = latAdapt[it, 0:ncolsAdapt[it]] contour = Ngl.contour_map(wks, NewTracer_AI_Adapt[it, 0:ncolsAdapt[it], lev], res) gsres = Ngl.Resources() gsres.gsLineColor = "Gray25" gsres.gsLineThicknessF = 2.0 for nc in range(ncolsAdapt[it]): Ngl.polyline(wks, contour, vertx[it, nc, :], verty[it, nc, :], gsres) Ngl.frame(wks) # Ngl.Draw(wks) Ngl.destroy(wks) Ngl.end()
import numpy as np import Ngl, Nio #-- open file and read variables f = Nio.open_file("/mnt/e/SYSU/data/NCEP/air.mon.mean.nc", "r") var = f.variables["air"][0, 0, :, :] lat = f.variables["lat"][:] lon = f.variables["lon"][:] wks = Ngl.open_wks("png", "/mnt/e/SYSU/p_py") #-- resource settings res = Ngl.Resources() res.nglFrame = False res.cnFillOn = True res.cnFillPalette = "NCL_default" res.cnLineLabelsOn = False res.lbOrientation = "horizontal" #-- horizontal labelbar res.sfXArray = lon res.sfYArray = lat #-- create the contour plot plot = Ngl.contour_map(wks, var, res) #-- write variable long_name and units to the plot txres = Ngl.Resources() txres.txFontHeightF = 0.012 Ngl.text_ndc(wks,f.variables["air"].attributes['long_name'],\ 0.14,0.82,txres) Ngl.text_ndc(wks,f.variables["air"].attributes['units'], \ 0.95,0.82,txres) #-- advance the frame Ngl.frame(wks) Ngl.end()
# Chukchi plot parameters res.mpProjection = "Stereographic" res.mpCenterLatF = 90 res.mpCenterLonF = 205 res.mpLimitMode = "Corners" res.mpLeftCornerLatF = 60.0 res.mpLeftCornerLonF = 180.0 res.mpRightCornerLatF = 74. res.mpRightCornerLonF = 250.0 res.mpLandFillColor = "Tan1" res.mpOceanFillColor = "SkyBlue" res.mpInlandWaterFillColor = "SkyBlue" plot = Ngl.contour_map(wks, hice, res) res.cnFillOn = True res.cnLinesOn = False res.cnLineLabelsOn = False res.cnFillMode = "CellFill" res.cnCellFillEdgeColor = "Black" res.cnMonoFillColor = True res.cnFillColor = "Transparent" res.cnCellFillMissingValEdgeColor = "Red" plot = Ngl.contour_map(wks, hice, res) #plot = Ngl.contour_map(wks, hice[:-2,:-2], res) Ngl.end()