def save(self, filename='plot'): #'eps' workstation doesn't work reliably, but 'ps' is OK weps = Ngl.open_wks('ps', filename, self.WorkstationResources) Ngl.change_workstation(self.plot, weps) Ngl.draw(self.plot) Ngl.change_workstation(self.plot, self.workstation) Ngl.destroy(weps)
def save(self,filename = 'plot'): #'eps' workstation doesn't work reliably, but 'ps' is OK weps = Ngl.open_wks('ps',filename,self.WorkstationResources) Ngl.change_workstation(self.plot,weps) Ngl.draw(self.plot) Ngl.change_workstation(self.plot,self.workstation) Ngl.destroy(weps)
def skewt(fname, p, tc, tdc, z, wspd, wdir, saveas='pdf', barbstride=20): wks = Ngl.open_wks(saveas,fname) dataOpts = Ngl.Resources() # Options describing """ # data and plotting. dataOpts.sktHeightWindBarbsOn = True # Plot wind barbs at # height levels. dataOpts.sktPressureWindBarbComponents = "SpeedDirection" # Wind speed and # dir [else: u,v]. dataOpts.sktHeightWindBarbPositions = hght # height of wind reports dataOpts.sktHeightWindBarbSpeeds = hspd # speed # [or u components] dataOpts.sktHeightWindBarbDirections = hdir # direction # [or v components] """ skewtOpts = Ngl.Resources() skewtOpts.sktHeightScaleOn = True # default is False skewtOpts.sktHeightScaleUnits = "km" # default is "feet" skewtOpts.sktColoredBandsOn = False # default is False skewtOpts.sktGeopotentialWindBarbColor = "Red" dataOpts.sktPressureWindBarbStride = barbstride skewtOpts.tiMainString = "Graw Launch WBB - Env. Instr Lab 5" # create a background skewt_bkgd = Ngl.skewt_bkg(wks, skewtOpts) # plot the darn profile... skewt_data = Ngl.skewt_plt(wks, skewt_bkgd, p, tc, tdc, z, \ wspd, wdir, dataOpts) Ngl.draw(skewt_bkgd) Ngl.draw(skewt_data) Ngl.frame(wks) Ngl.end()
def hilo_valplot(lons, lats, highs, lows, cfg): """ Special case of having a value plot with a high and low value to plot, which is common for some climate applications """ tmpfp = tempfile.mktemp() cmap = numpy.array([[1., 1., 1.], [0., 0., 0.], [1., 0., 0.], \ [0., 0., 1.], [0., 1., 0.]], 'f') rlist = Ngl.Resources() rlist.wkColorMap = cmap #rlist.wkOrientation = "landscape" wks = Ngl.open_wks("ps", tmpfp, rlist) res = iowa() res.mpOutlineDrawOrder = "PreDraw" plot = Ngl.map(wks, res) for key in cfg.keys(): if key == 'wkColorMap' or key[0] == "_": continue setattr(res, key, cfg[key]) txres = Ngl.Resources() txres.txFontHeightF = 0.016 txres.txFontColor = "red" txres.txJust = "BottomRight" for i in range(len(lons)): Ngl.add_text(wks, plot, cfg["_format"] % highs[i], lons[i], lats[i],txres) txres = Ngl.Resources() txres.txFontHeightF = 0.016 txres.txFontColor = "blue" txres.txJust = "TopRight" for i in range(len(lons)): Ngl.add_text(wks, plot, cfg["_format"] % lows[i], lons[i], lats[i],txres) if cfg.has_key("_labels"): txres = Ngl.Resources() txres.txFontHeightF = 0.008 txres.txJust = "CenterLeft" txres.txFontColor = 1 for i in range(len(lons)): Ngl.add_text(wks, plot, cfg["_labels"][i], lons[i], lats[i],txres) watermark(wks) manual_title(wks, cfg) vpbox(wks) Ngl.draw(plot) Ngl.frame(wks) del wks return tmpfp
def 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 _draw_plots(self, plots, res): """Draw the provided plots.""" for plot in xrange(self.number_plots): # It is OK for a plot to be None, it will just be skipped. This # allows the user to have a lot of control over their panel plot. if plots[plot] is not None: # Set the position of the plot. res_pos = Ngl.Resources() res_pos.vpXF, res_pos.vpYF = self.plot_coordinates[plot] Ngl.set_values(plots[plot], res_pos) # Draw to plot. Ngl.draw(plots[plot])
def __call__(self, *args): """Ngl graphics function with modifications applied.""" # Make a local copy of the resources arguments, preventing them # from being modified in the calling namespace. These copied (and # possibly modified) are used only inside this method. res = list() for i, arg in enumerate(args): if isinstance(arg, Ngl.Resources): res.append((copy(arg), i)) # Form the new argument list containing copies of the resource # variables. We alse need to intercept nglDraw and nglFrame at the top # level, making sure they are turned off while modifications are # applied. After modifications we can check if drawing and frame # advancing was requested and do so then. new_args = list(args) draw_on = frame_on = False for r, i in res: draw_on = getattr(r, 'nglDraw', True) frame_on = getattr(r, 'nglFrame', True) if draw_on: setattr(r, 'nglDraw', False) if frame_on: setattr(r, 'nglFrame', False) new_args[i] = r # Call the modifier pre-plot methods. special_resources = list() for modifier in self.modifiers: # Run the preplot method of each modifier. modifier.preplot(*new_args) special_resources += modifier.resource_names # Go back and remove all special resources from resource variables # before they are passed to the Ngl plotting routine. for r, i in res: for resource_name in special_resources: try: delattr(r, resource_name) except AttributeError: pass # Make the plot. plot = self.f(*new_args) # Call the modifier post-plot methods. wks = args[0] for modifier in self.modifiers: modifier.postplot(wks, plot) # Check if the plot should be drawn and the frame advanced. Do so now # if required. if draw_on: Ngl.draw(plot) if frame_on: Ngl.frame(wks) # Return the modified plot. return plot
def draw(data, lon, lat, dataSources, latRanges, lonRanges, imgTypes, colorBarName, imgOutputPaths, img_output_names, mainTitle, subTitles, unit, dataSources1): ''' 方法定义: 用于绘图。(画的什么图不清楚,建议名字优化一下) @param data: 数据(是否是2D呢??) @param lon: 精度 @param lat: 纬度 (建议常用的查询要素封装成到一个类中去) @param dataSources: 数据源 @param latRanges: 纬度范围 @param lonRanges: 经度 @param imgTypes: 图片格式 @param colorBarName: 颜色名称(到底是啥玩意) @param imgOutputPaths: (图片输出路径) @param img_output_names: (图片名称) @param mainTitle: 主标题 @param subTitles: 副标题 @param unit: 单元(什么的单元???) @param dataSources1: 数据源1(这个数据源1是干嘛用的,为啥叫1) @return: 无返回值,只是用于画图,然后保存而已。 ''' #1.数据信息提取Begin startLon = lonRanges[0] endLon = lonRanges[1] startLat = latRanges[0] endLat = latRanges[1] print(" Longitude starts with %f ,ends with %f " % (startLon, endLon)) #获取经纬度起止值(此处建议引入日志配置,而不是简单的print函数) print(" Latitude starts with %f ,ends with %f " % (startLon, endLon)) image_path = output_directory_absolute_path + img_output_names #指定输出文件 (常量不应该写死在方法内部,应该定义全局变量,或者由配置文件引入。) #2.绘图环境配置Begin wks = create_workstation(colorBarName, image_path) # 3.绘制等值线图 plot = draw_contour(colorBarName, data, endLat, endLon, imgOutputPaths, lat, lon, startLat, startLon, wks) #4.绘制海岸线图 draw_sea_polyline(endLon, plot, wks) Ngl.draw(plot) Ngl.frame(wks) Ngl.end() #5.字体绘制 im = setting_font(dataSources1, image_path, mainTitle, subTitles, unit) #6.加载ncc.png(不清楚这个作用是什么? 背景色吗) setting_bgImage(im) print(image_path + ".png") im.save(image_path + ".png")
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 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 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 plot_xy(vpx=0.2,vpy=0.8,hei=0.3,wth=0.4,xlab='',ylab='',legend=True, yrev=False, lab=''): nprof = len(vy) res = Ngl.Resources() res.nglFrame = False res.nglPaperOrientation = 'Portrait' res.nglMaximize = False res.nglDraw = False res.xyLineColors = colors res.xyLineThicknesses = thicknesses res.tiYAxisString = ylab res.tiXAxisString = xlab res.tiMainString = lab res.tiMainFontHeightF = 0.015 res.tiMainOffsetYF = -hei/4.7 res.tiMainOffsetXF = -wth * 2./5. res.trXMinF = xmin res.trXMaxF = xmax res.trYMinF = ymin res.trYMaxF = ymax res.trYReverse = yrev res.vpXF = vpx res.vpYF = vpy res.vpHeightF = hei res.vpWidthF = wth xy = Ngl.xy(wks,vx[0],vy[0],res) for jn in range(1,nprof): res = Ngl.Resources() res.gsLineColor = colors[jn] res.gsLineDashPattern = patterns[jn] res.gsLineThicknessF = thicknesses[jn] if ( isinstance(vx,list) and len(vx) >= len(vy) ): tmpx = vx[jn] elif (isinstance(vx,list) and len(vx)-1 < jn ): tmpx = vx[0] else: tmpx = vx line = Ngl.add_polyline(wks,xy,tmpx,vy[jn],res) Ngl.draw(xy) wth2 = 0.08 hei2 = 0.08 for jn in range(0,2): if (jn == 0): x0 = vpx+wth-(wth2) y0 = vpy+hei2 st = 0 sp = 4 elif (jn == 1 and nprof > 4): x0 = vpx+wth-(2*wth2+0.05) y0 = vpy+hei2 st = 4 sp = nprof lres = Ngl.Resources() lres.vpWidthF = wth2 lres.vpHeightF = hei2 lres.lgLineColors = colors[st:sp] lres.lgLineThicknesses = thicknesses[st:sp] lres.lgDashIndexes = patterns[st:sp] lres.lgLineLabelsOn = False lres.lgLabelFontHeightF = 0.008 if(legend): lg = Ngl.legend_ndc(wks,sp-st,titles1[st:sp],x0,y0,lres)
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)
def plot_xy(wks,vx,data_vy,vpx=0.2,vpy=0.8,hei=0.3,xlab='',ylab='',\ prof=False,yrev=True,\ linecolors = ['red','blue','black','green','yellow'],\ linethicknesses=[1,1,1,1,1], linepatterns=[0,0,0,0,0],\ titles=[''],\ xmin=0.,xmax=1000.,ymin=0.,ymax=100.,\ frame=True): """ """ if ( isinstance(data_vy,list) ): nprof = len(data_vy) else: data_vy = [data_vy] nprof = 1 vx = fill_blanks(vx,nprof) linecolors = fill_blanks(linecolors,nprof) linepatterns = fill_blanks(linepatterns,nprof) linethicknesses = fill_blanks(linethicknesses,nprof) if (prof): tmp = vx vx = data_vy data_vy = tmp res = Ngl.Resources() res.nglFrame = False res.nglPaperOrientation = 'Portrait' res.nglMaximize = False res.nglDraw = False res.xyLineColors = linecolors res.tiYAxisString = ylab res.tiXAxisString = xlab res.trYReverse = yrev res.trXMinF = xmin res.trXMaxF = xmax res.trYMinF = ymin res.trYMaxF = ymax if(prof): wth = hei * 1./np.sqrt(2.) else: wth = hei * np.sqrt(2.) res.vpXF = vpx res.vpYF = vpy res.vpHeightF = hei res.vpWidthF = wth xy = Ngl.xy(wks,vx[0],data_vy[0],res) for jn in range(1,nprof): res = Ngl.Resources() res.gsLineColor = linecolors[jn] res.gsLineDashPattern = linepatterns[jn] res.gsLineThicknessF = linethicknesses[jn] line = Ngl.add_polyline(wks,xy,vx[jn],data_vy[jn],res) Ngl.draw(xy) wth2 = 0.15 hei2 = 0.08 for jn in range(0,2): if (jn == 0): x0 = vpx+wth-(wth2) y0 = vpy+hei2 st = 0 sp = 4 elif (jn == 1): x0 = vpx+wth-(2*wth2+0.05) y0 = vpy+hei2 st = 4 sp = 7 lres = Ngl.Resources() lres.vpWidthF = wth2 lres.vpHeightF = hei2 lres.lgLineColors = linecolors[st:sp] lres.lgLineThicknesses = linethicknesses[st:sp] lres.lgDashIndexes = linepatterns[st:sp] lres.lgLineLabelsOn = False lres.lgLabelFontHeightF = 0.01 lg = Ngl.legend_ndc(wks,sp-st,titles[st:sp],x0,y0,lres) #tres = Ngl.Resources() #tres.txFontHeightF = 0.015 #tres.txJust = 'CenterLeft' #y = vpy + 0.03 #x0 = vpx #dx = 0.15 #print nprof #print titles #for jn in range(0,nprof): # tres.txFontColor = linecolors[jn] # x = x0 + dx*jn # Ngl.text_ndc(wks,titles[jn],x,y,tres) if (frame): Ngl.frame(wks)
def plot_psirr(vpx=0.2, vpy=0.8, hei=0.4, lbar=True, xlab=1,ylab=1): ## ## Colors for hydrothermal stream functions ## ld = 550. dl = 50 res = Ngl.Resources() res.wkColorMap = 'WhiteBlue' #res.wkColorMap = 'BlueWhiteOrangeRed' Ngl.set_values(wks,res) ## ## Reverse colormap ## del res res = Ngl.Resources() cmap = Ngl.retrieve_colormap(wks) cmap[2:,:] = cmap[-1:1:-1,:] res.wkColorMap = cmap Ngl.set_values(wks,res) psi_levels = np.arange(-ld,0.,dl) if(1): if(1): del res res = Ngl.Resources() res.nglMaximize = False res.nglPaperOrientation = 'Portrait' res.nglFrame = False res.nglDraw = False res.cnFillOn = True res.cnLinesOn = True res.cnLineLabelsOn = False res.cnLineLabelDensityF = 2 res.cnLineLabelBackgroundColor = -1 res.cnLevelSelectionMode = 'ExplicitLevels' res.cnLevels = psi_levels if (lbar): res.pmLabelBarSide = 'Top' res.lbLabelBarOn = True res.lbOrientation = 'Horizontal' res.pmLabelBarDisplayMode = 'Always' res.pmLabelBarWidthF = 0.6 res.pmLabelBarHeightF = 0.03 res.pmLabelBarOrthogonalPosF = 0.07 #res.pmLabelBarParallelPosF = 1.1 res.lbTitleString = 'Sv (10~S~9~N~kg/s)' res.lbLabelFontHeightF = 0.012 res.lbTitleFontHeightF = 0.015 else: res.pmLabelBarDisplayMode = 'Never' res.sfXArray = vx res.sfYArray = vy res.trXMinF = -3 res.trXMaxF = 55 res.trYMinF = 250 res.trYMaxF = 360 res.tiXAxisString = 'Latent heat [kJ/kg]' res.tiYAxisString = 'Dry static energy [kJ/kg]' res.tiMainString = title res.tiMainOffsetYF = -0.045 res.tiMainFontHeightF = 0.015 if (xlab == 1): res.tiXAxisOn = True res.tmXBLabelsOn = True res.tiXAxisSide = 'Bottom' elif (xlab == -1): res.tiXAxisOn = True res.tmXBLabelsOn = False res.tmXTLabelsOn = True res.tiXAxisSide = 'Top' elif (xlab == 0): res.tiXAxisOn = False res.tmXBLabelsOn = False res.tmXTLabelsOn = False if (ylab == 1): res.tiYAxisOn = True res.tmYLLabelsOn = True res.tmYRLabelsOn = False res.tiYAxisSide = 'Left' elif (ylab == -1): res.tiYAxisOn = True res.tmYLLabelsOn = False res.tmYRLabelsOn = True res.tiYAxisSide = 'Right' elif (ylab == 0): res.tiYAxisOn = False res.tmYLLabelsOn = False res.tmYRLabelsOn = False res.vpWidthF = hei res.vpHeightF = hei res.vpYF = vpy res.vpXF = vpx lsmooth = False if (lsmooth): sigma = 2 order = 0 for ji in range(0,2): ndimage.filters.gaussian_filter(zplot[:,:],sigma,order=order,\ output=zplot[:,:],\ mode='reflect', cval=0.0) cont = Ngl.contour(wks,zplot[:,:],res) ## Clausius-Clapeyron line vy_cc = np.linspace(240,360,101) press = 101300. vx_cc,es = cclap(vy_cc*1000/1004.,press) vx_cc = 2.5 * 10**3 * vx_cc #ccstring = 'C-C, RH=100%' lres = Ngl.Resources() lres.gsLineDashPattern = 15 lres.gsLineLabelFontHeightF = 0.009 lres.gsLineThicknessF = 2 #lres.gsLineLabelString = ccstring line = Ngl.add_polyline(wks,cont,vx_cc,vy_cc,lres) ## MSE profile lres = Ngl.Resources() lres.gsLineDashPattern = 1 lres.gsLineThicknessF = 3 line = Ngl.add_polyline(wks,cont,vlh,vdse,lres) Ngl.draw(cont)
def plot_dots(wks,vx,vy,vpx=0.2,vpy=0.8,hei=0.3,xlab='',ylab='',\ prof=False,lreg=True,\ dotcolors = ['red','blue','black','green','yellow'],\ dotsizes=[1,1,1,1,1], dotindices=[9,6,2,3,4,5],\ titles=[''],\ xmin=0.,xmax=1000.,ymin=0.,ymax=100.,\ frame=True): """ """ ndots = len(vy) print dotcolors print dotindices print dotsizes dotcolors = fill_blanks(dotcolors,ndots) dotindices = fill_blanks(dotindices,ndots) dotsizes = fill_blanks(dotsizes,ndots) res = Ngl.Resources() res.nglFrame = False res.nglPaperOrientation = 'Portrait' res.nglMaximize = False res.nglDraw = False res.xyMarkLineMode = 'Markers' res.xyMonoMarkerColor = False res.xyMarkerColors = dotcolors res.xyMarkerThicknesses = 2 res.xyMarkerSizes = np.array(dotsizes) * 0.01 res.xyMarkers = dotindices res.tiYAxisString = ylab res.tiXAxisString = xlab res.trXMinF = xmin res.trXMaxF = xmax res.trYMinF = ymin res.trYMaxF = ymax if(prof): wth = hei * 1./np.sqrt(2.) else: wth = hei * np.sqrt(2.) res.vpXF = vpx res.vpYF = vpy res.vpHeightF = hei res.vpWidthF = wth print vx print vy print xmin,xmax,ymin,ymax xy = Ngl.xy(wks,np.transpose(np.vstack((vx,vx))),np.transpose(np.vstack((vy,vy))),res) if (lreg): ## Fit line k,m,cor,sig,err = stats.linregress(vx,vy) vx = np.linspace(xmin,xmax,10) vy = vx * k + m # Plot line lres = Ngl.Resources() lres.gsLineColor = 'black' lres.gsLineDashPattern = 1 lres.gsLineThicknessF = 2 line = Ngl.add_polyline(wks,xy,vx,vy,lres) # Print correlations text = 'R = '+repr(cor) if (sig*100. < 1.): text = text + ' (99% sign.)' elif (sig*100. < 5.): text = text + ' (95% sign.)' else: text = text + ' (not sign.)' tres = Ngl.Resources() tres.txFontHeightF = 0.01 tres.txJust = 'BottomLeft' tres.txFontColor = 'black' Ngl.text_ndc(wks,text,vpx+wth,vpy-hei-0.03,tres) Ngl.draw(xy) #wth2 = 0.15 #hei2 = 0.08 #for jn in range(0,2): # if (jn == 0): # x0 = vpx+wth-(wth2) # y0 = vpy+hei2 # st = 0 # sp = 4 # elif (jn == 1): # x0 = vpx+wth-(2*wth2+0.05) # y0 = vpy+hei2 # st = 4 # sp = 7 # lres = Ngl.Resources() # lres.vpWidthF = wth2 # lres.vpHeightF = hei2 # lres.lgLineColors = linecolors[st:sp] # lres.lgLineThicknesses = linethicknesses[st:sp] # lres.lgDashIndexes = linepatterns[st:sp] # lres.lgLineLabelsOn = False # lres.lgLabelFontHeightF = 0.01 # lg = Ngl.legend_ndc(wks,sp-st,titles[st:sp],x0,y0,lres) if (frame): Ngl.frame(wks)
lbres.lbTitleOffsetF = 0.00 #---Create the labelbar labels = ["0","1","2","3"] lbid = Ngl.labelbar_ndc (wks,len(labels),labels,0.0,0.,lbres) # # Create some annotation resources indicating how we want to # attach the labelbar to the plot. The default is the center # of the plot. Below amOrthogonalPosF is set to move the # labelbar down and outside the plot. # amres = Ngl.Resources() amres.amOrthogonalPosF = 0.7 annoid = Ngl.add_annotation(plot,lbid,amres) txres = Ngl.Resources() txres.txFontHeightF = 0.01 txres.txJust = "TopRight" txres.txPerimOn = True txid = Ngl.add_text(wks,plot,flnm,res.mpMaxLonF,res.mpMaxLatF,txres) #---This will resize plot so it and the labelbar fit in the frame. Ngl.maximize_plot(wks, plot) #---Drawing the original map also draws the attached labelbar. Ngl.draw(plot) Ngl.frame(wks) Ngl.end()
res.trXMaxF = 20.0 res.trXMinF = 0.0 res.trYMinF = 0.0 # # Width, height, and position of X axis. Every time the # axis is redrawn, the vpYF resource will be changed to change # the position. # res.vpXF = 0.2 res.vpYF = 0.9 res.vpHeightF = 0.02 res.vpWidthF = 0.7 xy = Ngl.xy(wks, x, y, res) Ngl.draw(xy) # # Draw 9 different plots demonstrating control of the bottom x-axis # tickmark labels using the XBFormat string resource. See the description # of the Floating Point Format Specification scheme in the HLU reference # guide to learn about the semantics and syntax of the format string: # # http://www.ncl.ucar.edu/Document/Graphics/format_spec.shtml # # There are links to this description in the TickMark reference pages under # the entries for the format string resources (XBFormat, for example). # sres = Ngl.Resources()
Ngl.overlay(map_plot,line_contour_plot) Ngl.overlay(map_plot,vector_plot) # # Change the title. # srlist = Ngl.Resources() srlist.tiMainString = "vectors, line, and filled contours" Ngl.set_values(map_plot,srlist) # # Draw the map plot, which now contains the vectors and # filled/line contours. # Ngl.maximize_plot(wks,map_plot) # Maximize size of plot in frame. Ngl.draw(map_plot) Ngl.frame(wks) # # Change the title. # srlist.tiMainString = "line and filled contours" Ngl.set_values(map_plot,srlist) # # Remove the vector plot and redraw. We should now # just see the line contours and filled contours. # Ngl.remove_overlay(map_plot,vector_plot,0) Ngl.draw(map_plot) Ngl.frame(wks)
taus_above_zero = Numeric.take(taus,ind_above_zero) px[0::5] = (taus_above_zero - dx/2.).astype(taus.typecode()) px[1::5] = (taus_above_zero - dx/2.).astype(taus.typecode()) px[2::5] = (taus_above_zero + dx/2.).astype(taus.typecode()) px[3::5] = (taus_above_zero + dx/2.).astype(taus.typecode()) px[4::5] = (taus_above_zero - dx/2.).astype(taus.typecode()) py[0::5] = rain_res.trYMinF py[1::5] = Numeric.take(rain03,ind_above_zero) py[2::5] = Numeric.take(rain03,ind_above_zero) py[3::5] = rain_res.trYMinF py[4::5] = rain_res.trYMinF polyg = Ngl.add_polygon(wks,rainhist,px,py,pgres) # # For the outlines, we don't need the fifth point. # polyl = Ngl.add_polyline(wks,rainhist,px,py,pgres) temptmsz = Ngl.xy(wks,taus,tempht,tempsfc_res) # ---------------------- overlay, draw, and advance frame --------- Ngl.overlay(rhfill,templine) # Overlay temperature contour on rh plot. Ngl.overlay(rhfill,windlayer) # Overlay windbarbs on rh plot. Ngl.draw(rhfill) Ngl.draw(rainhist) Ngl.draw(temptmsz) Ngl.frame(wks) Ngl.end()
if Animate: # # Loop through time (the rightmost dimension of "T") and generate # a contour/map plot at each time step. # for nt in range(1,T.shape[0]): print "plotting day ",nt+1 # # There's no need to recreate the contour/map plot since # the only thing changing is the data and the title, so # use Ngl.set_values to change the necessary two resources. # Using Ngl.set_values will result in slightly faster code. # srlist2.sfDataArray = T[nt,:,:] srlist1.lbTitleString = "Day " + str(nt+1) Ngl.set_values(map.contour,srlist1) # changing labelbar string Ngl.set_values(map.sffield,srlist2) # changing data # # Draw new contour/map plot and advance the frame. # Ngl.draw(map.base) Ngl.frame(wks) else: print "Only one frame was generated." print "Set 'Animate' to True if you want to generate all 31 frames." Ngl.end()
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 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
def simple_valplot(lons, lats, vals, cfg): """ Generate a simple plot of values on a map! """ 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() else: res = iowa() if cfg.has_key("_spatialDataLimiter"): xmin, ymin, xmax, ymax = [ min(lons), min(lats), max(lons), max(lats) ] res.mpMinLonF = xmin - 0.25 res.mpMaxLonF = xmax + 0.25 res.mpMinLatF = ymin - 0.25 res.mpMaxLatF = ymax + 0.25 res.mpCenterLonF = (xmax + xmin)/2.0 # Central Longitude res.mpCenterLatF = (ymax + ymin)/2.0 # Central Latitude res.mpOutlineDrawOrder = "PreDraw" res.mpUSStateLineColor = 10 res.mpNationalLineColor = 10 for key in cfg.keys(): if key == 'wkColorMap' or key[0] == "_": continue setattr(res, key, cfg[key]) plot = Ngl.map(wks, res) if cfg.has_key("_stationplot"): Ngl.wmsetp("col", 1) Ngl.wmsetp("ezf",1) if cfg.has_key("_removeskyc"): Ngl.wmsetp("WBC", 0.001) # Get rid of sky coverage Ngl.wmsetp("WBF", 0) # Put barb at center, no sky coverage Ngl.wmsetp("WBR", 0.001) # Size of calm circle #Ngl.wmsetp("WBL", 0.18) # Size of labels #Ngl.wmsetp("WBS", 0.029) # Size of wind barb shaft Ngl.wmstnm(wks, lats, lons, vals) else: txres = Ngl.Resources() txres.txFontHeightF = 0.014 txres.txJust = "BottomCenter" for i in range(len(lons)): Ngl.add_text(wks, plot, cfg.get("_format",'%s') % vals[i], lons[i], lats[i],txres) if cfg.has_key("_labels"): txres = Ngl.Resources() txres.txFontHeightF = 0.008 txres.txJust = "TopCenter" txres.txFontColor = 14 for i in range(len(lons)): Ngl.add_text(wks, plot, cfg["_labels"][i], lons[i], lats[i],txres) watermark(wks) manual_title(wks, cfg) Ngl.draw(plot) vpbox(wks) Ngl.frame(wks) del wks return tmpfp vpbox(wks)
cnres.nglMaximize = True # Maximize plot in frame cnres.nglDraw = False # Don't draw plot cnres.nglFrame = False # Don't advance the frame cnres.cnFillOn = True # Turn on contour fill cnres.cnFillPalette = cmap[:-3, :] cnres.cnLevelSelectionMode = "ManualLevels" cnres.cnLevelSpacingF = nice_spc cnres.cnMinLevelValF = nice_min cnres.cnMaxLevelValF = nice_max cnres.lbOrientation = "Vertical" # Default is horizontal cnres.tiMainString = "This is a title" cnres.tiXAxisString = "X axis" cnres.tiYAxisString = "Y axis" contourplot = Ngl.contour(wks, data, cnres) # Draw plot with viewport and bounding boxes. Ngl.draw(contourplot) draw_bb_box(wks, contourplot) draw_vp_box(wks, contourplot) # Advance frame. Ngl.frame(wks) Ngl.end()
patterns[:] = -1 for i in xrange(len(levels)): if (levels[i] <= -6.): patterns[i] = 5 else: if (levels[i] > 0.): patterns[i] = 17. patterns[-1] = 17 # last pattern rlist = Ngl.Resources() rlist.cnFillPatterns = patterns rlist.cnFillScaleF = 0.8 Ngl.set_values(contour,rlist) Ngl.draw(contour) # Draw the contour plot. txres = Ngl.Resources() # Annotate plot with some text. txres.txFontHeightF = 0.015 Ngl.text_ndc(wks,"~F25~U Component", .270,.815,txres) Ngl.text_ndc(wks,"~F25~(m-s~S~-1~N~)",.765,.815,txres) txres.txFontHeightF = 0.025 # Label right Y axis. txres.txAngleF = 90. Ngl.text_ndc(wks,"~F25~Height (km)",.89,.5,txres) Ngl.frame(wks) # Advance the frame. #----------- Begin second plot -----------------------------------------
# wks_type = "png" wks = Ngl.open_wks(wks_type, "skewt2") skewtOpts = Ngl.Resources() skewtOpts.sktWindSpeedMissingV = -999. # Missing value for # wind speed. skewtOpts.sktWindDirectionMissingV = -999. # Missing value for # wind direction. skewtOpts.sktColoredBandsOn = True # Default is False skewtOpts.tiMainString = "Raob Data; No Winds" skewt_bkgd = Ngl.skewt_bkg(wks, skewtOpts) skewt_data = Ngl.skewt_plt(wks, skewt_bkgd, p, tc, tdc, z, \ wspd, wdir, skewtOpts) Ngl.draw(skewt_bkgd) Ngl.draw(skewt_data) Ngl.frame(wks) # # Plot 2 - Create background skew-T and plot sounding and winds. # wspd = Ngl.fspan(0., 150., nlvl) # wind speed at each level. wdir = Ngl.fspan(0., 360., nlvl) # wind direction. # # Create a few artificial "pibal" reports. # hght = numpy.array([1500., 6000., 10000., 15000.], 'f') # Meters hspd = numpy.array([50., 27., 123., 13.], 'f') hdir = numpy.array([315., 225., 45., 135.], 'f')
if Animate: # # Loop through time (the rightmost dimension of "T") and generate # a contour/map plot at each time step. # for nt in range(1, T.shape[0]): print("plotting day {}".format(nt + 1)) # # There's no need to recreate the contour/map plot since # the only thing changing is the data and the title, so # use Ngl.set_values to change the necessary two resources. # Using Ngl.set_values will result in slightly faster code. # srlist2.sfDataArray = T[nt, :, :] srlist1.lbTitleString = "Day {}".format(nt + 1) Ngl.set_values(map.contour, srlist1) # changing labelbar string Ngl.set_values(map.sffield, srlist2) # changing data # # Draw new contour/map plot and advance the frame. # Ngl.draw(map.base) Ngl.frame(wks) else: print("Only one frame was generated.") print("Set 'Animate' to True if you want to generate all 31 frames.") Ngl.end()
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"][:] #---Add MRB outlines to map lines = add_mrb_lines(wks,map,mrb_lat,mrb_lon) #---Draw plot and advance frame. MRB outlines will be included. Ngl.draw(map) Ngl.frame(wks) # # Get the approximate index values that contain the area # we don't want to mask. # # This will make our gc_inout loop below go faster, because we're # not checking every single lat/lon point to see if it's inside # or outside the area of interest. # min_mrb_lat = min(mrb_lat) max_mrb_lat = max(mrb_lat) min_mrb_lon = min(mrb_lon) max_mrb_lon = max(mrb_lon)
# # Tropic of capricorn. Note: currently there is a limit on the # number of characters in a line label that prevents the '|' # character from being used between each letter in a label # of this length. # gsres.gsLineLabelString = "tr|o|p|ic of c|a|p|r|i|c|o|rn" py[0:2] = [-23.5, -23.5] Ngl.polyline(wks,map,px[:2],py[:2],gsres) # Arctic circle gsres.gsLineLabelString = "a|r|c|t|i|c c|i|r|c|l|e" py[0:2] = [66.5, 66.5] Ngl.polyline(wks,map,px[:2],py[:2],gsres) # Antarctic circle gsres.gsLineLabelString = "|a|n|t|a|r|c|t|i|c c|i|r|c|l|e" py[0:2] = [-66.5, -66.5] Ngl.polyline(wks,map,px[:2],py[:2],gsres) Ngl.draw(map) # Now draw the map and Ngl.frame(wks) # advance the frame. Ngl.end()
tstrings.append(Ngl.add_text(wks,plot,"CH~B~4~N~ + N~B~2~N~O",2,-.97,txres)) tstrings.append(Ngl.add_text(wks,plot,"Mineral Dust",3,-2.4,txres)) tstrings.append(Ngl.add_text(wks,plot,"Continental ice",4,-4.35,txres)) tstrings.append(Ngl.add_text(wks,plot,"+ sea level",4,-4.6,txres)) tstrings.append(Ngl.add_text(wks,plot,"Vegetation",5,-1.77,txres)) tstrings.append(Ngl.add_text(wks,plot,"Orbital",6,0.45,txres)) # # Draw two vertical strings on left side of plot. # txres.txFontHeightF = 0.009 txres.txAngleF = 90. Ngl.text_ndc(wks,"cooling",0.11,0.835,txres) Ngl.text_ndc(wks,"warming",0.11,0.95,txres) Ngl.draw(plot) # Draw the plot; all of the attached lines and # text strings will also get drawn. #========================================================================== print "Beginning robinson map projection section" Ngl.define_colormap(wks,"wh-bl-gr-ye-re") mpres = Ngl.Resources() # New resource list for map plots. mpres.nglMaximize = False mpres.nglFrame = False mpres.vpWidthF = 0.5 mpres.vpHeightF = 0.32 mpres.vpXF = .11 mpres.vpYF = .75
max_cont = 100.0 min_cont = 0.0 res.cnLevelSelectionMode = "ManualLevels" res.cnMinLevelValF = min_cont res.cnMaxLevelValF = max_cont res.cnLevelSpacingF = 2.5 res.cnLineThicknessF = 2.5 # create relative humidity plot for analysis data rh_plot = ngl.contour_map(wks, rh, res) ngl.maximize_plot(wks, rh_plot) ngl.draw(rh_plot) ngl.frame(wks) ngl.destroy(wks) del res ################################################################################################### # open forecast file f_fili = "GFS_forecast_%s_%s.nc" % (init_dt[:8], init_dt[8:10]) forecast = nio.open_file(diri + f_fili) # loop through forecast times for i in range(0, len(fore)):
res.cnLineColor = "steelblue1" res.cnLevelSelectionMode = "ManualLevels" res.cnMinLevelValF = -85.0 res.cnMaxLevelValF = 115.0 res.cnLevelSpacingF = 100.0 # plot ITD and overlay on colour contours ws_plot2 = ngl.contour(wks, ws, res) ngl.overlay(ws_plot, ws_plot2) ngl.overlay(ws_plot, uv_plot) ngl.maximize_plot(wks, ws_plot) ngl.draw(ws_plot) ngl.frame(wks) ngl.destroy(wks) del res del vcres ################################################################################################### # open forecast file f_fili = "GFS_forecast_%s_%s.nc" % (init_dt[:8], init_dt[8:10]) forecast = nio.open_file(diri + f_fili) # loop through forecast times
#添加框框# # 注意必须将frame和draw资源设置为手动 res = Ngl.Resources() res.nglFrame = False # Don't draw plot or advance frame res.nglDraw = False # until we add shapefile outlines. # 注意必须先转换成一维的数组 lnres = Ngl.Resources() lnres.gsLineColor="red" lnres.gsLineThicknessF=5.0 lnres.gsLineDashPattern=0 lon=np.ravel([80,100,100,80,80]) lat=np.ravel([50,50,0,0,50]) lnid = Ngl.add_polyline(wks,plot,lon,lat,lnres) # 手动画图和翻页 Ngl.draw(plot) Ngl.frame(wks) # 翻页操作 vp # view port(vp) 和视觉有关的属性 # make plot bigger res.vpXF = 0.1 res.vpYF = 0.9 res.vpWidthF = 0.8 res.vpHeightF = 0.8 # 画地图的等值线图 contour = Ngl.contour_map Ngl.draw(contour) # 画到画布上 Ngl.frame(wks) # 循环画图时特别重要, The maximum number of open PostScript workstations is fifteen.
bres.tmXBLabelFontHeightF = 0.015 # Make labels smaller. This # will affect Y labels too. #---Set the values and labels for the Y axis of blank plot. bres.tmYLMode = "Explicit" bres.tmYLValues = lat_values bres.tmYLLabels = lat_labels #---Align four corners of both plots, that is, don't do data transformation bres.tfDoNDCOverlay = True #---Create the blank plot. blank = Ngl.blank_plot(wks,bres) #---Draw blank plot for debugging purposes. #Ngl.draw(blank) #Ngl.frame(wks) #---Overlay blank plot on existing map plot. Ngl.overlay(map.base,blank) #---Resize map so it fits within frame Ngl.maximize_plot(wks, map) #---Drawing the original map also draws the overlaid blank plot Ngl.draw(map) Ngl.frame(wks) Ngl.end()
res.mpMinLatF = lattr res.mpMaxLatF = latbl res.mpOutlineBoundarySets = "AllBoundaries" res.mpNationalLineColor = -1 res.mpNationalLineThicknessF = 2.0 res.mpGeophysicalLineColor = -1 res.mpGeophysicalLineThicknessF = 2.0 res.mpGridLatSpacingF = 5.0 res.mpGridLonSpacingF = 5.0 res.mpGridLineThicknessF = 2.0 res.mpGridLineColor = colour res.cnMonoLineColor = True grid_plot = ngl.map(wks, res) ngl.maximize_plot(wks, grid_plot) ngl.draw(grid_plot) ngl.frame(wks) ngl.destroy(wks) del res os.system('mogrify -trim grid_' + colour + '_' + region + '.png') # if region == "WA" or region == "unknownWA": # os.system('mogrify -trim grid_'+colour+'_'+region+'.png') # os.system('mogrify -resize 886x600 grid_'+colour+'_'+region+'.png') # elif region == "EA" or region == "unknownEA": # os.system('mogrify -trim grid_'+colour+'_'+region+'.png') # os.system('mogrify -resize 600x733 grid_'+colour+'_'+region+'.png')
def plot_psirr_lines(vpx=0.2, vpy=0.8, hei=0.4, xlab=1,ylab=1): psi_levels = np.array([-500,-50]) if(1): if(1): res = Ngl.Resources() res.nglMaximize = False res.nglPaperOrientation = 'Portrait' res.nglFrame = False res.nglDraw = False res.cnFillOn = False res.cnLinesOn = True res.cnLineLabelsOn = True res.cnLineLabelDensityF = 2 res.cnLineLabelBackgroundColor = -1 res.cnLevelSelectionMode = 'ExplicitLevels' res.cnLevels = psi_levels res.cnMonoLineColor = True res.cnLineColor = 'blue' res.cnLineThicknessF = 2 res.cnInfoLabelOn = False res.sfXArray = vx res.sfYArray = vy res.trXMinF = -3 res.trXMaxF = 55 res.trYMinF = 250 res.trYMaxF = 360 res.tiXAxisString = 'Latent heat [kJ/kg]' res.tiYAxisString = 'Dry static energy [kJ/kg]' res.tiMainString = title if (xlab == 1): res.tiXAxisOn = True res.tmXBLabelsOn = True res.tiXAxisSide = 'Bottom' elif (xlab == -1): res.tiXAxisOn = True res.tmXBLabelsOn = False res.tmXTLabelsOn = True res.tiXAxisSide = 'Top' elif (xlab == 0): res.tiXAxisOn = False res.tmXBLabelsOn = False res.tmXTLabelsOn = False if (ylab == 1): res.tiYAxisOn = True res.tmYLLabelsOn = True res.tmYRLabelsOn = False res.tiYAxisSide = 'Left' elif (ylab == -1): res.tiYAxisOn = True res.tmYLLabelsOn = False res.tmYRLabelsOn = True res.tiYAxisSide = 'Right' elif (ylab == 0): res.tiYAxisOn = False res.tmYLLabelsOn = False res.tmYRLabelsOn = False res.vpWidthF = hei res.vpHeightF = hei res.vpYF = vpy res.vpXF = vpx lsmooth = False if (lsmooth): sigma = 2 order = 0 for ji in range(0,2): ndimage.filters.gaussian_filter(zplot1[:,:],sigma,order=order,\ output=zplot[:,:],\ mode='reflect', cval=0.0) cont1 = Ngl.contour(wks,zplot1[:,:],res) ## Clausius-Clapeyron line vy_cc = np.linspace(240,360,101) press = 101300. vx_cc,es = cclap(vy_cc*1000/1004.,press) vx_cc = 2.5 * 10**3 * vx_cc #ccstring = 'C-C, RH=100%' lres = Ngl.Resources() lres.gsLineDashPattern = 15 lres.gsLineLabelFontHeightF = 0.009 lres.gsLineThicknessF = 3 #lres.gsLineLabelString = ccstring line = Ngl.add_polyline(wks,cont1,vx_cc,vy_cc,lres) ## MSE profiles lres = Ngl.Resources() lres.gsLineDashPattern = 1 lres.gsLineThicknessF = 7 lres.gsLineColor = 'blue' line = Ngl.add_polyline(wks,cont1,vlh1,vdse1,lres) res.cnLineColor = 'red' cont2 = Ngl.contour(wks,zplot2[:,:],res) ## MSE profiles lres = Ngl.Resources() lres.gsLineDashPattern = 1 lres.gsLineThicknessF = 7 lres.gsLineColor = 'red' line = Ngl.add_polyline(wks,cont2,vlh2,vdse2,lres) Ngl.overlay(cont2,cont1) Ngl.draw(cont2)
# and that the appropriate tickmarks were turned off in certain areas, # these two plots should look like one plot, but with two separate # curves and two separate Y axes. # # Also, change the main title of the first plot to reflect that # we have two vars here, and remove the main title from the second plot. # sres = Ngl.Resources() sres.tiMainString = "Two variables with individual scales" Ngl.set_values(plot1, sres) sres = Ngl.Resources() sres.tiMainOn = False Ngl.set_values(plot2, sres) Ngl.draw(plot1) Ngl.draw(plot2) Ngl.frame(wks) # # Just to show it can be done, add the second plot as an annotation # of the first plot. # sres = Ngl.Resources() sres.amZone = 0 # '0' means centered over base plot. sres.amResizeNotify = True anno = Ngl.add_annotation(plot1, plot2, sres) # # Change the main title to reflect this is an added annotation. #
def plot_dots(vpx=0.2,vpy=0.8,hei=0.3,wth=0.4,xlab='',ylab='',legend=True, yrev=False, lab=''): res = Ngl.Resources() res.nglFrame = False res.nglPaperOrientation = 'Portrait' res.nglMaximize = False res.nglDraw = False res.xyMarkLineMode = 'Markers' res.xyMonoMarkerColor = True res.xyMarkerColor = 'black' res.xyMarkerThicknessF = 2 res.xyMarkerSizeF = 0.01 res.tiYAxisString = ylab res.tiXAxisString = xlab res.tiMainString = lab res.tiMainFontHeightF = 0.015 res.tiMainOffsetYF = -hei/4.7 res.tiMainOffsetXF = -wth * 2./5. res.trXMinF = xmin res.trXMaxF = xmax res.trYMinF = ymin res.trYMaxF = ymax res.trYReverse = yrev res.vpXF = vpx res.vpYF = vpy res.vpHeightF = hei res.vpWidthF = wth xy = Ngl.xy(wks,np.transpose(np.vstack((vx,vx))),np.transpose(np.vstack((vy,vy))),res) if(1): ## Fit line k,m,cor,sig,err = stats.linregress(vx,vy) vx2 = np.linspace(xmin,xmax,10) vy2 = vx2 * k + m # Plot line lres = Ngl.Resources() lres.gsLineColor = 'black' lres.gsLineDashPattern = 1 lres.gsLineThicknessF = 2 line = Ngl.add_polyline(wks,xy,vx2,vy2,lres) # Print correlations text = 'k = %.2f R = %4.2f' % (k,cor) if (sig*100. < 1.): text = text + ' (99% sign.)' elif (sig*100. < 5.): text = text + ' (95% sign.)' else: text = text + ' (not sign.)' tres = Ngl.Resources() tres.txFontHeightF = 0.012 tres.txJust = 'CenterLeft' tres.txFontColor = 'black' Ngl.text_ndc(wks,text,vpx,vpy+0.02,tres) Ngl.draw(xy)
cnres.sfYArray = time cnres.tmXBMode = "Explicit" # Label X and Y axes cnres.tmYLMode = "Explicit" # with explicit labels. cnres.tmXBValues = lon_values cnres.tmYLValues = time_values cnres.tmXBLabels = lon_labels cnres.tmYLLabels = time_labels cnres.nglPointTickmarksOutward = True contour = Ngl.contour(wks,chi,cnres) # Create, but don't draw contour plot. neg_dash_contours(contour) # Dash the negative contours. Ngl.draw(contour) # Now draw contours and Ngl.frame(wks) # advance the frame. # # Set some new resources to control how the lines are labeled. # Use Ngl.set_values to apply these new resources to our existing # plot. # nrlist = Ngl.Resources() nrlist.cnLineLabelPlacementMode = "Computed" nrlist.cnLineLabelDensityF = 3. # < 1.0 = less, > 1.0 = more nrlist.cnLineLabelInterval = 1 # Label every line if possible. Ngl.set_values(contour,nrlist)
vcres.vcLineArrowThicknessF = 2.0 # create vector plot for analysis data and overlay on colour contours level 1 uv_plot1 = ngl.vector(wks,u_1,v_1,vcres) # create vector plot for analysis data and overlay on colour contours level2 vcres.vcLineArrowColor = "Red" uv_plot2 = ngl.vector(wks,u_2,v_2,vcres) ngl.overlay(shear_plot,uv_plot1) ngl.overlay(shear_plot,uv_plot2) ngl.maximize_plot(wks, shear_plot) ngl.draw(shear_plot) ngl.frame(wks) ngl.destroy(wks) del res del vcres ################################################################################################### # open forecast file f_fili = "GFS_48h_forecast_%s_%s.nc" % (init_dt[:8], init_dt[8:10]) forecast = nio.open_file(diri+f_fili) # loop through forecast times
# Skew-T resource names decided on. # import Ngl wks_type = "ps" wks = Ngl.open_wks (wks_type, "skewt1") # # First plot - default background # skewtOpts = Ngl.Resources() skewtOpts.tiMainString = "Default Skew-T" skewt_bkgd = Ngl.skewt_bkg(wks, skewtOpts) Ngl.draw(skewt_bkgd) Ngl.frame(wks) del skewtOpts # # Second plot - fancier background # skewtOpts = Ngl.Resources() skewtOpts.sktColoredBandsOn = True # default is False skewtOpts.sktHeightScaleOn = True # default is False skewtOpts.tiMainString = "USAF Skew T, Log(p); DOD-WPC 9-16-1" skewt_bkgd = Ngl.skewt_bkg(wks, skewtOpts) Ngl.draw(skewt_bkgd) Ngl.frame(wks) del skewtOpts
ores.cnFillOpacityF = 1.0 # Fully opaque ores.lbLabelBarOn = False # Turn off labelbar ores.sfMissingValueV = u._FillValue ores.sfXArray = lon['lon|-120:120'] ores.sfYArray = lat['lat|-30:30'] # Use PyNIO's selection syntax to subset the lat/lon area of interest overlay_plot = Ngl.contour(wks, u['time|i1 lat|-30:30 lon|-120:120'], ores) # Overlay the contour plot on the contour/map plot Ngl.overlay(base_plot, overlay_plot) # Drawing the base plot draws both plots Ngl.draw(base_plot) Ngl.frame(wks) # Create the contour/plot again, but with no transparency del bres.cnFillOpacityF plot = Ngl.contour_map(wks, u[1, :, :], bres) # Set resources for a partially transparent polygon. gnres = Ngl.Resources() gnres.gsFillOpacityF = 0.6 # mostly opaque gnres.gsFillColor = "white" lat_box = [-30, -30, 30, 30, -30] lon_box = [-120, 120, 120, -120, -120] # Add a partially opaque filled polygon box to the filled contours
def trj(wks, x, y, time, res=None): ''' Plots trajectories with arrow heads attached. plot = trj(wks, x, y, time, res=None) wks : The identifier returned from calling Ngl.open_wks. x,y : The X and Y coordinates of the curve(s). These values can be one-dimensional NumPy arrays, NumPy masked arrays or two-dimensional NumPy arrays. If x and/or y are two-dimensional, then the leftmost dimension determines the number of curves. time : Time coordinates of the trajectories. These values can be one-dimensional NumPy arrays, NumPy masked arrays res: Resource list using following special resources: Special resources: trjArrowStep : Number of samples between arrow heads. Default: 10 trjArrowOffsetF : Shift the position of the arrows along the curve. Should be between 0. and 1. Default: 0.5 trjArrowDirection : can be 'pos' or 'neg' to select direction of the arrows. Default: 'pos' trjArrowXShapeF : Array containing the x NDC coordinates of the arrow head relative to the heads centre. Default: Equiliteral triangle trjArrowYShapeF : Array containing the y NDC coordinates of the arrow head relative to the heads centre. Default: Equiliteral triangle trjArrowXScaleF : Scales arrow head in X direction, befor rotation is applied. Default: 1. trjArrowYScaleF : Scales arrow head in y direction, befor rotation is applied. Default: 1. trjArrowSizeF : Scales the size of an arrow head. Default: 0.02 The arrow heads are plotted with add_polygon, so all gs* attributes of the resource list are applied to the arrow heads polygon. ''' if not res: res = ngl.Resources() # set default values: if not hasattr(res, 'trjArrowStep'): res.trjArrowStep = 10 if not hasattr(res, 'trjArrowOffsetF'): res.trjArrowOffsetF = .5 else: res.trjArrowOffsetF -= np.floor(res.trjArrowOffsetF) if not hasattr(res, 'trjArrowDirection'): res.trjArrowDirection = 'pos' if not hasattr(res, 'trjArrowXShapeF'): res.trjArrowXShapeF = [np.sqrt(3) / 3., -np.sqrt(3) / 6., -np.sqrt(3) / 6.] res.trjArrowXShapeF = np.asarray(res.trjArrowXShapeF) if not hasattr(res, 'trjArrowYShapeF'): res.trjArrowYShapeF = [0., .5, -.5] res.trjArrowYShapeF = np.asarray(res.trjArrowYShapeF) if not hasattr(res, 'trjArrowXScaleF'): res.trjArrowXScaleF = 1. if not hasattr(res, 'trjArrowYScaleF'): res.trjArrowYScaleF = 1. if not hasattr(res, 'trjArrowSizeF'): res.trjArrowSizeF = .02 # check for draw and frame if hasattr(res, "nglDraw"): doDraw = res.nglDraw else: doDraw = True res.nglDraw = False if hasattr(res, "nglFrame"): doFrame = res.nglFrame else: doFrame = True res.nglFrame = False # Convert to mask array x = np.ma.asarray(x) y = np.ma.asarray(y) time = np.ma.asarray(time) # check input data if x.shape != y.shape: raise ValueError("Inconsistend shape. x, y and time must have the " + "same shape.") if x.ndim < 1 or x.ndim > 2: raise ValueError("Input arrays x and y must be of rank 1 or 2.") if np.rank(x) == 1: # add singleton dimension to the begining x = x[np.newaxis, ...] y = y[np.newaxis, ...] # Dimension of trajectories dim = 0 # mask all missig values np.ma.masked_where(y.mask, x, copy=False) np.ma.masked_where(x.mask, y, copy=False) # create line plot resource res_lines = copy.deepcopy(res) # remove trj* attributes from res_lines for attr in dir(res_lines): if attr[0:3] == "trj" or (attr[0:2] == "gs" and attr[2] != "n"): delattr(res_lines, attr) # create line plot plot = ngl.xy(wks, x, y, res_lines) # get axes length in data coordinates xAxisLen, yAxisLen = [ngl.get_float(plot, "tr" + ax + "MaxF") - ngl.get_float(plot, "tr" + ax + "MinF") for ax in "XY"] # get marker color # to be implemented # place Marker marker_id = [] for t in xrange(x.shape[dim]): xt = x[t, ...].compressed() yt = y[t, ...].compressed() tt = time[::res.trjArrowStep] # shift time by offset if res.trjArrowOffsetF != 0.: tt = tt[:-1] + res.trjArrowOffsetF * (tt[1:] - tt[:-1]) # itterate over markers for tm in tt: # find nearest indices in time array idx = (np.abs(time - tm)).argmin().min() if time[idx] < tm: idx1 = idx idx2 = idx + 1 elif time[idx] > tm: idx1 = idx - 1 idx2 = idx else: if idx == 0: idx1 = idx idx2 = idx + 1 else: idx1 = idx - 1 idx2 = idx if idx >= len(xt) - 1: continue # interpolate linearly to get coordinates ds = (tm - time[idx1]) / (time[idx2] - time[idx1]) xm, ym = [coord[idx1] + ds * (coord[idx2] - coord[idx1]) for coord in [xt, yt]] x1, y1 = ngl.datatondc(plot, xt[idx1], yt[idx1]) x2, y2 = ngl.datatondc(plot, xt[idx2], yt[idx2]) angle = np.arctan2(y2 - y1, x2 - x1) # create marker resource res_marker = copy.deepcopy(res) # scale adjust marker scale res_marker.trjArrowXScaleF = res.trjArrowXScaleF * xAxisLen res_marker.trjArrowYScaleF = res.trjArrowYScaleF * yAxisLen marker_id.append( _plot_trj_marker(wks, plot, xm, ym, angle, res_marker)) if doDraw: ngl.draw(plot) res.nglDraw = True if doFrame: ngl.frame(wks) res.nglFrame = True return plot
res.mpGeophysicalLineColor = "gray40" res.mpGeophysicalLineThicknessF = 1.5 res.cnMonoLineColor = True res.cnLevelSelectionMode = "ManualLevels" res.cnMinLevelValF = 0.0 res.cnMaxLevelValF = 65.0 res.cnLevelSpacingF = 2.5 res.cnLineThicknessF = 2.5 # create PWAT plot for analysis data PWAT_plot = ngl.contour_map(wks, PWAT, res) ngl.maximize_plot(wks, PWAT_plot) ngl.draw(PWAT_plot) ngl.frame(wks) ngl.destroy(wks) del res del PWAT #del CIN ################################################################################################### # open forecast file f_fili = "GFS_forecast_%s_%s.nc" % (init_dt[:8], init_dt[8:10]) forecast = nio.open_file(diri + f_fili) # loop through forecast times
# Transpose the array so we can plot it, because Natgrid returns it # as an X x Y array, rather than Y x X which PyNGL expects. # zt = numpy.transpose(zo) contour = Ngl.contour(wks,zt,resources) # # Add some polymarkers showing the original locations of the X,Y points. # poly_res = Ngl.Resources() poly_res.gsMarkerIndex = 16 poly_res.gsMarkerSizeF = 0.015 Ngl.add_polymarker(wks,contour,x,y,poly_res) Ngl.draw(contour) Ngl.frame(wks) # # Now turn on RasterFill for the contours and compare. # resources.tiMainString = "Interpolation to a 2D grid (RasterFill)" resources.cnFillMode = 'RasterFill' contour = Ngl.contour(wks,zt,resources) # # Draw polymarkers again. # Ngl.add_polymarker(wks,contour,x,y,poly_res) Ngl.draw(contour)
def draw_colormap(wks, cmap): #---Read as RGBA array cmapr = Ngl.read_colormap_file(cmap) #---Set some options orientation = "horizontal" # "horizontal" or "vertical" lbres = Ngl.Resources() if (orientation == "vertical"): width = 0.2 height = 1.0 # full height of viewport xpos = 0.5 - width / 2. # centered ypos = 1.0 # flush w/top of viewport else: height = 0.2 width = 1.0 # full width of viewport xpos = 0.0 # flush right ypos = 0.5 + height / 2. # centered lbres.vpWidthF = width lbres.vpHeightF = height lbres.lbOrientation = orientation lbres.lbLabelsOn = False lbres.lbBoxLinesOn = False #---Make sure labelbar fills the viewport region we specified lbres.lbBoxMinorExtentF = 1.0 lbres.lbTopMarginF = 0.0 lbres.lbBottomMarginF = 0.0 lbres.lbRightMarginF = 0.0 lbres.lbLeftMarginF = 0.0 #---Necessary so we get all solid fill lbres.lbMonoFillPattern = True lbres.lbFillColors = cmapr cmaplen = cmapr.shape[0] labels = ["" for x in range(cmaplen)] lbid = Ngl.labelbar_ndc(wks, cmaplen, labels, xpos, ypos, lbres) Ngl.draw(lbid) #---Draw a box around the labelbar xbox = [xpos, xpos + width, xpos + width, xpos, xpos] ybox = [ypos, ypos, ypos - height, ypos - height, ypos] lnres = Ngl.Resources() lnres.gsLineThicknessF = 1.5 Ngl.polyline_ndc(wks, xbox, ybox, lnres) lnres = Ngl.Resources() lnres.gsLineThicknessF = 1.5 Ngl.polyline_ndc(wks, xbox, ybox, lnres) #---Add name of the color map txres = Ngl.Resources() txres.txFontHeightF = 0.02 if (orientation == "vertical"): txres.txJust = "TopRight" Ngl.text_ndc(wks, cmap, xpos, 1.0, txres) else: txres.txJust = "BottomCenter" Ngl.text_ndc(wks, cmap, 0.5, ypos, txres) Ngl.frame(wks) # Advance the frame
res3.tmYLLabelsOn = False res3.tmYLMinorOn = False # # Turn on the right Y labels and tickmarks and move the axis string to # the right. # res3.tmYRLabelsOn = False res3.tmYROn = False res3.tmYUseLeft = False res3.tmYRFormat = "f" # Gets rid of unnecessary trailing zeros plot3 = Ngl.xy(wks,x2,y2,res3) # Two plots sres = Ngl.Resources() Ngl.set_values(plot1,sres) sres = Ngl.Resources() Ngl.set_values(plot2,sres) sres = Ngl.Resources() Ngl.set_values(plot3,sres) Ngl.draw(plot1) Ngl.draw(plot2) Ngl.draw(plot3) Ngl.frame(wks)
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]) forecast = nio.open_file(diri+f_fili) # loop through forecast times
def grid_order_contourplot(model, grid, first_varying_var, cut_domain): # define paths # path = dict(base='/', plots='data/plots/experimental/gridpoint_order/') print('plotting model: {}'.format(model)) # load icosahedral grid information # if grid == 'icosahedral': clat, clon, vlat, vlon = read_grid_coordinates(model, grid) data_array1 = np.arange(clat.shape[0], dtype='float32') else: clat, clon = read_grid_coordinates(model, grid) clon = clon - 180 if first_varying_var == 'lon': data_array1 = np.arange(clat.shape[0] * clon.shape[0], dtype='float32').reshape( (clat.shape[0], clon.shape[0])) elif first_varying_var == 'lat': data_array1 = np.arange(clat.shape[0] * clon.shape[0], dtype='float32').reshape( (clon.shape[0], clat.shape[0])).T print('data_array1:', data_array1.shape, 'clat:', clat.shape, 'clon:', clon.shape) if grid == 'icosahedral': print('vlat:', vlat.shape, 'vlon:', vlon.shape) print('data_array1 min,max:', data_array1.min(), data_array1.max()) print('clat min,max:', clat.min(), clat.max()) print('clon min,max:', clon.min(), clon.max()) if grid == 'icosahedral': print('vlat min,max:', vlat.min(), vlat.max()) print('vlon min,max:', vlon.min(), vlon.max()) print('------------------------------------------') if cut_domain['name'] == 'uncut': data_array1_cut = data_array1 else: margin_deg = 0 if grid == 'icosahedral': data_array1_cut, clat, clon, vlat, vlon \ = cut_by_domain(cut_domain, grid, data_array1, clat, clon, vlat, vlon, margin_deg) else: data_array1_cut, clat, clon \ = cut_by_domain(cut_domain, grid, data_array1, clat, clon, None, None, margin_deg) print('data_array1:', data_array1_cut.shape, 'clat:', clat.shape, 'clon:', clon.shape) if grid == 'icosahedral': print('vlat:', vlat.shape, 'vlon:', vlon.shape) print('data_array1_cut min,max:', data_array1_cut.min(), data_array1_cut.max()) print('clat min,max:', clat.min(), clat.max()) print('clon min,max:', clon.min(), clon.max()) if grid == 'icosahedral': print('vlat min,max:', vlat.min(), vlat.max()) print('vlon min,max:', vlon.min(), vlon.max()) if grid == 'icosahedral': plot_name = 'gridpoint_order_{}_{}_global_{}'.format( model, grid, cut_domain['name']) else: plot_name = 'gridpoint_order_{}_{}_{}-varying-first_global_{}'.format( model, grid, first_varying_var, cut_domain['name']) # plot basic map with borders # wks_res = Ngl.Resources() x_resolution = 800 y_resolution = 800 wks_res.wkWidth = x_resolution wks_res.wkHeight = y_resolution wks_res.wkColorMap = 'BkBlAqGrYeOrReViWh200' levels1 = np.linspace(data_array1.min(), data_array1.max(), 200) wks_type = 'png' wks = Ngl.open_wks(wks_type, path['base'] + path['plots'] + plot_name, wks_res) mpres = Ngl.Resources() mpres.mpProjection = 'CylindricalEquidistant' mpres.mpLimitMode = 'LatLon' mpres.mpCenterLonF = 0.0 mpres.mpCenterLatF = 0.0 mpres.mpMinLonF = -180. mpres.mpMaxLonF = 180. mpres.mpMinLatF = -90. mpres.mpMaxLatF = 90. mpres.nglMaximize = False mpres.vpXF = 0.003 mpres.vpYF = 1.00 mpres.vpWidthF = 0.86 mpres.vpHeightF = 1.00 mpres.mpMonoFillColor = 'True' mpres.mpFillColor = -1 #Ngl.set_values(wks,mpres) mpres.mpFillOn = True #resources.cnFillDrawOrder = 'Predraw' # draw contours first mpres.mpGridAndLimbOn = False mpres.mpGreatCircleLinesOn = False #mpres.mpOutlineDrawOrder = 'PreDraw' mpres.mpDataBaseVersion = 'LowRes' mpres.mpDataSetName = 'Earth..4' mpres.mpOutlineBoundarySets = 'national' mpres.mpGeophysicalLineColor = 'black' mpres.mpNationalLineColor = 'black' mpres.mpGeophysicalLineThicknessF = 2. * x_resolution / 1000 mpres.mpNationalLineThicknessF = 2. * x_resolution / 1000 mpres.mpPerimOn = True mpres.mpPerimLineColor = 'black' mpres.mpPerimLineThicknessF = 8.0 * x_resolution / 1000 mpres.tmXBOn = False mpres.tmXTOn = False mpres.tmYLOn = False mpres.tmYROn = False mpres.nglDraw = False #-- don't draw plot mpres.nglFrame = False #-- don't advance frame basic_map = Ngl.map(wks, mpres) # plot variable1 in shading/contours # v1res = Ngl.Resources() v1res.sfDataArray = data_array1_cut v1res.sfXArray = clon v1res.sfYArray = clat if grid == 'icosahedral': v1res.cnFillMode = 'CellFill' v1res.sfXCellBounds = vlon v1res.sfYCellBounds = vlat else: v1res.cnFillMode = 'RasterFill' v1res.sfMissingValueV = 9999 v1res.cnLinesOn = False # Turn off contour lines. v1res.cnFillOn = True #v1res.cnFillOpacityF = 0.5 #v1res.cnFillDrawOrder = 'Predraw' v1res.cnLineLabelsOn = False v1res.cnLevelSelectionMode = 'ExplicitLevels' v1res.cnLevels = levels1 # set resources for a nice label bar # v1res.lbLabelBarOn = True v1res.lbAutoManage = False v1res.lbOrientation = 'vertical' v1res.lbLabelOffsetF = 0.04 # minor axis fraction: the distance between colorbar and numbers v1res.lbBoxMinorExtentF = 0.20 # minor axis fraction: width of the color boxes when labelbar down v1res.lbTopMarginF = 0.05 # make a little more space at top for the unit label v1res.lbRightMarginF = 0.0 v1res.lbBottomMarginF = 0.0 v1res.lbLeftMarginF = -0.35 v1res.cnLabelBarEndStyle = 'ExcludeOuterBoxes' #v1res.cnLabelBarEndStyle = 'IncludeOuterBoxes' #v1res.cnExplicitLabelBarLabelsOn = True #v1res.pmLabelBarDisplayMode = 'Always' v1res.pmLabelBarWidthF = 0.10 #v1res.lbLabelStrings = label_str_list v1res.lbLabelFontHeightF = 0.010 #v1res.lbBoxCount = 40 v1res.lbBoxSeparatorLinesOn = False v1res.lbBoxLineThicknessF = 4 #v1res.lbBoxEndCapStyle = 'TriangleBothEnds' v1res.lbLabelAlignment = 'InteriorEdges' v1res.lbLabelStride = 1 v1res.nglFrame = False v1res.nglDraw = False v1plot = Ngl.contour(wks, data_array1_cut, v1res) # plot label bar unit # text_str = 'Index' text_res_1 = Ngl.Resources() text_res_1.txFontColor = 'black' text_x = 0.975 text_y = 0.72 text_res_1.txFontHeightF = 0.012 Ngl.overlay(basic_map, v1plot) Ngl.draw(basic_map) Ngl.text_ndc(wks, text_str, text_x, text_y, text_res_1) Ngl.frame(wks) Ngl.destroy(wks) #Ngl.end() # cut top and bottom whitespace of plot # im = Image.open(path['base'] + path['plots'] + plot_name + '.png') image_array = np.asarray(im.convert('L')) image_array = np.where(image_array < 255, 1, 0) image_filter = np.amax(image_array, axis=1) vmargins = [ np.nonzero(image_filter)[0][0], np.nonzero(image_filter[::-1])[0][0] ] #print(vmargins) #print(im.size) im_cropped = Image.new( 'RGB', (im.size[0], im.size[1] - vmargins[0] - vmargins[1]), (255, 255, 255)) im_cropped.paste( im.crop((0, vmargins[0], im.size[0], im.size[1] - vmargins[1])), (0, 0)) #print(im_cropped.size) im.close() im_cropped.save(path['base'] + path['plots'] + plot_name + '.png', 'png') im_cropped.close() del data_array1, data_array1_cut, clat, clon if grid == 'icosahedral': del vlat, vlon return
res.tiMainFontColor = "Navy" res.tiMainOffsetYF = 0.02 res.tiMainFontHeightF = 0.035 res.tiYAxisString = "Left Y axis string" res.stMonoLineColor = False # Use multiple colors for streamlines. res.stLineThicknessF = 2.0 # Twice as thick res.lbOrientation = "Horizontal" res.pmLabelBarOrthogonalPosF = -0.02 res.pmLabelBarHeightF = 0.1 res.pmLabelBarWidthF = 0.6 plot = Ngl.streamline_scalar(wks, u, v, spd, res) # Create streamline plot. txres = Ngl.Resources() # Text resources desired txres.txFontColor = "OrangeRed" subtitles(wks, plot, "Left string", "Center string", "Right string", txres) del txres.txFontColor # Go back to foreground color (black) txres.txFontHeightF = 0.029 right_axis(wks, plot, "Right Y axis string", txres) Ngl.maximize_plot(wks, plot) Ngl.draw(plot) # Drawing the plot will draw the three subtitles attached. Ngl.frame(wks) Ngl.end()
res.mpFillOn = False #-- don't draw map outlines res.mpGridAndLimbOn = False #-- don't draw grid lines res.cnFillMode = "CellFill" #-- set fill mode 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 = "ICON grid - raster fill" res.tiMainOffsetYF = 0.03 #-- move main title towards plot #-- create the contour plot to retrieve levels and colors plot = Ngl.contour_map(wks,var,res) Ngl.draw(plot) Ngl.frame(wks) del(levels) #========== second plot ============ #-- retrieve the colors and levels from contour plot levels = list(Ngl.get_float_array(plot.contour,"cnLevels")) labels = list(Ngl.get_string_array(plot.contour,"cnLevels")) nlevels = len(levels) #-- define colormap (RGB value range 0-255) colormap255 = np.array([[ 0, 0, 0], [255, 255, 255], [ 80, 255, 255], \ [ 27, 44, 98], [ 45, 102, 175], [ 66, 133, 196], \ [ 90, 166, 217], [119, 189, 230], [148, 211, 243], \ [215, 239, 249], [237, 248, 252], [255, 255, 255], \
# Make sure map plot is same size as contour/map plot. mpres.nglMaximize = False # this must be turned off otherwise plot will be resized! mpres.vpXF = bres.vpx mpres.vpYF = bres.vpy mpres.vpWidthF = bres.vpw mpres.vpHeightF = bres.vph # Turn off since they are already drawn in contour/map plot. mpres.pmTickMarkDisplayMode = "Never" # Make the ocean white and land transparent. This will mask out the contour fill over ocean. mpres.mpOceanFillColor = "white" mpres.mpInlandWaterFillColor = "white" mpres.mpLandFillColor = "transparent" # Create a map plot with the white ocean and transparent land. map_plot = Ngl.map(wks, mpres) # # If you need to resize the plots later---for example, to use in # a panel---then it's easier to make one plot an annotation of # the other. # annoid = Ngl.add_annotation(contour_map_plot, map_plot) Ngl.draw(contour_map_plot) # This draws both plots Ngl.frame(wks) Ngl.end()
resources.vpYF = 0.90 # Change size and location of plot. resources.vpXF = 0.18 resources.vpWidthF = 0.74 resources.vpHeightF = 0.74 resources.trYMaxF = 980 # Set the maximum value for the Y axes. resources.tiYAxisString = "Depth of a subsurface stratum" xy = Ngl.xy(xwks, xo, zt[2:9:2, :], resources) # Draw an XY plot. #----------- Draw to other workstations ------------------------------ Ngl.change_workstation(contour, cgmwks) # Change the workstation that the Ngl.change_workstation(xy, cgmwks) # contour and XY plot is drawn to. Ngl.draw(contour) # Draw the contour plot to the new Ngl.frame(cgmwks) # workstation and advance the frame. Ngl.draw(xy) # Draw the XY plot to the new Ngl.frame(cgmwks) # workstation and advance the frame. Ngl.change_workstation(contour, pswks) # Do the same for the PostScript Ngl.change_workstation(xy, pswks) # workstation. Ngl.draw(contour) Ngl.frame(pswks) Ngl.draw(xy) Ngl.frame(pswks) Ngl.change_workstation(contour, pdfwks) # And for the PDF workstation... Ngl.change_workstation(xy, pdfwks) Ngl.draw(contour) Ngl.frame(pdfwks)
dirc = Ngl.pynglpath("data") f = Nio.open_file(os.path.join(dirc,"cdf","uv300.nc")) u = f.variables["U"][0,:,8] lat = f.variables["lat"][:] #---Start the graphics section wks_type = "png" wks = Ngl.open_wks (wks_type,"newcolor2") # Open "newcolor2.png" for graphics #---Set some resources. res = Ngl.Resources() res.nglDraw = False res.nglFrame = False plot = Ngl.xy (wks,lat,u,res) # Create plot txres = Ngl.Resources() # text mods desired txres.txFont = 30 txres.txFontHeightF = 0.04 # font smaller. default big txres.txFontOpacityF = 0.10 # highly transparent txres.txAngleF = 45. txid = Ngl.add_text(wks,plot,"Preliminary Data",10,15,txres) Ngl.draw(plot) # Drawing plot will draw attached text Ngl.frame(wks) # Advance frame Ngl.end()
resources.vpYF = 0.90 # Change size and location of plot. resources.vpXF = 0.18 resources.vpWidthF = 0.74 resources.vpHeightF = 0.74 resources.trYMaxF = 980 # Set the maximum value for the Y axes. resources.tiYAxisString = "Depth of a subsurface stratum" xy = Ngl.xy(xwks,xo,zt[2:9:2,:],resources) # Draw an XY plot. #----------- Draw to other workstations ------------------------------ Ngl.change_workstation(contour,cgmwks) # Change the workstation that the Ngl.change_workstation(xy,cgmwks) # contour and XY plot is drawn to. Ngl.draw(contour) # Draw the contour plot to the new Ngl.frame(cgmwks) # workstation and advance the frame. Ngl.draw(xy) # Draw the XY plot to the new Ngl.frame(cgmwks) # workstation and advance the frame. Ngl.change_workstation(contour,pswks) # Do the same for the PostScript Ngl.change_workstation(xy,pswks) # workstation. Ngl.draw(contour) Ngl.frame(pswks) Ngl.draw(xy) Ngl.frame(pswks) Ngl.change_workstation(contour,pdfwks) # And for the PDF workstation... Ngl.change_workstation(xy,pdfwks) Ngl.draw(contour) Ngl.frame(pdfwks)
# wks_type = "ps" wks = Ngl.open_wks(wks_type, "skewt2") skewtOpts = Ngl.Resources() skewtOpts.sktWindSpeedMissingV = -999. # Missing value for # wind speed. skewtOpts.sktWindDirectionMissingV = -999. # Missing value for # wind direction. skewtOpts.sktColoredBandsOn = True # Default is False skewtOpts.tiMainString = "Raob Data; No Winds" skewt_bkgd = Ngl.skewt_bkg(wks, skewtOpts) skewt_data = Ngl.skewt_plt(wks, skewt_bkgd, p, tc, tdc, z, \ wspd, wdir, skewtOpts) Ngl.draw(skewt_bkgd) Ngl.draw(skewt_data) Ngl.frame(wks) # # Plot 2 - Create background skew-T and plot sounding and winds. # wspd = Ngl.fspan(0., 150., nlvl) # wind speed at each level. wdir = Ngl.fspan(0., 360., nlvl) # wind direction. # # Create a few artificial "pibal" reports. # hght = numpy.array([1500., 6000., 10000., 15000.], 'f') # Meters hspd = numpy.array([ 50., 27., 123., 13.], 'f') hdir = numpy.array([ 315., 225., 45., 135.], 'f')
plres.gsFillColor = colors[2] if (unemp[i] >= 0.04): plres.gsFillColor = colors[3] startSegment = geometry[i][geom_segIndex] numSegments = geometry[i][geom_numSegs] lines = [] for seg in range(startSegment, startSegment+numSegments): startPT = segments[seg, segs_xyzIndex] endPT = startPT + segments[seg, segs_numPnts] - 1 lines.append(Ngl.add_polygon(wks, plot, lon[startPT:endPT], \ lat[startPT:endPT], plres)) segNum = segNum + 1 Ngl.draw(plot) # Make a labelbar... labels = [ "1", "2", "3", "4" ] lres = Ngl.Resources() lres.vpWidthF = 0.50 # location lres.vpHeightF = 0.05 # " " lres.lbPerimOn = False # Turn off perimeter. lres.lbOrientation = "Horizontal" # Default is vertical. lres.lbLabelAlignment = "BoxCenters" # Default is "BoxCenters". lres.lbFillColors = colors lres.lbMonoFillPattern = True # Fill them all solid. lres.lbLabelFontHeightF = 0.012 # label font height lres.lbTitleString = "percent" # title lres.lbTitlePosition = "Bottom" # location of title
def plot_oope_map(data, figname, size_class=None, percentage=1): ''' Draws 2D OOPE maps. :param xarray.Dataset data: 2D OOPE array. Dims must be (y, x, comm, size) :param str figname: Name of the figure file (must end by .png or .pdf) :param list size_class: Size classes to output (in m) :param float percentage: percentage used to saturate colorbar from percentile. Colorbar is saturated from values of the (X) and (100 - X) percentile. :return: None ''' if size_class is None: size_class = [1e-3, 1e-2, 1e-1, 1] # sort size class in ascending order, and add 0 and infinity as size bounds size_class = np.sort(size_class) if size_class[0] != 0: size_class = np.concatenate(([0], size_class), axis=0) if size_class[-1] != np.Inf: size_class = np.concatenate((size_class, [np.Inf]), axis=0) # Check that the OOPE dataset has 4 dimensions (i.e. no time dimension) ndims = len(data['OOPE'].dims) if ndims != 4: message = 'Data must have dimensions of size (lat, lon, comm, wei)' print(message) sys.exit(0) # Recover data variables length = data['length'].values oope = data['OOPE'].values lon = data['longitude'][:].values lat = data['latitude'][:].values comm = data['community'][:].values.astype(np.int) # mask oope where land oope = np.ma.masked_where(np.isnan(oope), oope) comm_string = misc.extract_community_names(data) if figname.endswith('png'): form = 'png' elif figname.endswith('pdf'): form = 'pdf' else: message = 'Figure name should end with png or pdf' print(message) sys.exit(0) # opens the document wks = Ngl.open_wks(form, figname) # set the document colormap # resngl = Ngl.Resources() # resngl.wkColorMap = 'precip2_15lev' # Ngl.set_values(wks, resngl) # Add gray to the workspace Ngl.new_color(wks, 0.7, 0.7, 0.7) # init the plot resources # For a detailed description, see https://www.ncl.ucar.edu/Document/Graphics/Resources/ res = Ngl.Resources() # not necessary, just a good habit res.nglDraw = False res.nglFrame = False # Set map resources. res.mpLimitMode = "LatLon" # limit map via lat/lon res.mpMinLatF = lat.min() # map area res.mpMaxLatF = lat.max() # latitudes res.mpMinLonF = lon.min() # and res.mpMaxLonF = lon.max() # longitudes res.mpFillOn = True res.mpLandFillColor = "LightGray" res.mpOceanFillColor = -1 res.mpInlandWaterFillColor = "LightBlue" res.mpGeophysicalLineThicknessF = 1 # thickness of coastlines # coordinates for contour plots res.sfXArray = lon res.sfYArray = lat res.cnFillOn = True # filled contour res.cnLinesOn = False # no lines res.cnLineLabelsOn = False # no labels res.cnInfoLabelOn = False # no info about contours res.cnFillMode = 'CellFill' # contourf=AreaFill, pcolor="CellFill" or "RasterFill" res.lbOrientation = "Horizontal" # colorbar orientation res.lbLabelFontHeightF = 0.012 # colorbar label fontsize res.lbTitlePosition = "Bottom" # position of colorbar title res.lbTitleFontHeightF = 0.012 # title font height # res.cnFillPalette = "wgne15" res.cnFillPalette = "WhiteBlueGreenYellowRed" txres = Ngl.Resources() txres.txJust = "BottomCenter" txres.txFontHeightF = 0.02 res.cnLevelSelectionMode = 'ExplicitLevels' res.cnMaxLevelCount = 41 res.mpGridAndLimbOn = True # Equations are complicated with NCARG # see https://www.ncl.ucar.edu/Applications/fcodes.shtml res.lbTitleString = "OOPE (J.kg~S~-1~N~.m~S~-2~N~)" # title of colorbar # Loop over communities for icom in comm: # Loop over size classes for isize in xrange(0, len(size_class) - 1): # Extract sizes comprised between the size class bound iw = np.nonzero((length >= size_class[isize]) & (length < size_class[isize+1]))[0] if iw.size == 0: continue # Integrate OOPE for the given community and given size class temp = oope[:, :, icom, iw] temp = np.sum(temp, axis=-1) # Finds the colorbar limits cmin, cmax = misc.find_percentile(temp, percentage=1) # draw the contour maps # defines the contour res.cnLevels = np.linspace(cmin, cmax, res.cnMaxLevelCount) mapplot = Ngl.contour_map(wks, temp, res) # add title title = 'Community=%s, %.2E m <= L < %.2E m' % (comm_string[icom], size_class[isize], size_class[isize + 1]) Ngl.text_ndc(wks, title, 0.5, 0.85, txres) # draws the map Ngl.draw(mapplot) # add a page to the pdf output Ngl.frame(wks)