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 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_coherence(cohsq, phase1, phase2, symmetry=("symm"), source="", vars1="", vars2="", plotpath="./", wkstype="png", flim=0.5, nwaveplt=20, cmin=0.05, cmax=0.55, cspc=0.05, plotxy=[1, 1], N=[1, 2]): dims = cohsq.shape nplot = dims[0] FillMode = "AreaFill" # text labels abc = list(string.ascii_lowercase) # plot resources #wkstype = wkstype reswks = ngl.Resources() reswks.wkWidth = 3000 reswks.wkHeight = 3000 wks = ngl.open_wks(wkstype, plotpath + "SpaceTimeCoherence_", reswks) plots = [] # coherence2 plot resources res = coh_resources(cmin, cmax, cspc, FillMode, flim, nwaveplt) # phase arrow resources res_a = phase_resources(flim, nwaveplt) # dispersion curve resources dcres = ngl.Resources() dcres.gsLineThicknessF = 2.0 dcres.gsLineDashPattern = 0 # text box resources txres = ngl.Resources() txres.txPerimOn = True txres.txFontHeightF = 0.013 txres.txBackgroundFillColor = "Background" # panel plot resources res_p = panel_resources(nplot, abc) # plot contours and phase arrows pp = 0 while pp < nplot: coh2 = cohsq[pp, :, :] phs1 = phase1[pp, :, :] phs2 = phase2[pp, :, :] if len(symmetry) == nplot: Symmetry = symmetry[pp] else: Symmetry = symmetry var1 = vars1[pp] var2 = vars2[pp] res.tiMainString = source + " coh^2(" + var1 + "," + var2 + ") " + Symmetry plot = ngl.contour(wks, coh2, res) plot_a = ngl.vector(wks, phs1, phs2, res_a) ngl.overlay(plot, plot_a) (matsuno_names, textlabels, textlocsX, textlocsY) = text_labels(Symmetry) nlabel = len(textlocsX) # generate matsuno mode dispersion curves if Symmetry == "midlat": He = [3000, 7000, 10000] matsuno_modes = matsuno_modes_wk_bg(he=He, n=N, latitude=0., max_wn=nwaveplt, n_wn=500, u=30) else: He = [12, 25, 50] matsuno_modes = mp.matsuno_modes_wk(he=He, n=N, latitude=0., max_wn=nwaveplt, n_wn=500) # add polylines for dispersion curves for he in matsuno_modes: df = matsuno_modes[he] wn = df.index.values for wavename in df: for matsuno_name in matsuno_names: if wavename == (matsuno_name + str(he) + "m)"): wave = df[wavename].values wnwave = wn[~np.isnan(wave)] wave = wave[~np.isnan(wave)] ngl.add_polyline(wks, plot, wnwave, wave, dcres) # add text boxes ll = 0 while ll < nlabel: ngl.add_text(wks, plot, textlabels[ll], textlocsX[ll], textlocsY[ll], txres) ll += 1 plots.append(plot) pp += 1 # panel plots ngl.panel(wks, plots, plotxy, res_p) ngl.delete_wks(wks) ngl.end() return
clres.cnLineThicknessF = 3. # triple thick contour lines clres.cnInfoLabelOrthogonalPosF = -0.15 # Move info label up. # # Create the various plots. They will not get drawn because # nglDraw is set to False for all of them. # map_plot = Ngl.map(wks,mpres) vector_plot = Ngl.vector(wks,ua,va,vcres) line_contour_plot = Ngl.contour(wks,pa,clres) fill_contour_plot = Ngl.contour(wks,ta,cfres) # # Overlay everything on the map plot. # Ngl.overlay(map_plot,fill_contour_plot) 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.
vcres.vcMinDistanceF = 0.02 vcres.vcRefAnnoOrthogonalPosF = -0.20 vcres.vcRefAnnoFontHeightF = 0.005 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])
def large_scale_prf (ptype,cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs, casedir): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = 'Red' mkres.gsMarkerSizeF = 15. infiles = ['' for x in range(ncases)] ncdfs = ['' for x in range(ncases)] nregions = nsite localnames=np.append('ERAI',casenames) varis = [ 'CLOUD' , 'CLDLIQ', 'THETA','RELHUM'] varisobs = ['CC_ISBL', 'CLWC_ISBL', 'THETA','RELHUM' ] alphas = ['a) ','b) ','c) ','d) ','e) ','f) ','g) ','h) ','i) ', 'j) ', 'k) ', 'l) ', 'm) ', 'n) ', 'o) ', 'p) ', 'q) ', 'r) ', 's) ', 't) ', 'u) ', 'v) ', 'w) ', 'x) ', 'y) ', 'z) '] nvaris = len(varis) cunits = ['%','g/kg','K', '%' ] cscale = [100, 1000 , 1., 1 ] cscaleobs = [100, 1000 , 1., 1, 1, 1000, 1,1,1,1,1,1,1] obsdataset =['ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI','ERAI','ERAI'] plotlgs=['' for x in range(nsite)] for ire in range (0, nsite): if not os.path.exists(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N'): os.mkdir(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N') plotname = casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N/Largescale_'+str(lons[ire])+'E_'+str(lats[ire])+'N_'+cseason plotlgs[ire] = 'Largescale_'+str(lons[ire])+'E_'+str(lats[ire])+'N_'+cseason wks= Ngl.open_wks(ptype,plotname) Ngl.define_colormap(wks,'GMT_paired') plot = [] res = Ngl.Resources() res.nglMaximize = False res.nglDraw = False res.nglFrame = False res.lgPerimOn = False # no box around res.vpWidthF = 0.30 # set width and height res.vpHeightF = 0.30 res.tiYAxisString = "Pressure [hPa]" if (lats[ire] > 0 and lons[ire]<230 ): res.trYMinF = 400. res.trYMaxF = 1000. else: res.trYMinF = 700. res.trYMaxF = 1000. res.tiMainFont = _Font res.tmYLLabelFont = _Font res.tmXBLabelFont = _Font res.tiYAxisFont = _Font res.tiXAxisFont = _Font res.tmXBLabelFontHeightF = 0.01 res.tmXBLabelFontThicknessF = 1.0 res.xyMarkLineMode = 'Lines' res.xyLineThicknesses = [3.0, 3.0, 3.0, 3.0, 3.0, 3.0,3.,3.,3.,3.,3,3,3,3,3,3,3] res.xyDashPatterns = np.arange(0,24,1) pres = Ngl.Resources() pres.nglFrame = False pres.txFont = _Font pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 # pres.nglPanelTop = 0.88 pres.wkPaperWidthF = 17 # in inches pres.wkPaperHeightF = 28 # in inches pres.nglMaximize = True pres.nglPanelTop = 0.935 pres.nglPanelFigureStrings = alphas pres.nglPanelFigureStringsJust = 'Topleft' pres.nglPanelFigureStringsFontHeightF = 0.015 for iv in range (0, nvaris): if(iv == nvaris-1): res.pmLegendDisplayMode = 'NEVER' res.xyExplicitLegendLabels = casenames[:] res.pmLegendSide = 'top' res.pmLegendParallelPosF = 0.6 res.pmLegendOrthogonalPosF = -0.5 res.pmLegendWidthF = 0.10 res.pmLegendHeightF = 0.10 res.lgLabelFontHeightF = .02 res.lgLabelFontThicknessF = 1.5 res.lgPerimOn = True else: res.pmLegendDisplayMode = 'NEVER' if(obsdataset[iv] =='CCCM'): if(cseason == 'ANN'): fileobs = '/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-'+cseason+'.nc' else: fileobs = '/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-2010-'+cseason+'.nc' inptrobs = Dataset(fileobs,'r') latobs=inptrobs.variables['lat'][:] latobs_idx = np.abs(latobs - lats[ire]).argmin() lonobs=inptrobs.variables['lon'][:] lonobs_idx = np.abs(lonobs - lons[ire]).argmin() B=inptrobs.variables[varisobs[iv]][:,latobs_idx,lonobs_idx] else: if (varisobs[iv] =='PRECT'): fileobs = filepathobs+'/GPCP_'+cseason+'_climo.nc' else: fileobs = filepathobs + obsdataset[iv]+'_'+cseason+'_climo.nc' inptrobs = Dataset(fileobs,'r') if (varisobs[iv] =='THETA'): latobs=inptrobs.variables['lat'][:] latobs_idx = np.abs(latobs - lats[ire]).argmin() lonobs=inptrobs.variables['lon'][:] lonobs_idx = np.abs(lonobs - lons[ire]).argmin() B = inptrobs.variables['T'][0,:,latobs_idx,lonobs_idx] pre1 = inptrobs.variables['lev'][:] for il1 in range (0, len(pre1)): B[il1] = B[il1]*(1000/pre1[il1])**0.286 else: pre1 = inptrobs.variables['lev'][:] latobs=inptrobs.variables['lat'][:] latobs_idx = np.abs(latobs - lats[ire]).argmin() lonobs=inptrobs.variables['lon'][:] lonobs_idx = np.abs(lonobs - lons[ire]).argmin() B = inptrobs.variables[varisobs[iv]][0,:,latobs_idx,lonobs_idx] B[:]=B[:] * cscaleobs[iv] for im in range (0,ncases): ncdfs[im] = './data/'+cases[im]+'_site_location.nc' infiles[im]= filepath[im]+cases[im]+'/'+cases[im]+'_'+cseason+'_climo.nc' inptrs = Dataset(infiles[im],'r') # pointer to file1 lat=inptrs.variables['lat'][:] nlat=len(lat) lon=inptrs.variables['lon'][:] nlon=len(lon) lev=inptrs.variables['lev'][:] nlev=len(lev) ncdf= Dataset(ncdfs[im],'r') n =ncdf.variables['n'][:] idx_cols=ncdf.variables['idx_cols'][:,:] ncdf.close() if (im ==0 ): A_field = np.zeros((ncases,nlev),np.float32) for subc in range( 0, n[ire]): npoint=idx_cols[ire,n[subc]-1]-1 if (varis[iv] == 'THETA'): tmp = inptrs.variables['T'][0,:,npoint] hyam =inptrs.variables['hyam'][:] hybm =inptrs.variables['hybm'][:] ps=inptrs.variables['PS'][0,npoint] ps=ps p0=inptrs.variables['P0'] pre = np.zeros((nlev),np.float32) for il in range (0, nlev): pre[il] = hyam[il]*p0 + hybm[il] * ps tmp[il] = tmp[il] * (100000/pre[il])**0.286 theunits=str(cscale[iv])+inptrs.variables['T'].units else: tmp=inptrs.variables[varis[iv]][0,:,npoint] theunits=str(cscale[iv])+inptrs.variables[varis[iv]].units A_field[im,:] = (A_field[im,:]+tmp[:]/n[ire]).astype(np.float32 ) A_field[im,:] = A_field[im,:] *cscale[iv] inptrs.close() textres = Ngl.Resources() textres.txFontHeightF = 0.02 textres.txFont = _Font textres.txFontHeightF = 0.015 res.tiXAxisString = varis[iv]+ " Unit= " + cunits[iv] res.trXMinF = min(np.min(A_field[0, :]),np.min(B)) res.trXMaxF = max(np.max(A_field[0, :]),np.max(B)) if(varis[iv] == 'CLOUD') : if (lats[ire] >= 0 and lons[ire]<230): res.trXMinF = 0. res.trXMaxF = 50. else: res.trXMinF = 0. res.trXMaxF = 100. if(varis[iv] =='CLDLIQ') : if (lats[ire] >= 0): res.trXMinF = 0. res.trXMaxF = 0.1 else: res.trXMinF = 0. res.trXMaxF = 0.1 if(varis[iv] =='RELHUM') : res.trXMinF = 0. res.trXMaxF = 100. if(varis[iv] == 'THETA') : if (lats[ire] >= 0 and lons[ire]<230 ): res.trXMinF = 290. res.trXMaxF = 340. else: res.trXMinF = 280 res.trXMaxF = 320 if(varis[iv] == 'T') : res.trXMinF = 180 res.trXMaxF = 300 if(varis[iv] == 'U') : res.trXMinF = -40 res.trXMaxF = 40 res.trYReverse = True res.xyLineColors = np.arange(3,20,2) res.xyMarkerColors = np.arange(2,20,2) p = Ngl.xy(wks,A_field,lev,res) res.trYReverse = False res.xyLineColors = ['black'] pt = Ngl.xy(wks,B,pre1,res) Ngl.overlay(p,pt) plot.append(p) Ngl.panel(wks,plot[:],[nvaris/2,2],pres) txres = Ngl.Resources() txres.txFontHeightF = 0.02 txres.txFont = _Font Ngl.text_ndc(wks,'Large-scale VAR at '+ str(lons[ire])+'E,'+str(lats[ire])+'N',0.5,0.93,txres) Common_functions.create_legend(wks,localnames,0.02,np.append('black',np.arange(3,20,2)),0.25,0.85) Ngl.frame(wks) Ngl.destroy(wks) return plotlgs
def create_meteogram_for(filepath, filename, timestamp): with open(filepath + filename) as f: head, input = read_file(f) # Create numpy 2D array cdf = numpy.array(input) # Collect meteorological data pressure = cdf[:, 9] / 100 rain_cum = cdf[:, 16] rain_expl = cdf[:, 17] tempht = cdf[:, 5] - 273.15 hum = cdf[:, 6] taus = cdf[:, 1] u = cdf[:, 7] v = cdf[:, 8] rain_sum = numpy.add(rain_cum, rain_expl) # set up a color map and open an output workstation. colors = numpy.array([ \ [255,255,255], [255,255,255], [255,255,255], \ [240,255,240], [220,255,220], [190,255,190], \ [120,255,120], [ 80,255, 80], [ 50,200, 50], \ [ 20,150, 20] \ ],'f') / 255. wks_type = "png" output_file = filepath + timestamp.strftime( "%m_%d_%H") + "_meteogram_" + filename.split(".")[0] wks = Ngl.open_wks(wks_type, output_file) # calculate secondary data count_xdata = taus[-1] main_hours, sec_hours, labels = generate_xlegend(timestamp, count_xdata) # dew points data and relative humidity rel_hum = humidity_lib.calculate_relative_humidity(hum, tempht, pressure, len(taus)) dew_point = temperature_lib.calculate_dewpoint(tempht, rel_hum, len(taus)) # 3 hour rain sums rain3h_sum, rain3h_time = rain_lib.calculate_3hrain_data(rain_sum, taus) # wind speed wind_speed = wind_lib.calculate_windspeed(u, v, len(taus)) # wind direction wind_direction = wind_lib.calculate_winddirection(u, v, len(taus)) # generate measurand resources # pressure resource sealevel_pressure = pressure_lib.reduce_pressure_to_sealevel( pressure, cdf[:, 5], float(head[13])) pres_res = pressure_lib.get_pressure_resource(count_xdata, sealevel_pressure) pres_res.tiMainString = format_title(head[0], timestamp) pres_res = config_xaxis_legend(pres_res, main_hours, sec_hours, labels) # relative humidity relhum_res = humidity_lib.get_relhumidity_resource(count_xdata) relhum_res = config_xaxis_legend(relhum_res, main_hours, sec_hours, labels) # wind speed recource wind_res = wind_lib.get_windspeed_resource(count_xdata, wind_speed) wind_res = config_xaxis_legend(wind_res, main_hours, sec_hours, labels) # wind direction recource direction_res = wind_lib.get_winddirection_resource( count_xdata, wind_speed) direction_res = config_xaxis_legend(direction_res, main_hours, sec_hours, labels) # rain sum resources rainsum_res = rain_lib.get_rainsum_resource(count_xdata) rainsum_res = config_xaxis_legend(rainsum_res, main_hours, sec_hours, labels) # 3 hour rain sum bar charts rain3h_res = rain_lib.get_3hrain_resource(rain3h_time) rainhist = create_rain_bar_plot(wks, rain3h_time, rain3h_sum, rain3h_res) # ground temperature resource tempsfc_res = temperature_lib.get_temperature_resource( count_xdata, tempht, dew_point) tempsfc_res = config_xaxis_legend(tempsfc_res, main_hours, sec_hours, labels) # generate plot results pressmsz = Ngl.xy(wks, taus, sealevel_pressure, pres_res) relhummsz = Ngl.xy(wks, taus, rel_hum, relhum_res) windmsz = Ngl.xy(wks, taus, wind_speed, wind_res) dirmsz = Ngl.xy(wks, taus, wind_direction, direction_res) rainsum = Ngl.xy(wks, taus, rain_sum, rainsum_res) temptmsz = Ngl.xy(wks, taus, tempht, tempsfc_res) tempsfc_res.xyLineColor = "blue" # line color for dew point dewpmsz = Ngl.xy(wks, taus, dew_point, tempsfc_res) Ngl.draw(pressmsz) Ngl.draw(relhummsz) Ngl.overlay(rainsum, rainhist) Ngl.draw(rainsum) Ngl.draw(windmsz) Ngl.draw(dirmsz) Ngl.overlay(temptmsz, dewpmsz) Ngl.draw(temptmsz) Ngl.frame(wks) Ngl.delete_wks(wks) # delete currently used workstation
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()
cnres2.nglDraw = False cnres2.cnFillOn = False cnres2.cnLinesOn = True cnres2.cnLineLabelsOn = False cnres2.cnInfoLabelOn = False #cnres2.cnLineLabelInterval = 4 #cnres2.cnLineLabelBackgroundColor = -1 #cnres2.cnLineLabelFontColor = "gray20" #cnres2.cnLineLabelFontHeightF = 0.014 #cnres2.cnLabelMasking = True cnres2.cnLineDashPatterns = 3 cnres2.cnLineThicknessF = 4 cnres2.cnLineColor = "gray20" cnres2.cnLevelSelectionMode = "ManualLevels" cnres2.cnMinLevelValF = 0. cnres2.cnMaxLevelValF = 10. cnres2.cnLevelSpacingF = 1. cnres2.sfXArray = lon.data cnres2.sfYArray = lat.data contour = Ngl.contour_map(wks, var1[:, :], cnres) contour2 = Ngl.contour(wks, var1[:, :], cnres2) tx = add_labels_lcm(wks, contour, 5, 5) Ngl.overlay(contour, contour2) Ngl.draw(contour) Ngl.frame(wks) print('end') #Ngl.end()
res.cnMonoLineLabelFontColor = True res.lbLabelFontHeightF = 0.01 res.cnLineDashPattern = 11 res.cnLineThicknessF = 5.0 res.cnLineColor = "purple" res.cnLevelSelectionMode = "ManualLevels" res.cnMinLevelValF = -85.0 res.cnMaxLevelValF = 115.0 res.cnLevelSpacingF = 100.0 # plot ITD and overlay on colour contours dp_plot2 = ngl.contour(wks, dewpoint, res) ngl.overlay(dp_plot, dp_plot2) ngl.maximize_plot(wks, dp_plot) ngl.draw(dp_plot) ngl.frame(wks) ngl.destroy(wks) del res del dewpoint ################################################################################################### # open forecast file f_fili = "GFS_forecast_%s_%s.nc" % (init_dt[:8], init_dt[8:10]) forecast = nio.open_file(diri + f_fili)
res.cnLineLabelsOn = True res.cnLinesOn = True res.cnMonoLineLabelFontColor = True res.lbLabelFontHeightF = 0.01 res.cnLevelSelectionMode = "ManualLevels" res.cnMinLevelValF = geo_thresh - 200.0 res.cnMaxLevelValF = geo_thresh + 200.0 res.cnLevelSpacingF = 200.0 res.cnLineThicknessF = 2.5 # plot ITD and overlay on colour contours HL_plot = ngl.contour(wks, geo_diff, res) ngl.overlay(dp_plot, HL_plot) ngl.maximize_plot(wks, dp_plot) ngl.draw(dp_plot) ngl.frame(wks) ngl.destroy(wks) del res del dp del geo1 del geo2 del geo_diff ################################################################################################### os.system('mogrify -trim *' + region + '_*DPandHL_2M_SNGL_' + init_dt[0:10] +
# Create base plot upon which we will overlay the rest of the # "spaghetti" contours. # plot_base = Ngl.contour_map(wks, hgt0, mpres) # # Copy just the contour resources from mpres to a new resource list (cnres). # cnres = Ngl.Resources() for t in dir(mpres): if (t[0:2] == 'cn' or t[0:2] == 'sf' or t[0:3] == 'ngl'): setattr(cnres, t, getattr(mpres, t)) # # Loop over other 19 fields but only do contour plot. # Note the color index is changing. In loop, we select # a new color from the default color map. # for i in range(19): cnres.cnLineColor = 2 + i # Change line color. hgt0 = Ngl.add_cyclic(hgt[i + 1, :, :]) # Add a cyclic pt to data. plot = Ngl.contour(wks, hgt0, cnres) # Generate contours. Ngl.overlay(plot_base, plot) # Overlay this contour on map. # Draw the plot, add the lon labels, and advance the frame. Ngl.draw(plot_base) add_lon_labels(wks) Ngl.frame(wks) Ngl.end()
resv.vfXArray = lon resv.vfYArray = lat # set the annotation string. ~C~ is line break resv.vcRefAnnoString1 = "Wind Speed~C~ (50 m/s)" resv.vcRefAnnoArrowSpaceF = 0.65 # reduces white space resv.vcRefAnnoString2On = False # remove the string "Reference vector" resv.vcRefMagnitudeF = 50.0 # speed of the reference arrow resv.vcRefLengthF = 0.08 # length of the reference arrow resv.vcMinDistanceF = 0.02 # min. dist. between arrows # Draw a vector plot. Note that here, the vector_map method is not used, # since map projection will be managed vplot = Ngl.vector(wks, u, v, resv) Ngl.overlay(m, vplot) # draws the map Ngl.draw(m) # add a page to the pdf output Ngl.frame(wks) # add the colormap to see the colors # Ngl.draw_colormap(wks) # Ngl.end() # - # <img src="figs/pyngl_examples.000008.png" width="50%">
map_plot = Ngl.map(wks, resmp) plot_fill = Ngl.contour(wks, 3.6E6 * field[:, :, 0], resources) #plt.hist(3.6E6*field[:,:,0].flatten(),range(1,20)) #plt.savefig('RC.png') fst_data = read_fst(file, "PN", 0, fhour, yy) field = fst_data[0] lat = fst_data[1] lon = fst_data[2] respn.sfXArray = lon respn.sfYArray = lat plot_line = Ngl.contour(wks, field[:, :, 0], respn) Ngl.overlay(map_plot, plot_fill) Ngl.overlay(map_plot, plot_line) Ngl.draw(map_plot) Ngl.frame(wks) Ngl.delete_wks(wks) del ([resources, respn, resmp]) print 'done' os.system("convert -density 300 RT.ps RT.png") cmd = "convert -trim -geometry 2000x1500 +repage -border 8 -bordercolor white -background white -flatten RT.png RT.png" os.system(cmd) del ([field, lat, lon]) if var == "RC" and fhour <= 144 and model_name != "HRDPS": print "calculating mid-level precip rate"
taus_above_zero = numpy.take(taus, ind_above_zero) px[0::5] = (taus_above_zero - dx / 2.).astype(taus.dtype.char) px[1::5] = (taus_above_zero - dx / 2.).astype(taus.dtype.char) px[2::5] = (taus_above_zero + dx / 2.).astype(taus.dtype.char) px[3::5] = (taus_above_zero + dx / 2.).astype(taus.dtype.char) px[4::5] = (taus_above_zero - dx / 2.).astype(taus.dtype.char) py[0::5] = rain_res.trYMinF py[1::5] = numpy.take(rain03, ind_above_zero) py[2::5] = numpy.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()
mpres.mpMaskAreaSpecifiers = mask_specs # areas to mask (protect) # # This set of resources deals with a map labelbar. # # Note that this is different from a contour labelbar # (which we will turn off below), and we have more # control over it (i.e. we can set the number of boxes, # the fill # colors, etc) than we do with a contour labelbar. # mpres.pmLabelBarDisplayMode = "Always" # Turn on a map labelbar # Labelbar resources. mpres.lbLabelStrings = ["Ocean","Land","< 0","0-10","10-20","20-30",\ "30-40","40-50","50-60","60-70","70-80", \ "80-90","90-100","> 100"] mpres.lbFillColors = mp_fill_colrs + cn_fill_clrs # Fill resources cnres.cnFillColors = cn_fill_clrs cnres.pmLabelBarDisplayMode = "Never" # turn off, b/c map has one turned on contour = Ngl.contour(wks,z[:,:],cnres) map = Ngl.map(wks,mpres) Ngl.overlay(map,contour) Ngl.draw(map) Ngl.frame(wks) Ngl.end()
res.cnMonoLineLabelFontColor = True res.lbLabelFontHeightF = 0.0075 res.cnLineThicknessF = 2.5 res.cnInfoLabelOn = True res.cnInfoLabelString = "CIN Contours at -50, -100 and -250 J/Kg" res.cnInfoLabelOrthogonalPosF = -0.06 res.cnInfoLabelParallelPosF = 0.505 res.cnLevelSelectionMode = "ExplicitLevels" res.cnLevels = [-250.0, -100.0, -50.0] # plot CIN and overlay on colour contours CIN_plot = ngl.contour(wks,CIN,res) ngl.overlay(CAPE_plot,CIN_plot) ngl.maximize_plot(wks, CAPE_plot) ngl.draw(CAPE_plot) ngl.frame(wks) ngl.destroy(wks) del res del CAPE del CIN ################################################################################################### # open forecast file f_fili = "GFS_forecast_%s_%s.nc" % (init_dt[:8], init_dt[8:10])
def contourwithoverlay(wks,resMP,varin, plotoverlay): plottemp = Ngl.contour_map(wks,varin,resMP) Ngl.overlay(plottemp,plotoverlay) return(plottemp)
mpres.mpLabelsOn = False mpres.mpLeftCornerLatF = 10. mpres.mpLeftCornerLonF = -180. mpres.mpLimitMode = "corners" mpres.mpProjection = "Stereographic" mpres.mpRightCornerLatF = 10. mpres.mpRightCornerLonF = 0. mpres.tiMainFontHeightF = 0.02 mpres.tiMainString = "Busy graphic with contours and streamlines" stream = Ngl.streamline(wks, data[0, :, :], data[1, :, :], stres) contour = Ngl.contour(wks, data[2, :, :], cnres) map = Ngl.map(wks, mpres) Ngl.overlay(map, stream) Ngl.overlay(map, contour) # Since we overlaid 2 plots, we need to resize them to make sure # they fit in frame. Ngl.maximize_plot(wks, map) Ngl.draw(map) Ngl.frame(wks) del cnres.nglDraw del cnres.nglFrame del mpres.nglDraw del mpres.nglFrame del stres.nglDraw del stres.nglFrame
res.vcLineArrowColor = "Black" vcres.vcRefMagnitudeF = 30.0 # define vector ref mag vcres.vcRefLengthF = 0.03 # define length of vec ref vcres.vcMinFracLengthF = 0.3 vcres.vcMinDistanceF = 0.02 vcres.vcRefAnnoOrthogonalPosF = -0.20 vcres.vcRefAnnoFontHeightF = 0.005 vcres.vcLineArrowThicknessF = 2.0 # create vector plot for analysis data and overlay on colour contours uv_plot1 = ngl.vector(wks, max_shear_u2_u1, max_shear_v2_v1, vcres) # create vector plot for analysis data and overlay on colour contours level2 ngl.overlay(PRATE_plot, uv_plot1) ngl.maximize_plot(wks, PRATE_plot) ngl.draw(PRATE_plot) ngl.frame(wks) ngl.destroy(wks) del res.mpProjection del res.mpLimitMode del res.mpMinLonF del res.mpMaxLonF del res.mpMinLatF del res.mpMaxLatF # del res.mpPerimOn del res.mpOutlineBoundarySets del res.mpNationalLineColor
volplot = Ngl.contour(wks,zplot[ja,:,:],res) ## ## Draw hydrothermal stream lines on top ## res.pmLabelBarDisplayMode = 'Never' res.cnFillOn = False res.cnLinesOn = True res.cnLineLabelsOn = True res.cnInfoLabelOn = False res.cnLevels = psi_levels psi2 = psi * 10**(-9) psiplot = Ngl.contour(wks,psi2,res) Ngl.overlay(volplot,psiplot) Ngl.draw(volplot) print '-------------------------------------------' print 'mass('+rts_label[jb]+','+rts_label[jc]+')' print ' '+title[ja] print ' Total mass: '+repr(np.sum(volrr[jb,jc,ja,:,:])) tres = Ngl.Resources() fhei = 0.03 tres.txFontHeightF = fhei Ngl.text_ndc(wks,'b)',0.82,0.67,tres) Ngl.frame(wks)
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
vcres.vfYArray = lat vcres.vcFillArrowsOn = True vcres.vcRefMagnitudeF = 30.0 # define vector ref mag vcres.vcRefLengthF = 0.02 # define length of vec ref vcres.vcMinFracLengthF = 0.3 vcres.vcMinDistanceF = 0.02 vcres.vcRefAnnoOrthogonalPosF = -0.20 vcres.vcRefAnnoFontHeightF = 0.005 cnres.tiMainString = "Fully opaque filled vectors over filled contours" #---Draw fully opaque vectors uv_plot = Ngl.vector(wks,u,v,vcres) spd_plot = Ngl.contour_map(wks,spd,cnres) Ngl.overlay(spd_plot,uv_plot) Ngl.maximize_plot(wks, spd_plot) Ngl.draw(spd_plot) Ngl.frame(wks) #---This time make vectors partially transparent vcres.vcGlyphOpacityF = 0.3 cnres.tiMainString = "Partially transparent vectors over filled contours" uv_plot = Ngl.vector(wks,u,v,vcres) spd_plot = Ngl.contour_map(wks,spd,cnres) Ngl.overlay(spd_plot,uv_plot) Ngl.maximize_plot(wks, spd_plot) Ngl.draw(spd_plot) Ngl.frame(wks)
res.cnMonoLineLabelFontColor = True res.lbLabelFontHeightF = 0.01 res.cnLineDashPattern = 0 res.cnLineThicknessF = 5.0 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])
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()
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)
def draw_gh_500hPa(sel_year, sel_month): print("darwing 500hPa gh plot for " + str(sel_month).zfill(2) + " " + str(sel_year)) files_cli = sorted( glob.glob( os.path.join( '/home/alley/work/Dong/mongo/seasonal_analysis/data/data/download_from_mongo/cli/', 'gh_500_*.grb'))) f_cli = xr.open_mfdataset(files_cli, concat_dim="time", combine="nested", engine="cfgrib", parallel=True) h = f_cli["z"] h = h.mean(dim="time") h_cli = h / 98 lat = f_cli["latitude"].values lon = f_cli["longitude"].values file_cur = "/home/alley/work/Dong/mongo/seasonal_analysis/data/data/download_from_mongo/cur/gh_500_" + str( sel_year) + str(sel_month).zfill(2) + ".grb" # print(file_cur) f_cur = xr.open_mfdataset(file_cur, engine="cfgrib", parallel=True) h_cur = f_cur["z"] / 98 h_ano = h_cur - h_cli leftString = "500hPa Height & Anomaly for " + str(sel_month) + str( sel_year) rightString = "dagpm" wks_type = 'png' wks = Ngl.open_wks( wks_type, '/home/alley/work/Dong/mongo/seasonal_analysis/images/gh_500hPa_' + str(sel_year) + str(sel_month).zfill(2) + '.png') res = Ngl.Resources() res.nglFrame = False res.nglDraw = False res.mpLimitMode = "LatLon" res.mpMinLonF = 60 res.mpMaxLonF = 180 res.mpMinLatF = 0 res.mpMaxLatF = 60 plot_map = Ngl.map(wks, res) fres = Ngl.Resources() fres.nglFrame = False fres.nglDraw = False fres.cnFillOn = True fres.sfXArray = lon fres.sfYArray = lat fres.lbOrientation = "Horizontal" # horizontal labelbar fres.cnLinesOn = False fres.cnLineLabelsOn = False fres.cnLevelSelectionMode = "ExplicitLevels" fres.cnFillPalette = "BlueDarkRed18" fres.cnLevels = np.arange(-5, 6, 1) plot_cn = Ngl.contour(wks, h_ano, fres) cnres = Ngl.Resources() cnres.nglDraw = False cnres.nglFrame = False cnres.cnFillOn = False cnres.cnLinesOn = True cnres.cnLineLabelsOn = True cnres.cnInfoLabelOn = False cnres.sfXArray = lon cnres.sfYArray = lat cnres.cnLevelSelectionMode = "ExplicitLevels" cnres.cnLevels = np.arange(500, 600, 4) cnres.cnLineColor = "black" cnres.cnLineThicknessF = 5 plot2 = Ngl.contour(wks, h_cur, cnres) Ngl.overlay(plot_map, plot_cn) Ngl.overlay(plot_map, plot2) # txres = Ngl.Resources() txres.txFontHeightF = 0.024 # Ngl.text_ndc(wks, leftString, 0.3, 0.83, txres) Ngl.text_ndc(wks, rightString, 0.85, 0.83, txres) # Ngl.maximize_plot(wks, plot_map) Ngl.draw(plot_map) Ngl.frame(wks) Ngl.end() print("Finish darwing 500hPa gh plot plot for " + str(sel_month).zfill(2) + " " + str(sel_year))
# Set resources for contour plot only ores = set_common_resources() 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]
cnres.mpMinLonF = 60 cnres.mpMaxLonF = 180 cnres.mpMinLatF = 0 cnres.mpMaxLatF = 60 cnres.sfXArray = lon cnres.sfYArray = lat cnres.cnLinesOn = False cnres.cnLineLabelsOn = False cnres.cnLevelSelectionMode = "ExplicitLevels" cnres.cnFillPalette = "BlueDarkRed18" cnres.cnLevels = np.arange(500, 600, 4) cn #res.cnMonoLineThickness = False cn #res.cnLineThicknesses = value cnres.cnLineThicknessF = 5 cn # res.cnInfoLabelOn=False cn #res.cnLineColor="black" plot1 = Ngl.contour_map(wks, h_cur, res) Ngl.overlay(plot1, plot) txres = Ngl.Resources() txres.txFontHeightF = 0.024 Ngl.text_ndc(wks, leftString, 0.3, 0.78, txres) Ngl.text_ndc(wks, rightString, 0.9, 0.78, txres) Ngl.frame(wks) Ngl.end() # In[ ]:
mpres.mpMaskAreaSpecifiers = mask_specs # areas to mask (protect) # # This set of resources deals with a map labelbar. # # Note that this is different from a contour labelbar # (which we will turn off below), and we have more # control over it (i.e. we can set the number of boxes, # the fill # colors, etc) than we do with a contour labelbar. # mpres.pmLabelBarDisplayMode = "Always" # Turn on a map labelbar # Labelbar resources. mpres.lbLabelStrings = ["Ocean","Land","< 0","0-10","10-20","20-30",\ "30-40","40-50","50-60","60-70","70-80", \ "80-90","90-100","> 100"] mpres.lbFillColors = mp_fill_colrs + cn_fill_clrs # Fill resources cnres.cnFillColors = cn_fill_clrs cnres.pmLabelBarDisplayMode = "Never" # turn off, b/c map has one turned on contour = Ngl.contour(wks, z[:, :], cnres) map = Ngl.map(wks, mpres) Ngl.overlay(map, contour) Ngl.draw(map) Ngl.frame(wks) Ngl.end()
vcres.vcRefMagnitudeF = 30.0 # define vector ref mag vcres.vcRefLengthF = 0.03 # define length of vec ref vcres.vcMinFracLengthF = 0.3 vcres.vcMinDistanceF = 0.02 vcres.vcRefAnnoOrthogonalPosF = -0.20 vcres.vcRefAnnoFontHeightF = 0.005 vcres.vcLineArrowThicknessF = 2.0 # create vector plot for analysis data and overlay on colour contours level 1 uv_plot1 = ngl.vector(wks, max_shear_u2_u1, max_shear_v2_v1, vcres) PWAT_plot = ngl.contour(wks, PWAT, res) ngl.overlay(LI_plot, uv_plot1) ngl.overlay(LI_plot, PWAT_plot) ngl.maximize_plot(wks, LI_plot) ngl.draw(LI_plot) ngl.frame(wks) ngl.destroy(wks) del res del LI del PWAT del vcres del u1 del v1 del u2 del v2
bres.tmXBLabelFontHeightF = 0.01 # Make these labels smaller. bres.tmXBMajorOutwardLengthF = 0.0 # Don't draw tickmarks b/c they bres.tmXBMajorLengthF = 0.0 # were drawn on previous plot. bres.tmXBLabelDeltaF = 0.6 # Move label away from tickmarks. bres.tmXBLabelFontColor = "Brown" bres.tmYROn = False # Turn off right tickmarks. bres.tmXTOn = False # Turn off top tickmarks. bres.tmYLOn = False # Turn off left tickmarks. #---Create the blank plot. blank = Ngl.blank_plot(wks, bres) #---Overlay on existing XY plot. Ngl.overlay(plot, blank) #---Drawing the original plot also draws the overlaid blank plot Ngl.draw(plot) Ngl.frame(wks) # # Second plot section. # #---Create dummy data for additional curve. npts2 = 40 y2 = numpy.zeros([npts2], 'f') for i in range(npts2): y2[i] = 3.0 - 6. * random.random()
res.tmYRLabelFont = res.tmYLLabelFont res.tmXBLabelFontHeightF = 0.015 res.tmYLLabelFontHeightF = res.tmXBLabelFontHeightF res.tmYRLabelFontHeightF = res.tmYLLabelFontHeightF if ~('res_d' in locals()): res_d = copy.deepcopy(res) res_d.xyLineColor = "red" res_d.xyDashPattern = 2 fire = np.arange(1000.) xf = np.empty(shape=len(fire), dtype=np.float64) xf[:] = fire_i plot = [] plot.append(Ngl.xy(wks, xx, vv[:, i], res)) plot.append(Ngl.xy(wks, xf, fire, res_d)) Ngl.overlay(plot[0], plot[1]) Ngl.draw(plot[0]) Ngl.frame(wks) del res Ngl.end() end_time = cpu_time() end_time = (end_time - start_time) / 60.0 print( os.path.basename(__file__) + " has done!\nTime elapsed: {:.2f}".format(end_time), "mins.")
#-- generate tplot, but don't draw it yet print("-- map --") map = Ngl.map(wks, mpres) #-- generate tplot, but don't draw it yet print("-- tplot --") tplot = Ngl.contour(wks, t, tres) #-- generate plot2, but don't draw it yet print("-- rplot --") rplot = Ngl.contour(wks, rhum, rres) #-- overlay rplot on tplot print("-- overlay tplot --") Ngl.overlay(map, tplot) print("-- overlay rplot --") Ngl.overlay(map, rplot) #-- draw the plot Ngl.draw(map) #-- write variable long_name and units to the plot txres = Ngl.Resources() txres.txFontHeightF = 0.014 Ngl.text_ndc(wks, f.variables["t"].attributes['long_name'], 0.17, 0.88, txres) Ngl.text_ndc(wks, f.variables["t"].attributes['units'], 0.95, 0.88, txres) #-- advance the frame Ngl.frame(wks)
def large_scale_prf(ptype, cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs, casedir, dofv): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = "Red" mkres.gsMarkerSizeF = 15. infiles = ["" for x in range(ncases)] ncdfs = ["" for x in range(ncases)] nregions = nsite varis = [ "CLOUD", "OMEGA", "Q", "CLDLIQ", "THETA", "RELHUM", "U", "CLDICE", "T" ] varisobs = [ "CC_ISBL", "OMEGA", "SHUM", "CLWC_ISBL", "THETA", "RELHUM", "U", "CIWC_ISBL", "T" ] nvaris = len(varis) cunits = [ "%", "mba/day", "g/kg", "g/kg", "K", "%", "m/s", "g/kg", "m/s", "m/s", "K", "m" ] cscale = [100, 864, 1000, 1000, 1., 1, 1, 1000, 1, 1, 1, 1, 1, 1, 1] cscaleobs = [100, 1, 1, 1000, 1., 1, 1, 1000, 1, 1, 1, 1, 1, 1, 1] obsdataset = [ "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI" ] plotlgs = ["" for x in range(nsite)] for ire in range(0, nsite): if not os.path.exists(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N'): os.mkdir(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N') plotname = casedir + '/' + str(lons[ire]) + 'E_' + str( lats[ire]) + 'N/Largescale_' + str(lons[ire]) + "E_" + str( lats[ire]) + "N_" + cseason plotlgs[ire] = 'Largescale_' + str(lons[ire]) + "E_" + str( lats[ire]) + "N_" + cseason wks = Ngl.open_wks(ptype, plotname) Ngl.define_colormap(wks, "GMT_paired") plot = [] res = Ngl.Resources() res.nglMaximize = False res.nglDraw = False res.nglFrame = False res.lgPerimOn = False # no box around res.vpWidthF = 0.30 # set width and height res.vpHeightF = 0.30 res.tiYAxisString = "Pressure [hPa]" res.tiMainFont = _Font res.tmYLLabelFont = _Font res.tmXBLabelFont = _Font res.tiYAxisFont = _Font res.tiXAxisFont = _Font res.tmXBLabelFontHeightF = 0.01 res.tmXBLabelFontThicknessF = 1.0 res.xyMarkLineMode = 'Lines' # res.tmXBLabelAngleF = 45 res.xyLineThicknesses = [ 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3., 3., 3., 3., 3, 3, 3, 3, 3, 3, 3 ] res.xyDashPatterns = np.arange(0, 24, 1) pres = Ngl.Resources() pres.nglFrame = False pres.txString = "Large-scale VAR at" + str(lons[ire]) + "E," + str( lats[ire]) + "N" pres.txFont = _Font pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelTop = 0.88 pres.wkPaperWidthF = 17 # in inches pres.wkPaperHeightF = 28 # in inches pres.nglMaximize = True pres.wkWidth = 10000 pres.wkHeight = 10000 for iv in range(0, nvaris): if (iv == nvaris - 1): res.pmLegendDisplayMode = "NEVER" res.xyExplicitLegendLabels = casenames[:] res.pmLegendSide = "top" res.pmLegendParallelPosF = 0.6 res.pmLegendOrthogonalPosF = -0.5 res.pmLegendWidthF = 0.10 res.pmLegendHeightF = 0.10 res.lgLabelFontHeightF = .02 res.lgLabelFontThicknessF = 1.5 res.lgPerimOn = True else: res.pmLegendDisplayMode = "NEVER" if (obsdataset[iv] == "CCCM"): if (cseason == "ANN"): fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-" + cseason + ".nc" else: fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-2010-" + cseason + ".nc" inptrobs = Dataset(fileobs, 'r') latobs = inptrobs.variables['lat'][:] latobs_idx = np.abs(latobs - lats[ire]).argmin() lonobs = inptrobs.variables['lon'][:] lonobs_idx = np.abs(lonobs - lons[ire]).argmin() B = inptrobs.variables[varisobs[iv]][:, latobs_idx, lonobs_idx] else: if (varisobs[iv] == "PRECT"): fileobs = filepathobs + '/GPCP_' + cseason + '_climo.nc' else: fileobs = filepathobs + obsdataset[ iv] + '_' + cseason + '_climo.nc' inptrobs = Dataset(fileobs, 'r') if (varisobs[iv] == "THETA"): latobs = inptrobs.variables['lat'][:] latobs_idx = np.abs(latobs - lats[ire]).argmin() lonobs = inptrobs.variables['lon'][:] lonobs_idx = np.abs(lonobs - lons[ire]).argmin() B = inptrobs.variables['T'][0, :, latobs_idx, lonobs_idx] pre1 = inptrobs.variables['lev'][:] for il1 in range(0, len(pre1)): B[il1] = B[il1] * (1000 / pre1[il1])**0.286 else: pre1 = inptrobs.variables['lev'][:] latobs = inptrobs.variables['lat'][:] latobs_idx = np.abs(latobs - lats[ire]).argmin() lonobs = inptrobs.variables['lon'][:] lonobs_idx = np.abs(lonobs - lons[ire]).argmin() B = inptrobs.variables[varisobs[iv]][0, :, latobs_idx, lonobs_idx] B[:] = B[:] * cscaleobs[iv] for im in range(0, ncases): ncdfs[im] = './data/' + cases[im] + '_site_location.nc' infiles[im] = filepath[im] + '/' + cases[ im] + '_' + cseason + '_climo.nc' inptrs = Dataset(infiles[im], 'r') # pointer to file1 lat = inptrs.variables['lat'][:] nlat = len(lat) lon = inptrs.variables['lon'][:] nlon = len(lon) lev = inptrs.variables['lev'][:] nlev = len(lev) ncdf = Dataset(ncdfs[im], 'r') n = ncdf.variables['n'][:] idx_cols = ncdf.variables['idx_cols'][:, :] if (dofv): idx_lats = ncdf.variables['idx_coord_lat'][:, :] idx_lons = ncdf.variables['idx_coord_lon'][:, :] ncdf.close() theunits = "[units]" if (im == 0): A_field = np.zeros((ncases, nlev), np.float32) for subc in range(0, n[ire]): npoint = idx_cols[ire, n[subc] - 1] - 1 if (dofv): npointlat = idx_lats[ire, 0] npointlon = idx_lons[ire, 0] if (varis[iv] == 'THETA'): if (dofv): tmp = inptrs.variables['T'][0, :, npointlat, npointlon] else: tmp = inptrs.variables['T'][0, :, npoint] hyam = inptrs.variables['hyam'][:] hybm = inptrs.variables['hybm'][:] if (dofv): ps = inptrs.variables['PS'][0, npointlat, npointlon] else: ps = inptrs.variables['PS'][0, npoint] ps = ps p0 = 100000.0 #CAM uses a hard-coded p0 pre = np.zeros((nlev), np.float32) for il in range(0, nlev): pre[il] = hyam[il] * p0 + hybm[il] * ps tmp[il] = tmp[il] * (100000 / pre[il])**0.286 theunits = str( cscale[iv]) + "x" + inptrs.variables['T'].units else: if (dofv): tmp = inptrs.variables[varis[iv]][0, :, npointlat, npointlon] else: tmp = inptrs.variables[varis[iv]][0, :, npoint] theunits = str(cscale[iv]) + "x" + inptrs.variables[ varis[iv]].units ##import pdb; pdb.set_trace() A_field[im, :] = (A_field[im, :] + tmp[:] / n[ire]).astype( np.float32) A_field[im, :] = A_field[im, :] * cscale[iv] inptrs.close() res.tiMainString = varis[iv] + " " + theunits res.trXMinF = min(np.min(A_field[0, :]), np.min(B)) res.trXMaxF = max(np.max(A_field[0, :]), np.max(B)) if (varis[iv] == "THETA"): res.trXMinF = 270. res.trXMaxF = 400. if (varis[iv] == "CLOUD" or varis[iv] == "RELHUM"): res.trXMinF = 0. res.trXMaxF = 100. if (varis[iv] == "T"): res.trXMinF = 180 res.trXMaxF = 300 if (varis[iv] == "U"): res.trXMinF = -40 res.trXMaxF = 40 res.trYReverse = True res.xyLineColors = np.arange(3, 20, 2) res.xyMarkerColors = np.arange(2, 20, 2) p = Ngl.xy(wks, A_field, lev, res) res.trYReverse = False res.xyLineColors = ["black"] pt = Ngl.xy(wks, B, pre1, res) Ngl.overlay(p, pt) plot.append(p) Ngl.panel(wks, plot[:], [nvaris / 3, 3], pres) txres = Ngl.Resources() txres.txFontHeightF = 0.02 txres.txFont = _Font Ngl.text_ndc( wks, "Large-scale VAR at" + str(lons[ire]) + "E," + str(lats[ire]) + "N", 0.5, 0.92 + ncases * 0.01, txres) Common_functions.create_legend(wks, casenames, 0.02, np.arange(3, 20, 2), 0.1, 0.89 + ncases * 0.01) Ngl.frame(wks) Ngl.destroy(wks) return plotlgs