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 plot(filename, outputend): # set up parameters f = Nio.open_file(filename) q = f.variables['q'][:, 0, :] r2d = 57.2957795 lat = f.variables['lat'][:, :]*r2d lon = f.variables['lon'][:, :]*r2d vertx = f.variables['vertx'][:, :, :]*r2d verty = f.variables['verty'][:, :, :]*r2d ncols = f.variables['nCols'][:] ae = 6.371229e6 # Open a workstation. wks_type = "pdf" rlist = Ngl.Resources() rlist.wkColorMap = "WhBlReWh" # Create contour and map resource lists. for it in range(13): wks = Ngl.open_wks(wks_type,"Moving_"+str(it)+outputend, rlist) cnres = Ngl.Resources() cnres.nglFrame = False # cnres.nglDraw = False cnres.mpGridAndLimbOn = False cnres.mpOutlineOn = False cnres.mpPerimOn = False# ; turn off box around plot cnres.nglMaximize = True cnres.mpProjection = "Orthographic" # Change the map projection. # x_c, y_c = 0, 90.#qmoving(it*24.*3600., 12.*24.*3600., 0.25*np.pi, ae) cnres.mpCenterLonF = x_c*r2d # Rotate the projection. cnres.mpCenterLatF = y_c*r2d # Rotate the projection. cnres.mpOutlineOn = False cnres.sfXArray = lon[it, 0:ncols[it]] cnres.sfYArray = lat[it, 0:ncols[it]] cnres.cnLinesOn = False cnres.cnFillOn = True cnres.cnLineLabelsOn = False cnres.cnInfoLabelOn = False cnres.lbLabelBarOn = True cnres.cnLevelSelectionMode = "ManualLevels" cnres.cnMinLevelValF = 0.4 cnres.cnMaxLevelValF = 1.6 cnres.cnLevelSpacingF = 0.05 cnres.pmTickMarkDisplayMode = "Never" contour1 = Ngl.contour_map(wks,q[it, 0:ncols[it]],cnres) gsres = Ngl.Resources() gsres.gsLineColor = "Gray25" gsres.gsLineThicknessF = 3.0 # print(vertx[0, :, 0],verty[0, :, 0]) for nc in range(ncols[it]): Ngl.polyline(wks,contour1,vertx[it, :, nc],verty[it, :, nc],gsres) # Ngl.draw(contour1) Ngl.frame(wks) Ngl.destroy(wks) Ngl.end()
def __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 draw_clubb_tau(ptype, cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs, casedir, varis, vname, cscale, chscale, pname): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = "Red" mkres.gsMarkerSizeF = 15. infiles = ["" for x in range(ncases)] ncdfs = ["" for x in range(ncases)] nregions = nsite nvaris = len(varis) plottau = ["" for x in range(nsite * ncases)] 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) ' ] for ire in range(0, nsite): for im in range(0, ncases): if not os.path.exists(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N'): os.mkdir(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N') plotname = casedir + '/' + str(lons[ire]) + 'E_' + str( lats[ire]) + 'N/' + pname + '_' + casenames[im] + "_" + str( lons[ire]) + "E_" + str(lats[ire]) + "N_" + cseason plottau[im + ncases * ire] = pname + '_' + casenames[im] + "_" + str( lons[ire]) + "E_" + str(lats[ire]) + "N_" + cseason wks = Ngl.open_wks(ptype, plotname) Ngl.define_colormap(wks, "radar") plot = [] res = Ngl.Resources() res.nglMaximize = False res.nglDraw = False res.nglFrame = False res.vpWidthF = 0.30 # set width and height res.vpHeightF = 0.30 # if (lats[ire] > 0 and lons[ire]!=240 ): # res.trYMinF = 400. # res.trYMaxF = 1000. # else: res.trYMinF = 100. 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 = "MarkLines" res.xyLineThicknesses = [ 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3., 2., 2., 2., 2, 2, 2, 2, 2, 2, 2 ] res.xyDashPatterns = np.arange(0, 24, 1) res.xyMarkers = np.arange(16, 40, 1) res.xyMarkerSizeF = 0.005 res.pmLegendDisplayMode = "Never" res.pmLegendSide = "top" # Change location of res.pmLegendParallelPosF = 0.75 # move units right res.pmLegendOrthogonalPosF = -0.65 # more neg = down res.pmLegendWidthF = 0.1 # Change width and res.pmLegendHeightF = 0.15 # height of legend. res.lgLabelFontHeightF = .02 # change font height res.lgLabelFontThicknessF = 1. # res.lgBoxMinorExtentF = 0.2 res.lgPerimOn = True res.tiYAxisString = "Pressure [hPa]" res.trYReverse = True pres = Ngl.Resources() pres.nglFrame = False pres.txFont = _Font pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelTop = 0.93 pres.txFont = _Font pres.nglMaximize = False pres.txFont = _Font pres.nglPanelTop = 0.935 pres.nglPanelFigureStrings = alphas pres.nglPanelFigureStringsJust = 'Topright' pres.nglPanelFigureStringsFontHeightF = 0.015 for iv in range(0, nvaris): if (varis[iv] == 'tau_no_N2_zm'): budget_ends = ['tau_no_N2_zm', 'bkgnd', 'sfc', 'shear'] budget_name = [ '1/~F8~t~N~~F10~~B~noN2~N~', '1/~F8~t~N~~F10~~B~bkgnd~N~', '1/~F8~t~N~~F10~~B~surf~N~', '1/~F8~t~N~~F10~~B~shear~N~' ] nterms = len(budget_ends) if (varis[iv] == 'tau_xp2_zm'): budget_ends = ['tau_xp2_zm', 'tau_no_N2_zm'] budget_name = [ "1/~F8~t~N~~F10~~B~x'~S~2~N~~N~", '1/~F8~t~N~~F10~~B~noN2~N~' ] nterms = len(budget_ends) if (varis[iv] == 'tau_wp2_zm'): budget_ends = ['tau_wp2_zm', 'tau_no_N2_zm', 'bvpos'] budget_name = [ "1/~F8~t~N~~F10~~B~w'~S~2~N~~N~", '1/~F8~t~N~~F10~~B~noN2~N~', '1/~F8~t~N~~F10~~B~bv~N~' ] nterms = len(budget_ends) if (varis[iv] == 'tau_wpxp_zm'): budget_ends = [ 'tau_wpxp_zm', 'tau_no_N2_zm', 'bvpos', 'clear' ] budget_name = [ "1/~F8~t~N~~F10~~B~w'x'~N~", "1/~F8~t~N~~F10~~B~noN2~N~", '1/~F8~t~N~~F10~~B~bv~N~', '1/~F8~t~N~~F10~~B~clr~N~' ] nterms = len(budget_ends) if (varis[iv] == 'tau_wp3_zm'): budget_ends = [ 'tau_wpxp_zm', 'tau_no_N2_zm', 'bvpos', 'clear' ] budget_name = [ "1/~F8~t~N~~F10~~B~w'x'~N~", '1/~F8~t~N~~F10~~B~noN2~N~', '1/~F8~t~N~~F10~~B~bv~N~', '1/~F8~t~N~~F10~~B~clr~N~' ] nterms = len(budget_ends) ncdfs[im] = './data/' + cases[im] + '_site_location.nc' infiles[im] = filepath[im] + cases[im] + '/' + cases[ im] + '_' + cseason + '_climo.nc' inptrs = Dataset(infiles[im], 'r') # pointer to file1 lat = inptrs.variables['lat'][:] nlat = len(lat) lon = inptrs.variables['lon'][:] nlon = len(lon) ilev = inptrs.variables['ilev'][:] nilev = len(ilev) ncdf = Dataset(ncdfs[im], 'r') n = ncdf.variables['n'][:] idx_cols = ncdf.variables['idx_cols'][:, :] ncdf.close() A_field = np.zeros((nterms, nilev), np.float32) if (varis[iv] == 'tau_no_N2_zm' or varis[iv] == 'tau_wp2_zm' or varis[iv] == 'tau_xp2_zm' or varis[iv] == 'tau_wp3_zm' or varis[iv] == 'tau_wpxp_zm'): theunits = str(chscale[iv]) + '~F10~' + inptrs.variables[ varis[iv]].units + '~S~-1~N~' else: theunits = str( chscale[iv]) + '~F10~' + inptrs.variables[varis[iv] + '_bt'].units res.tiXAxisString = '1/~F8~t~N~~F25~~B~' + vname[ iv] + "~N~ " + ' Unit= ' + theunits res1 = Ngl.Resources() res1 = res for it in range(0, nterms): for subc in range(0, n[ire]): npoint = idx_cols[ire, n[subc] - 1] - 1 if (varis[iv] == 'tau_wp2_zm' or varis[iv] == 'tau_xp2_zm' or varis[iv] == 'tau_wp3_zm' or varis[iv] == 'tau_wpxp_zm' or varis[iv] == 'tau_no_N2_zm'): varis_tau = budget_ends[it] if ( varis_tau == 'bkgnd' or varis_tau == 'shear' \ or varis_tau == 'sfc' ): tmp = inptrs.variables['invrs_tau_' + varis_tau][0, :, npoint] if (varis_tau == 'tau_no_N2_zm'): tmp = inptrs.variables[varis_tau][0, :, npoint] tmp = 1 / tmp if (varis[iv] == 'tau_wp2_zm'): if (varis_tau == 'tau_wp2_zm'): tmp = inptrs.variables[varis_tau][0, :, npoint] tmp = 1 / tmp if (varis_tau == 'bvpos'): tmp0 = inptrs.variables['tau_wp2_zm'][ 0, :, npoint] tmp1 = inptrs.variables['tau_no_N2_zm'][ 0, :, npoint] tmp = tmp0 tmp = 1 / tmp0 - 1 / tmp1 if (varis[iv] == 'tau_zm'): if (varis_tau == 'tau_zm'): tmp = inptrs.variables[varis_tau][0, :, npoint] tmp = 1 / tmp if (varis_tau == 'bvpos'): tmp0 = inptrs.variables['tau_zm'][0, :, npoint] tmp1 = inptrs.variables['tau_no_N2_zm'][ 0, :, npoint] tmp = tmp0 tmp = 1 / tmp0 - 1 / tmp1 if (varis[iv] == 'tau_xp2_zm'): if (varis_tau == 'tau_xp2_zm'): tmp = inptrs.variables[varis_tau][0, :, npoint] tmp = 1 / tmp if (varis_tau == 'Rich'): tmp0 = inptrs.variables['tau_xp2_zm'][ 0, :, npoint] tmp1 = inptrs.variables['tau_no_N2_zm'][ 0, :, npoint] tmp = tmp0 tmp = 1 / tmp0 / (1 / tmp1) / 1000 if (varis[iv] == 'tau_wp3_zm'): if (varis_tau == 'tau_wp3_zm' or varis_tau == 'tau_wpxp_zm'): tmp = inptrs.variables[varis_tau][0, :, npoint] tmp = 1 / tmp tmp[0:10] = 0 if (varis_tau == 'bvpos'): tmp0 = inptrs.variables['tau_wp2_zm'][ 0, :, npoint] tmp1 = inptrs.variables['tau_no_N2_zm'][ 0, :, npoint] tmp = tmp0 tmp = 1 / tmp0 - 1 / tmp1 if (varis_tau == 'clear'): tmp0 = inptrs.variables['tau_wp3_zm'][ 0, :, npoint] tmp1 = inptrs.variables['tau_wp2_zm'][ 0, :, npoint] tmp = tmp0 tmp = 1 / tmp0 - 1 / tmp1 tmp[0:10] = 0 if (varis[iv] == 'tau_wpxp_zm'): if (varis_tau == 'tau_wpxp_zm' or varis_tau == 'tau_zm'): tmp = inptrs.variables[varis_tau][0, :, npoint] tmp = 1 / tmp if (varis_tau == 'bvpos'): tmp0 = inptrs.variables['tau_zm'][0, :, npoint] tmp1 = inptrs.variables['tau_no_N2_zm'][ 0, :, npoint] tmp = tmp0 tmp = 2 / tmp0 - 1 / tmp1 if (varis_tau == 'clear'): tmp0 = inptrs.variables['tau_wpxp_zm'][ 0, :, npoint] tmp1 = inptrs.variables['tau_zm'][0, :, npoint] tmp = tmp0 tmp = 1 / tmp0 / 5 - 2 / tmp1 else: varis_tau = varis[iv] + budget_ends[it] tmp0 = inptrs.variables[varis[iv]][0, :, npoint] tmp = inptrs.variables[varis_tau][0, :, npoint] tmp = tmp * cscale[iv] A_field[it, :] = (A_field[it, :] + tmp[:] / n[ire]).astype(np.float32) inptrs.close() res.pmLegendDisplayMode = "Never" if (varis[iv] == 'tau_wp3_zm'): res.trXMinF = 0 res.trXMaxF = 450 res.xyMarkerColors = [ 'black', 'orange', 'purple', 'firebrick' ] res.xyLineColors = [ 'black', 'orange', 'purple', 'firebrick' ] if (varis[iv] == 'tau_no_N2_zm'): res.trXMinF = 0 res.trXMaxF = 20 res.xyMarkerColors = ['black', 'red', 'green', 'blue'] res.xyLineColors = ['black', 'red', 'green', 'blue'] if (varis[iv] == 'tau_wp2_zm'): res.trXMinF = 0 res.trXMaxF = 12 res.xyMarkerColors = ['black', 'orange', 'purple'] res.xyLineColors = ['black', 'orange', 'purple'] if (varis[iv] == 'tau_xp2_zm'): res.trXMinF = 0 res.trXMaxF = 35 res.xyMarkerColors = ['black', 'orange'] res.xyLineColors = ['black', 'orange'] p = Ngl.xy(wks, A_field, ilev, res) plot.append(p) xp = np.mod(iv, 2) yp = int(iv / 2) if (varis[iv] == 'tau_wp3_zm'): res.trXMinF = 0 res.trXMaxF = 450 res.xyMarkerColors = [ 'black', 'orange', 'purple', 'firebrick' ] res.xyLineColors = [ 'black', 'orange', 'purple', 'firebrick' ] Common_functions.create_legend( wks, budget_name[:], 0.02, ['black', 'orange', 'purple', 'firebrick'], 0.3 + xp * 0.5, 0.8 - yp * 0.5) if (varis[iv] == 'tau_no_N2_zm'): res.trXMinF = 0 res.trXMaxF = 20 res.xyMarkerColors = ['black', 'red', 'green', 'blue'] res.xyLineColors = ['black', 'red', 'green', 'blue'] Common_functions.create_legend( wks, budget_name[:], 0.02, ['black', 'red', 'green', 'blue'], 0.3 + xp * 0.5, 0.8 - yp * 0.5) if (varis[iv] == 'tau_wp2_zm'): res.trXMinF = 0 res.trXMaxF = 12 res.xyMarkerColors = ['black', 'orange', 'purple'] res.xyLineColors = ['black', 'orange', 'purple'] Common_functions.create_legend( wks, budget_name[:], 0.02, ['black', 'orange', 'purple'], 0.3 + xp * 0.5, 0.8 - yp * 0.5) if (varis[iv] == 'tau_xp2_zm'): res.trXMinF = 0 res.trXMaxF = 35 res.xyMarkerColors = ['black', 'orange'] res.xyLineColors = ['black', 'orange'] Common_functions.create_legend(wks, budget_name[:], 0.02, ['black', 'orange'], 0.3 + xp * 0.5, 0.8 - yp * 0.5) Ngl.panel(wks, plot[:], [nvaris / 2, 2], pres) txres = Ngl.Resources() txres.txFont = _Font txres.txFontHeightF = 0.020 Ngl.text_ndc( wks, casenames[im] + " BUDGET at " + str(lons[ire]) + "E," + str(lats[ire]) + "N", 0.5, 0.95, txres) Ngl.frame(wks) Ngl.destroy(wks) return (plottau)
def clubb_skw_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 = [ "C6rt_Skw_fnc", "C11_Skw_fnc", "C1_Skw_fnc", "C7_Skw_fnc", "Lscale", "Richardson_num", "Kh_zm", "tau_zm", "Skw_velocity" ] 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 = [ 1, 1, 1, 1, 1., 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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" ] plotskw = ["" 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/CLUBB_skewfunc_' + str(lons[ire]) + "E_" + str( lats[ire]) + "N_" + cseason plotskw[ire] = 'CLUBB_skewfunc_' + str(lons[ire]) + "E_" + str( lats[ire]) + "N_" + cseason wks = Ngl.open_wks(ptype, plotname) Ngl.define_colormap(wks, "GMT_paired") plot = [] res = Ngl.Resources() res.nglDraw = False res.nglFrame = False res.lgLabelFontHeightF = .012 # change font height res.lgPerimOn = False # no box around res.vpWidthF = 0.30 # set width and height res.vpHeightF = 0.30 #res.vpXF = 0.04 # res.vpYF = 0.30 res.tmYLLabelFont = _Font res.tmXBLabelFont = _Font res.tmXBLabelFontHeightF = 0.01 res.tmXBLabelFontThicknessF = 1.0 # res.tmXBLabelAngleF = 45 res.xyMarkLineMode = "Lines" res.xyLineThicknesses = [ 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3., 3., 3., 3., 3, 3, 3, 3, 3, 3, 3 ] res.xyDashPatterns = np.arange(0, 24, 1) # res.xyMarkers = np.arange(16,40,1) # res.xyMarkerSizeF = 0.005 pres = Ngl.Resources() # pres.nglMaximize = True pres.nglFrame = False pres.txFont = _Font pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelTop = 0.88 pres.wkWidth = 2500 pres.wkHeight = 2500 for iv in range(0, nvaris): if (iv == nvaris - 1): res.pmLegendDisplayMode = "NEVER" res.xyExplicitLegendLabels = casenames[:] res.pmLegendSide = "top" res.pmLegendParallelPosF = 0.6 res.pmLegendOrthogonalPosF = -0.5 res.pmLegendWidthF = 0.10 res.pmLegendHeightF = 0.10 res.lgLabelFontHeightF = .02 res.lgLabelFontThicknessF = 1.5 res.lgPerimOn = False else: res.pmLegendDisplayMode = "NEVER" # 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') # B=inptrobs.variables[varisobs[iv]][:,(lats[ire]),(lons[ire])] # 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"): # B = inptrobs.variables['T'][0,:,(lats[ire]),(lons[ire])] # 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'][:] # B = inptrobs.variables[varisobs[iv]][0,:,(lats[ire]),(lons[ire])] # # 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['ilev'][:] 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() 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 (dofv): tmp = inptrs.variables[varis[iv]][0, :, npointlat, npointlon] 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() res.tiMainString = varis[iv] + " " + theunits # res.trXMinF = min(np.min(A_field[0, :])) # res.trXMaxF = max(np.max(A_field[0, :])) res.trYReverse = True res.xyLineColors = np.arange(3, 20, 2) res.xyMarkerColors = np.arange(2, 20, 2) p = Ngl.xy(wks, A_field, lev, res) # res.trYReverse = False # res.xyLineColors = ["black"] # pt = Ngl.xy(wks,B,pre1,res) # Ngl.overlay(p,pt) plot.append(p) pres.txString = "Skewness Functions at" + str(lons[ire]) + "E," + str( lats[ire]) + "N" txres = Ngl.Resources() txres.txFontHeightF = 0.020 txres.txFont = _Font Ngl.text_ndc( wks, "Skewness Functions 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.panel(wks, plot[:], [nvaris / 3, 3], pres) Ngl.frame(wks) Ngl.destroy(wks) return plotskw
# # 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()
def plot_rain_around_point(path, data_rain_tot_sum, hour_start, hour_end, point, stat_processing, member): if stat_processing == 'max': data_processed = (data_rain_tot_sum[hour_end, :, :] - data_rain_tot_sum[hour_start, :, :]).max(axis=0) elif stat_processing == 'member_extract': data_processed = data_rain_tot_sum[hour_end, member-1, :] - data_rain_tot_sum[hour_start, member-1, :] ######################################################################## if stat_processing == 'max': member_text_filename = 'max' elif stat_processing == 'member_extract': member_text_filename = 'm{:02d}'.format(member) plot_name = 'iconeueps_rain_{}_{:02d}Z-{:02d}Z_{}'.format(\ point['name'], hour_start+12, hour_end+12, member_text_filename) mpi_file = nc.Dataset(path['base'] + path['grid'] + 'icon_grid_0028_R02B07_N02.nc', 'r') vlat = mpi_file.variables['clat_vertices'][:].data * 180./np.pi vlon = mpi_file.variables['clon_vertices'][:].data * 180./np.pi clat = mpi_file.variables['clat'][:].data * 180./np.pi clon = mpi_file.variables['clon'][:].data * 180./np.pi mpi_file.close() ######################################################################## x_resolution = 800 y_resolution = 800 wks_res = Ngl.Resources() wks_res.wkWidth = x_resolution wks_res.wkHeight = y_resolution wks_type = 'png' wks = Ngl.open_wks(wks_type, path['base'] + path['plots'] + plot_name, wks_res) resources = Ngl.Resources() resources.mpProjection = 'Hammer' resources.mpCenterLonF = point['lon'] resources.mpCenterLatF = point['lat'] radius = 500 # image radius in km around centered point cutout_plot = dict( lat_min = point['lat'] - radius / 111.2, lat_max = point['lat'] + radius / 111.2, lon_min = point['lon'] - radius / (111.2 * np.cos(point['lat']*np.pi/180)), lon_max = point['lon'] + radius / (111.2 * np.cos(point['lat']*np.pi/180)), ) resources.mpLimitMode = 'latlon' resources.mpMinLonF = cutout_plot['lon_min'] resources.mpMaxLonF = cutout_plot['lon_max'] resources.mpMinLatF = cutout_plot['lat_min'] resources.mpMaxLatF = cutout_plot['lat_max'] resources.nglMaximize = False resources.vpXF = 0.05 resources.vpYF = 0.95 resources.vpWidthF = 0.7 resources.vpHeightF = 0.7 ######################################################################## # Turn on filled map areas: resources.mpFillOn = True # Set colors for [FillValue, Ocean, Land , InlandWater]: resources.mpFillColors = ['pink','blue','white','blue'] resources.mpDataBaseVersion = 'MediumRes' resources.mpDataSetName = 'Earth..4' resources.mpOutlineBoundarySets = 'national' resources.mpGeophysicalLineThicknessF = 7.0 * x_resolution / 1000 resources.mpNationalLineThicknessF = 7.0 * x_resolution / 1000 #resources.mpGridAndLimbDrawOrder = 'postdraw' resources.mpGridAndLimbOn = False #resources.mpLimbLineColor = 'black' #resources.mpLimbLineThicknessF = 10 #resources.mpGridLineColor = 'black' #resources.mpGridLineThicknessF = 1.0 #resources.mpGridSpacingF = 1 resources.mpPerimOn = True resources.mpPerimLineColor = 'black' resources.mpPerimLineThicknessF = 8.0 * x_resolution / 1000 resources.tmXBOn = False resources.tmXTOn = False resources.tmYLOn = False resources.tmYROn = False resources.sfDataArray = data_processed resources.sfXArray = clon resources.sfYArray = clat resources.sfXCellBounds = vlon resources.sfYCellBounds = vlat resources.sfMissingValueV = 9999 resources.cnFillOn = True resources.cnFillMode = 'CellFill' resources.cnCellFillEdgeColor = 'black' resources.cnMissingValFillColor = 'black' resources.cnFillPalette = 'WhiteBlueGreenYellowRed' resources.cnLevelSelectionMode = 'ManualLevels' minlevel = 0.0 maxlevel = 50.0 numberoflevels = 250 resources.cnMinLevelValF = minlevel resources.cnMaxLevelValF = maxlevel resources.cnLevelSpacingF = (maxlevel - minlevel) / numberoflevels # Turn off contour lines and labels: resources.cnLinesOn = False resources.cnLineLabelsOn = False # Set resources for a nice label bar resources.lbLabelBarOn = True resources.lbAutoManage = False resources.lbOrientation = 'vertical' resources.lbLabelOffsetF = 0.05 #resources.lbBoxMinorExtentF = 0.2 resources.lbLabelStride = 25 resources.lbLabelFontHeightF = 0.02 resources.lbBoxSeparatorLinesOn = False resources.lbBoxLineThicknessF = 4.0 #resources.lbBoxEndCapStyle = 'TriangleBothEnds' resources.lbLabelAlignment = 'BoxCenters' resources.lbTitleString = 'mm' resources.lbTitleFontHeightF = 0.02 resources.lbTitlePosition = 'Right' resources.lbTitleDirection = 'Across' resources.lbTitleAngleF = 90.0 resources.lbTitleExtentF = 0.1 resources.lbTitleOffsetF = 0.0 resources.nglFrame = False plot = Ngl.contour_map(wks, data_processed, resources) ######################################################################## polymarker_res_1 = Ngl.Resources() polymarker_res_1.gsMarkerColor = 'black' polymarker_res_1.gsMarkerIndex = 16 polymarker_res_1.gsMarkerSizeF = 0.012 polymarker_res_1.gsMarkerThicknessF = 1 Ngl.polymarker(wks, plot, point['lon'], point['lat'], polymarker_res_1) ######################################################################## polymarker_res_2 = Ngl.Resources() polymarker_res_2.gsMarkerColor = 'white' polymarker_res_2.gsMarkerIndex = 16 polymarker_res_2.gsMarkerSizeF = 0.008 polymarker_res_2.gsMarkerThicknessF = 1 Ngl.polymarker(wks, plot, point['lon'], point['lat'], polymarker_res_2) ######################################################################## if stat_processing == 'max': member_text = 'max member of each cell' elif stat_processing == 'member_extract': member_text = 'member {:d}'.format(member) text = 'rain_gsp + rain_con, 07.08.19 {}Z-{}Z, {}'.format(hour_start+12, hour_end+12, member_text) x = 0.1 y = 0.95 text_res_1 = Ngl.Resources() text_res_1.txFontHeightF = 0.02 text_res_1.txJust = 'BottomLeft' Ngl.text_ndc(wks, text, x, y, text_res_1) Ngl.frame(wks) Ngl.destroy(wks) return
def rain_prf (ptype,cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs,casedir,varis,cscale,chscale,pname): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = 'Red' mkres.gsMarkerSizeF = 15. infiles = ['' for x in range(ncases)] ncdfs = ['' for x in range(ncases)] nregions = nsite varisobs = ['CC_ISBL', 'OMEGA','SHUM','CLWC_ISBL', 'THETA','RELHUM','U','CIWC_ISBL','T' ] nvaris = len(varis) cunits = ['%','mba/day','g/kg','g/kg','K', '%', 'm/s', 'g/kg', 'm/s', 'm/s','K','m' ] cscaleobs = [100, 1, 1, 1000 , 1., 1, 1, 1000, 1,1,1,1,1,1,1] obsdataset =['ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI','ERAI','ERAI'] plotrain=['' for x in range(nsite)] for ire in range (0, nsite): if not os.path.exists(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N'): os.mkdir(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N') plotname = casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N/'+pname+'_'+str(lons[ire])+'E_'+str(lats[ire])+'N_'+cseason plotrain[ire] = pname+'_'+str(lons[ire])+'E_'+str(lats[ire])+'N_'+cseason wks= Ngl.open_wks(ptype,plotname) Ngl.define_colormap(wks,'GMT_paired') plot = [] res = Ngl.Resources() res.nglDraw = False res.nglFrame = False res.lgLabelFontHeightF = .02 # change font height res.lgPerimOn = False # no box around res.vpWidthF = 0.30 # set width and height res.vpHeightF = 0.30 #res.vpXF = 0.04 # res.vpYF = 0.30 res.tmYLLabelFont = _Font res.tmXBLabelFont = _Font res.tiMainFont = _Font res.tmXBLabelFontHeightF = 0.015 res.tmXBLabelFontThicknessF = 1.0 # res.tmXBLabelAngleF = 45 res.xyMarkLineMode = 'Lines' res.xyLineThicknesses = [3.0, 3.0, 3.0, 3.0, 3.0, 3.0,3.,3.,3.,3.,3,3,3,3,3,3,3] res.xyDashPatterns = np.arange(0,24,1) # res.xyMarkers = np.arange(16,40,1) # res.xyMarkerSizeF = 0.005 pres = Ngl.Resources() # pres.nglMaximize = True pres.nglFrame = False pres.txFont = _Font pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelTop = 0.88 pres.wkWidth = 2500 pres.wkHeight = 2500 for iv in range (0, nvaris): if(iv == nvaris-1): res.pmLegendDisplayMode = 'Never' res.xyExplicitLegendLabels = casenames[:] res.pmLegendSide = 'top' res.pmLegendParallelPosF = 0.6 res.pmLegendOrthogonalPosF = -0.5 res.pmLegendWidthF = 0.10 res.pmLegendHeightF = 0.10 res.lgLabelFontHeightF = .02 res.lgLabelFontThicknessF = 1.5 res.lgPerimOn = False else: res.pmLegendDisplayMode = 'NEVER' for im in range (0,ncases): ncdfs[im] = './data/'+cases[im]+'_site_location.nc' infiles[im]= filepath[im]+cases[im]+'/'+cases[im]+'_'+cseason+'_climo.nc' inptrs = Dataset(infiles[im],'r') # pointer to file1 lat=inptrs.variables['lat'][:] nlat=len(lat) lon=inptrs.variables['lon'][:] nlon=len(lon) lev=inptrs.variables['lev'][:] nlev=len(lev) ncdf= Dataset(ncdfs[im],'r') n =ncdf.variables['n'][:] idx_cols=ncdf.variables['idx_cols'][:,:] ncdf.close() if (im ==0): A_field = np.zeros((ncases,nlev),np.float32) for subc in range( 0, n[ire]): npoint=idx_cols[ire,n[subc]-1]-1 tmp=inptrs.variables[varis[iv]][0,:,npoint] theunits=str(chscale[iv])+'x'+inptrs.variables[varis[iv]].units A_field[im,:] = (A_field[im,:]+tmp[:]/n[ire]).astype(np.float32 ) A_field[im,:] = A_field[im,:] *cscale[iv] inptrs.close() res.tiMainString = varis[iv]+' '+theunits # res.trXMinF = min(np.min(A_field[0, :])) # res.trXMaxF = max(np.max(A_field[0, :])) res.trYReverse = True res.xyLineColors = np.arange(3,20,2) res.xyMarkerColors = np.arange(2,20,2) p = Ngl.xy(wks,A_field,lev,res) # res.trYReverse = False # res.xyLineColors = ['black'] # pt = Ngl.xy(wks,B,pre1,res) # Ngl.overlay(p,pt) plot.append(p) pres.txString = pname+' at'+ str(lons[ire])+'E,'+str(lats[ire])+'N' txres = Ngl.Resources() txres.txFontHeightF = 0.020 txres.txFont = _Font Ngl.text_ndc(wks,pname+' at'+ str(lons[ire])+'E,'+str(lats[ire])+'N',0.5,0.92+ncases*0.01,txres) Common_functions.create_legend(wks,casenames,np.arange(3,20,2),0.1,0.89+ncases*0.01) Ngl.panel(wks,plot[:],[nvaris/2,2],pres) Ngl.frame(wks) Ngl.destroy(wks) return plotrain
# Set up info for box. width = 0.07 # Box width height = 0.05 # Box height # Set coordinates for top left corner of the eight boxes. xpos = [0.20,0.40,0.60,0.80,0.20, 0.40, 0.60, 0.80] ypos = [0.13,0.13,0.13,0.13,0.055,0.055,0.055,0.055] # Text resources. txres = Ngl.Resources() txres.txFontHeightF = 0.015 # Decrease size of font txres.txJust = "CenterLeft" # Left justify nboxes = len(xpos) for i in xrange(nboxes): xp = xpos[i] yp = ypos[i] xbox = [xp,xp+width,xp+width,xp,xp] ybox = [yp,yp,yp-height,yp-height,yp] gsres.gsFillColor = colors[i+2] Ngl.polygon_ndc(wks,xbox,ybox,gsres) # Fill the box Ngl.polyline_ndc(wks,xbox,ybox) # Outline the box Ngl.text_ndc(wks,labels[i],xp+width+0.005,yp-height/2.,txres) Ngl.frame(wks) # Now advance the frame. Ngl.end()
def histogram(wks, data, res): """Plot a histogram. The NumPy histogram function is used to define the histogram. Arguments: wks -- Ngl wrokstation. data -- 1D array of data to construct a histogram from. res -- Ngl resources variable. Valid resources are: """ # Define a function to compute bar locations. def bar_position(x, y, dx, ymin, bar_width_perc): """Compute the coordinates required to draw a specified bar.""" dxp = dx * bar_width_perc xbar = np.array([x, x+dxp, x+dxp, x, x]) ybar = np.array([ymin, ymin, y, y, ymin]) return xbar, ybar # Make a local copy of resources so they can be modified. res = copy(res) # Intercept and turn off draw and frame resources. These will be applied # if necessary once the histogram has been constructed. frame_on = getattr(res, 'nglFrame', True) draw_on = getattr(res, 'nglDraw', True) res.nglFrame = False res.nglDraw = False # Set default values of special resources that will not be recognised by # Ngl. resdefaults = { 'nglHistogramBarWidthPercent': 1., 'nglHistogramBinIntervals': None, 'nglHistogramNumberOfBins': 10, 'nglxHistogramRange': None, 'nglxHistogramBarColor': 0, 'nglxHistogramBarOutlineColor': 1, 'nglxHistogramDensity': True, } # Record the values of the special resources, and remove them from the # resource list. specialres = dict() for resname in resdefaults.keys(): specialres[resname] = getattr(res, resname, resdefaults[resname]) try: delattr(res, resname) except AttributeError: pass # Work out the values of histogram parameters. nbins = specialres['nglHistogramBinIntervals'] or \ specialres['nglHistogramNumberOfBins'] hrange = specialres['nglxHistogramRange'] density = specialres['nglxHistogramDensity'] # Compute the histogram with the NumPy routine. hist, binedges = np.histogram(data, bins=nbins, range=hrange, density=density) dx = binedges[1] - binedges[0] ymin = 0. # Draw up to three bars, the first and last and the tallest, if they are # different. This sets up the plot correctly. The user specified plotting # resources are respected during this process. The lines drawn here will # be covered by the histogram. xdum, ydum = list(), list() xbar, ybar = bar_position(binedges[0], hist[0], dx, ymin, # first bar specialres['nglHistogramBarWidthPercent']) xdum.append(xbar) ydum.append(ybar) if nbins > 1: xbar, ybar = bar_position(binedges[-2], hist[-1], dx, ymin, # last bar specialres['nglHistogramBarWidthPercent']) xdum.append(xbar) ydum.append(ybar) i = np.argmax(hist) if i not in (0, nbins-1): xbar, ybar = bar_position(binedges[i], hist[i], dx, ymin, # tallest bar specialres['nglHistogramBarWidthPercent']) xdum.append(xbar) ydum.append(ybar) plot = xy(wks, np.array(xdum), np.array(ydum), res) # Create resources for shading the bars and drawing outlines around them. fillres = Ngl.Resources() fillres.gsFillColor = specialres['nglxHistogramBarColor'] lineres = Ngl.Resources() lineres.gsLineColor = specialres['nglxHistogramBarOutlineColor'] # Draw the bars and their outlines. plot._histbars = list() plot._histlines = list() for bar in xrange(nbins): xbar, ybar = bar_position(binedges[bar], hist[bar], dx, ymin, specialres['nglHistogramBarWidthPercent']) plot._histbars.append(Ngl.add_polygon(wks, plot, xbar, ybar, fillres)) plot._histlines.append(Ngl.add_polyline(wks, plot, xbar, ybar, lineres)) # Apply drawing and frame advancing if they were specified in the input # resources. if draw_on: Ngl.draw(plot) if frame_on: Ngl.frame(plot) # Return a plot identifier. return plot
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)
def __call__(self, wks, plots, dims, res=None): """Panel a collection of plots. Arguments: wks -- An Ngl workstation to plot onto. plots -- A collection of plots to put together into a panel plot. dims -- Dimensions of the panel plot. It should be specified as (rows, cols) or, if the panel resource 'nglPanelRowSpec' is set to True, as (cols0, cols1, cols2) where each entry is a row and its value specifies the number of columns in the row. res -- An Ngl resources object. The following resources are understood: 'nglPanelRowSpec' 'nglPanelCenter' 'nglPanelScalePlotIndex' 'nglPanelTop' 'nglPanelLeft' 'nglPanelRight' 'nglPanelXF' 'nglPanelYF' 'nglPanelXWhiteSpacePercent' 'nglPanelYWhiteSpacePercent' 'nglPanelTitleString' 'nglPanelTitleFont' 'nglPanelTitleFontheightF' 'nglPanelTitleFontColor' 'nglPanelTitleOffsetXF' 'nglPanelTitleOffsetYF' 'nglPanelFigureStrings' X not implemented 'nglPanelLabelBar' X not implemented 'nglPanelDebug' """ # Get the unified panel specification. These details can be used to # produce the panel plot independently of the user's choice of panel # specification format. self.number_rows, self.number_columns, self.row_spec, \ self.number_panels = self._get_panel_spec(dims, res) # Get the number of plots that can actually be plotted. We cannot plot # more plots than panels that are defined. self.number_plots = self._get_number_plots(plots) # Retrieve the width and height of the plots from the plot objects. # Only one plot is considered and the others assumed to be the same # size. Unless otherwise specified, the plot this information comes # from will be the first plot. self.plot_width, self.plot_height = \ self._get_plot_dimensions(plots, res) # Compute the space to be left between plots. This consists of a base # size plus an offset. The offset can be user specified via the # resources variable. self.delta_x, self.delta_y = self._get_plot_spacing(res) # Compute the total width of the panel plot. self.total_width = self.number_columns * self.plot_width + \ (self.number_columns - 1) * self.delta_x # Compute the top and left coordinates of the panel plot. self.panel_x0, self.panel_center_x = self._get_panel_xcoord(res) self.panel_y0 = self._get_panel_ycoord(res) # Work out where to draw each of the plots. self.plot_coordinates = self._get_plot_coords(res) # Draw each plot on the workstation. self._draw_plots(plots, res) # Draw panel labels if required. self._draw_panel_labels(wks, res) # Draw a main title if required. self._draw_main_title(wks, res) # Finish the panelling by advancing the frame unless requested not to. if getattr(res, 'nglPanelFrame', True): Ngl.frame(wks)
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_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)
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_psiyr(wks,data,vx,vy,xlab='Latitude [deg N]',ylab = 'y',\ vsurf=[],hei=0.1,ylon=True,xon=False,lbar=False,flipy=False,\ vpx=0.15,vpy=0.8,lsmooth=False): """ Plots meridional overturning stream functions Usage: plot_psiyr(wks,data,vx,vy,xlab='Latitude',ylab='y',vsurf=np.array([]),\ hei=0.15,ylon=True,xon=True,lbar=True,flipy=False) Input: wks - Workstation ID data - 2D matrix. Can be several matrices in a list vx - Latitude vector vy - y-vector. Can be several in a list Optional: xlab - Title for x-axis ylab - Title for y-axis vsurf - Vector of surface values to draw in hei - Height of plot(s) ylon - Turn on y labels on left side (else right) xon - Turn on x labels on bottom lbar - Turn on colorbar Output: None """ ## res = Ngl.Resources() res.wkColorMap = 'ViBlGrWhYeOrRe' Ngl.set_values(wks,res) print ' Plotting overturning stream functions in (y,r) coordinates' print lbar if ( isinstance(data,list) ): nplots = len(data) else: nplots = 1 data = [data] vy = fill_blanks(vy,nplots) ylab = fill_blanks(ylab,nplots) vsurf = fill_blanks(vsurf,nplots) ylon = fill_blanks(ylon,nplots) xon = fill_blanks(xon,nplots) lbar = fill_blanks(lbar,nplots) lbar[0] = True flipy = fill_blanks(flipy,nplots) hei = max([0.8/(nplots+1),hei]) wth = min([0.7,hei * 4]) vpy = 0.9 - hei * np.arange(0,nplots+1) ## ## Color levels for y-r stream functions ## colour_levels = np.arange(-190,210,20) for jn in range(0,nplots): zplot = data[jn] 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 = colour_levels res.sfXArray = vx res.sfYArray = vy[jn] res.vpXF = vpx res.vpWidthF = wth res.vpYF = vpy[jn] res.vpHeightF = hei ## ## Axis ## res.tiYAxisFontHeightF = 0.012 res.tiYAxisString = ylab[jn] res.tiXAxisString = xlab if( ylon[jn] == True ): res.tiYAxisSide = 'Left' res.tmYLLabelsOn = True res.tmYRLabelsOn = False res.tmYLLabelFontHeightF = 0.012 else: res.tiYAxisSide = 'Right' res.tmYLLabelsOn = False res.tmYRLabelsOn = True res.tmYRLabelFontHeightF = 0.012 if( xon[jn] == True ): res.tiXAxisOn = True res.tmXBLabelsOn = True res.tiXAxisFontHeightF = 0.012 res.tmXBLabelFontHeightF = 0.012 else: res.tiXAxisOn = False res.tmXBLabelsOn = False ## ## Labelbar ## if( lbar[jn] == True ): res.lbTitleString = 'Sverdrup (10~S~9~N~kg/s)' res.lbLabelFontHeightF = 0.012 res.lbTitleFontHeightF = 0.015 res.lbLabelBarOn = True res.lbOrientation = 'Horizontal' res.pmLabelBarSide = 'Top' res.pmLabelBarDisplayMode = 'Always' res.pmLabelBarWidthF = 0.65 res.pmLabelBarHeightF = 0.07 else: res.lbLabelBarOn = False ## ## Flip y axis? ## if( flipy[jn] == True ): res.trYReverse = True else: res.trYReverse = False ## Smooth if (lsmooth==True): sigma = 2 order = 0 for ji in range(0,5): ndimage.filters.gaussian_filter(zplot[:,:],sigma,order=order,\ output=zplot[:,:],\ mode='reflect', cval=0.0) cont = Ngl.contour(wks,zplot,res) ## ## Also draw the surface values ## if (vsurf[jn].shape[0] == vx.shape[0]): lres = Ngl.Resources() lres.gsLineThicknessF = 1.5 lres.gsLineColor = 'black' lres.gsLineDashPattern = 1 line = Ngl.add_polyline(wks,cont,vx,vsurf[jn],lres) else: print ' Length of vx and vsurf do not agree ' ## And show the max/min values zmax = np.max( zplot.flatten() ) zmin = np.min( zplot.flatten() ) max_point = np.where(zplot == zmax) min_point = np.where(zplot == zmin) lmax = vx[max_point[1]][0] ymax = vy[jn][max_point[0]][0] print ' psimax = '+repr(zmax) print ' at lat = '+repr(lmax)+', y = '+repr(ymax) lmin = vx[min_point[1]][0] ymin = vy[jn][min_point[0]][0] print ' psimin = '+repr(zmin) print ' at lat = '+repr(lmin)+', y = '+repr(ymin) pres = Ngl.Resources() pres.gsMarkerColor = 'black' pres.gsMarkerThicknessF = 3. mark = Ngl.add_polymarker(wks,cont,lmax,ymax,pres) mark = Ngl.add_polymarker(wks,cont,lmin,ymin,pres) Ngl.draw(cont) #Ngl.frame(wks) flux_label = ['LH flux [PW]',\ 'DSE flux [PW]',\ 'MSE flux [PW]',\ 'Volume flux [m3/s]', 'Pressure flux [hPa]',\ 'Sensible heat flux [PW]'] jj = 0 if(1): vy2 = np.zeros((nplots,vx.shape[0])) for jc in range(0,nplots): zplot = data[jc][:,:] chi = 0.5 * (vy[jc][1:] + vy[jc][:-1]) for jj in range(0,vx.shape[0]): dpsi = zplot[1:,jj] - zplot[:-1,jj] vy2[jc,jj] = np.sum(dpsi * chi) vy2 = 10**(-3) * (-1) * vy2[:,:] # W->PW and change sign linecolors = ['blue','red','black','green','yellow','purple'] del res res = Ngl.Resources() res.nglMaximize = False res.nglPaperOrientation = 'Portrait' res.nglFrame = False res.nglDraw = True res.xyLineColors = linecolors #res.xyLineThicknesses = [2,2,2] #res.xyLabelMode = 'Custom' #res.xyExplicitLabels = ['LH','DSE','MSE'] # #if( np.mod(jc,2) == 0): # res.tiYAxisSide = 'Left' # res.tmYLLabelsOn = True # res.tmYRLabelsOn = False #else: # res.tiYAxisSide = 'Right' # res.tmYLLabelsOn = False # res.tmYRLabelsOn = True # #if( jc == icoord-1): # res.tiXAxisOn = True # res.tmXBLabelsOn = True #else: # res.tiXAxisOn = False # res.tmXBLabelsOn = False ## Axis res.tiXAxisString = 'Latitude' res.tiYAxisString = '[PW]' res.tiXAxisFontHeightF = 0.012 res.tiYAxisFontHeightF = 0.012 res.tmXBLabelFontHeightF = 0.012 res.tmYLLabelFontHeightF = 0.012 res.trYMaxF = 6. res.trYMinF = -6. res.vpXF = vpx res.vpWidthF = wth res.vpYF = vpy[-1] res.vpHeightF = hei cont = Ngl.xy(wks,vx,vy2[0:3],res) Ngl.frame(wks)
def plot_psirr(wks, zplot, vx, vy, xlab = 'x', ylab = 'y', vpx=0.2, vpy=0.8, \ hei=0.4, cc='dse',lsmooth=False, frame=True): """ """ ## ## Colors for hydrothermal stream functions ## ld = 450. dl = 60 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) ## ## Positions of four subplots ## print ' Plotting stream functions in (r,r) coordinates' if(1): if(1): #vu = np.zeros(zplot[-1,:,:].shape) #vv = np.zeros(zplot[-1,:,:].shape) #vu[1:,:] = zplot[-1,0:-1,:] - zplot[-1,1:,:] #vv[:,1:] = zplot[-1,:,1:] - zplot[-1,:,0:-1] title = 'psi('+xlab+','+ylab+')' print ' Amplitude, max. err : '+repr(np.max(np.abs(zplot[:,:]))),\ repr(np.max(np.abs(zplot[:,-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 res.pmLabelBarSide = 'Right' res.lbLabelBarOn = True res.lbOrientation = 'Vertical' res.pmLabelBarDisplayMode = 'Always' res.pmLabelBarWidthF = 0.03 res.pmLabelBarHeightF = hei res.lbTitleString = 'Sv (10~S~9~N~kg/s)' res.lbLabelFontHeightF = 0.01 res.lbTitleFontHeightF = 0.01 res.sfXArray = vx res.sfYArray = vy res.tiXAxisString = xlab res.tiYAxisString = ylab res.vpWidthF = hei res.vpHeightF = hei res.vpYF = vpy res.vpXF = vpx 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) wks,cont = plot_cc(wks,cont,x='lh',y=cc) Ngl.draw(cont) if(frame): Ngl.frame(wks)
line_res.gsLineDashPattern = 2 # dashed lines Ngl.polyline(wks, plot, lon2d[::4, 0], lat2d[::4, 0], line_res) Ngl.polyline(wks, plot, lon2d[::4, -1], lat2d[::4, -1], line_res) # # Add a text string explaining the lines. # text_res = Ngl.Resources() # text resources text_res.txFontHeightF = 0.03 # font height text_res.txFontColor = "Red" Ngl.text_ndc(wks, "dashed red line shows area with no data", 0.5, 0.17, text_res) Ngl.frame(wks) # Now advance frame. # # Add cyclic points. Since lat2d/lon2d are 2D arrays, make them # cyclic the same way you do the 2D data array. # u = Ngl.add_cyclic(urot[::4, ::4]) v = Ngl.add_cyclic(vrot[::4, ::4]) lon = Ngl.add_cyclic(lon2d[::4, ::4]) lat = Ngl.add_cyclic(lat2d[::4, ::4]) # # Specify new coordinate arrays for data. # resources.vfXArray = lon resources.vfYArray = lat
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_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 main(): import numpy import Ngl options = parse_input() u_array2, v_array2, s_array2, x_min, x_max, y_min, y_max = read_data(options) wks_type = 'ps' wks = Ngl.open_wks(wks_type, options.data) color_res = Ngl.Resources() gs_res = Ngl.Resources() text_res = Ngl.Resources() rgb_min = [] for s in options.rgb_min.split(): rgb_min.append(float(s)) rgb_max = [] for s in options.rgb_max.split(): rgb_max.append(float(s)) l = [] l.append([1.00, 1.00, 1.00]) l.append([0.00, 0.00, 0.00]) f_l = [] n = 100 for f in range(n): f_l.append(float((f + 1) * (1.0 / n))) for f in f_l: r = rgb_min[0] + f * (rgb_max[0] - rgb_min[0]) g = rgb_min[1] + f * (rgb_max[1] - rgb_min[1]) b = rgb_min[2] + f * (rgb_max[2] - rgb_min[2]) l.append([r, g, b]) rgb_map = numpy.array(l, 'f') color_res.wkColorMap = rgb_map Ngl.set_values(wks, color_res) vector_res = get_vector_res(options, x_min, x_max, y_min, y_max) plot = Ngl.vector_scalar(wks, u_array2, v_array2, s_array2, vector_res) color_res.wkColorMap = "default" Ngl.set_values(wks, color_res) line_thickness = 2.0 gs_res.gsMarkerSizeF = 10.0 gs_res.gsMarkerThicknessF = 2.0 gs_res.gsLineDashPattern = 2 gs_res.gsLineThicknessF = line_thickness text_res.txFont = 21 text_res.txFontHeightF = 0.015 text_res.txFontColor = options.text_color for atom in read_molecule(options): gs_res.gsMarkerIndex = 16 gs_res.gsMarkerColor = "White" Ngl.polymarker(wks, plot, [atom[2]], [atom[1]], gs_res) gs_res.gsMarkerIndex = 4 gs_res.gsMarkerColor = options.text_color Ngl.polymarker(wks, plot, [atom[2]], [atom[1]], gs_res) Ngl.text(wks, plot, atom[0], [atom[2] + 1.0], [atom[1]], text_res) Ngl.frame(wks) del plot Ngl.end()
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()
def draw_gh_500hPa(sel_year, sel_month): print("darwing 500hPa gh plot for " + str(sel_month).zfill(2) + " " + str(sel_year)) files_cli = sorted( glob.glob( os.path.join( '/home/alley/work/Dong/mongo/seasonal_analysis/data/data/download_from_mongo/cli/', 'gh_500_*.grb'))) f_cli = xr.open_mfdataset(files_cli, concat_dim="time", combine="nested", engine="cfgrib", parallel=True) h = f_cli["z"] h = h.mean(dim="time") h_cli = h / 98 lat = f_cli["latitude"].values lon = f_cli["longitude"].values file_cur = "/home/alley/work/Dong/mongo/seasonal_analysis/data/data/download_from_mongo/cur/gh_500_" + str( sel_year) + str(sel_month).zfill(2) + ".grb" # print(file_cur) f_cur = xr.open_mfdataset(file_cur, engine="cfgrib", parallel=True) h_cur = f_cur["z"] / 98 h_ano = h_cur - h_cli leftString = "500hPa Height & Anomaly for " + str(sel_month) + str( sel_year) rightString = "dagpm" wks_type = 'png' wks = Ngl.open_wks( wks_type, '/home/alley/work/Dong/mongo/seasonal_analysis/images/gh_500hPa_' + str(sel_year) + str(sel_month).zfill(2) + '.png') res = Ngl.Resources() res.nglFrame = False res.nglDraw = False res.mpLimitMode = "LatLon" res.mpMinLonF = 60 res.mpMaxLonF = 180 res.mpMinLatF = 0 res.mpMaxLatF = 60 plot_map = Ngl.map(wks, res) fres = Ngl.Resources() fres.nglFrame = False fres.nglDraw = False fres.cnFillOn = True fres.sfXArray = lon fres.sfYArray = lat fres.lbOrientation = "Horizontal" # horizontal labelbar fres.cnLinesOn = False fres.cnLineLabelsOn = False fres.cnLevelSelectionMode = "ExplicitLevels" fres.cnFillPalette = "BlueDarkRed18" fres.cnLevels = np.arange(-5, 6, 1) plot_cn = Ngl.contour(wks, h_ano, fres) cnres = Ngl.Resources() cnres.nglDraw = False cnres.nglFrame = False cnres.cnFillOn = False cnres.cnLinesOn = True cnres.cnLineLabelsOn = True cnres.cnInfoLabelOn = False cnres.sfXArray = lon cnres.sfYArray = lat cnres.cnLevelSelectionMode = "ExplicitLevels" cnres.cnLevels = np.arange(500, 600, 4) cnres.cnLineColor = "black" cnres.cnLineThicknessF = 5 plot2 = Ngl.contour(wks, h_cur, cnres) Ngl.overlay(plot_map, plot_cn) Ngl.overlay(plot_map, plot2) # txres = Ngl.Resources() txres.txFontHeightF = 0.024 # Ngl.text_ndc(wks, leftString, 0.3, 0.83, txres) Ngl.text_ndc(wks, rightString, 0.85, 0.83, txres) # Ngl.maximize_plot(wks, plot_map) Ngl.draw(plot_map) Ngl.frame(wks) Ngl.end() print("Finish darwing 500hPa gh plot plot for " + str(sel_month).zfill(2) + " " + str(sel_year))
def plot_oope_map(data, figname, size_class=None, percentage=1): ''' Draws 2D OOPE maps. :param xarray.Dataset data: 2D OOPE array. Dims must be (y, x, comm, size) :param str figname: Name of the figure file (must end by .png or .pdf) :param list size_class: Size classes to output (in m) :param float percentage: percentage used to saturate colorbar from percentile. Colorbar is saturated from values of the (X) and (100 - X) percentile. :return: None ''' if size_class is None: size_class = [1e-3, 1e-2, 1e-1, 1] # sort size class in ascending order, and add 0 and infinity as size bounds size_class = np.sort(size_class) if size_class[0] != 0: size_class = np.concatenate(([0], size_class), axis=0) if size_class[-1] != np.Inf: size_class = np.concatenate((size_class, [np.Inf]), axis=0) # Check that the OOPE dataset has 4 dimensions (i.e. no time dimension) ndims = len(data['OOPE'].dims) if ndims != 4: message = 'Data must have dimensions of size (lat, lon, comm, wei)' print(message) sys.exit(0) # Recover data variables length = data['length'].values oope = data['OOPE'].values lon = data['longitude'][:].values lat = data['latitude'][:].values comm = data['community'][:].values.astype(np.int) # mask oope where land oope = np.ma.masked_where(np.isnan(oope), oope) comm_string = misc.extract_community_names(data) if figname.endswith('png'): form = 'png' elif figname.endswith('pdf'): form = 'pdf' else: message = 'Figure name should end with png or pdf' print(message) sys.exit(0) # opens the document wks = Ngl.open_wks(form, figname) # set the document colormap # resngl = Ngl.Resources() # resngl.wkColorMap = 'precip2_15lev' # Ngl.set_values(wks, resngl) # Add gray to the workspace Ngl.new_color(wks, 0.7, 0.7, 0.7) # init the plot resources # For a detailed description, see https://www.ncl.ucar.edu/Document/Graphics/Resources/ res = Ngl.Resources() # not necessary, just a good habit res.nglDraw = False res.nglFrame = False # Set map resources. res.mpLimitMode = "LatLon" # limit map via lat/lon res.mpMinLatF = lat.min() # map area res.mpMaxLatF = lat.max() # latitudes res.mpMinLonF = lon.min() # and res.mpMaxLonF = lon.max() # longitudes res.mpFillOn = True res.mpLandFillColor = "LightGray" res.mpOceanFillColor = -1 res.mpInlandWaterFillColor = "LightBlue" res.mpGeophysicalLineThicknessF = 1 # thickness of coastlines # coordinates for contour plots res.sfXArray = lon res.sfYArray = lat res.cnFillOn = True # filled contour res.cnLinesOn = False # no lines res.cnLineLabelsOn = False # no labels res.cnInfoLabelOn = False # no info about contours res.cnFillMode = 'CellFill' # contourf=AreaFill, pcolor="CellFill" or "RasterFill" res.lbOrientation = "Horizontal" # colorbar orientation res.lbLabelFontHeightF = 0.012 # colorbar label fontsize res.lbTitlePosition = "Bottom" # position of colorbar title res.lbTitleFontHeightF = 0.012 # title font height # res.cnFillPalette = "wgne15" res.cnFillPalette = "WhiteBlueGreenYellowRed" txres = Ngl.Resources() txres.txJust = "BottomCenter" txres.txFontHeightF = 0.02 res.cnLevelSelectionMode = 'ExplicitLevels' res.cnMaxLevelCount = 41 res.mpGridAndLimbOn = True # Equations are complicated with NCARG # see https://www.ncl.ucar.edu/Applications/fcodes.shtml res.lbTitleString = "OOPE (J.kg~S~-1~N~.m~S~-2~N~)" # title of colorbar # Loop over communities for icom in comm: # Loop over size classes for isize in xrange(0, len(size_class) - 1): # Extract sizes comprised between the size class bound iw = np.nonzero((length >= size_class[isize]) & (length < size_class[isize+1]))[0] if iw.size == 0: continue # Integrate OOPE for the given community and given size class temp = oope[:, :, icom, iw] temp = np.sum(temp, axis=-1) # Finds the colorbar limits cmin, cmax = misc.find_percentile(temp, percentage=1) # draw the contour maps # defines the contour res.cnLevels = np.linspace(cmin, cmax, res.cnMaxLevelCount) mapplot = Ngl.contour_map(wks, temp, res) # add title title = 'Community=%s, %.2E m <= L < %.2E m' % (comm_string[icom], size_class[isize], size_class[isize + 1]) Ngl.text_ndc(wks, title, 0.5, 0.85, txres) # draws the map Ngl.draw(mapplot) # add a page to the pdf output Ngl.frame(wks)
def draw_2D_plot(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) if not os.path.exists(casedir + '/2D'): os.mkdir(casedir + '/2D') _Font = 25 interp = 2 extrap = False infiles = ['' for x in range(ncases)] ncdfs = ['' for x in range(ncases)] alpha = ['A', 'B', 'C', 'D', 'E', 'F'] cunits = [''] varis = [ 'SWCF', 'LWCF', 'PRECT', 'LHFLX', 'SHFLX', 'TMQ', 'PS', 'TS', 'U10', 'CLDTOT', 'CLDLOW', 'CLDHGH', 'TGCLDLWP' ] varisobs = [ 'SWCF', 'LWCF', 'PRECT', 'LHFLX', 'SHFLX', 'PREH2O', 'PS', 'TS', 'U10', 'CLDTOT_CAL', 'CLDTOT_CAL', 'CLDTOT_CAL', 'TGCLDLWP_OCEAN' ] nvaris = len(varis) cscale = [1, 1, 86400000, 1, 1, 1, 1, 1, 1, 100, 100, 100, 1000, 1, 1, 1] cscaleobs = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # cntrs = [[0 for col in range(11)] for row in range(nvaris)] cntrs = np.zeros((nvaris, 11), np.float32) obsdataset = [ 'CERES-EBAF', 'CERES-EBAF', 'GPCP', 'ERAI', 'NCEP', 'ERAI', 'NCEP', 'ERAI', 'ERAI', 'CALIPSOCOSP', 'CALIPSOCOSP', 'CALIPSOCOSP', 'NVAP' ] plot2d = ['' for x in range(nvaris)] for iv in range(0, nvaris): # make plot for each field if (varis[iv] == 'CLDTOT' or varis[iv] == 'CLDLOW' or varis[iv] == 'CLDHGH'): cntrs[iv, :] = [2, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90] if (varis[iv] == 'LWCF'): cntrs[iv, :] = [1, 2, 5, 10, 15, 20, 25, 30, 35, 40, 45] if (varis[iv] == 'SWCF' or varis[iv] == 'FLUT'): cntrs[iv, :] = [ -40, -50, -60, -70, -80, -90, -100, -110, -120, -130, -140 ] if (varis[iv] == 'PRECT' or varis[iv] == 'QFLX'): cntrs[iv, :] = [0.5, 1.5, 3, 4.5, 6, 7.5, 9, 10.5, 12, 13.5, 15] if (varis[iv] == 'LHFLX'): cntrs[iv, :] = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110] if (varis[iv] == 'SHFLX'): cntrs[iv, :] = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110] if (varis[iv] == 'U10'): cntrs[iv, :] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] if (varis[iv] == 'TMQ'): cntrs[iv, :] = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55] if (varis[iv] == 'TGCLDLWP'): cntrs[iv, :] = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110] # Observational data if (obsdataset[iv] == 'CCCM'): if (cseason == 'ANN'): fileobs = '/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-' + cseason + '.nc' else: fileobs = '/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-2010-' + cseason + '.nc' else: if (varisobs[iv] == 'PRECT'): fileobs = filepathobs + '/GPCP_' + cseason + '_climo.nc' else: fileobs = filepathobs + obsdataset[ iv] + '_' + cseason + '_climo.nc' # infiles[im]=filepath[im]+cases[im]+'/run/'+cases[im]+'_'+cseason+'_climo.nc' inptrobs = Dataset(fileobs, 'r') latobs = inptrobs.variables['lat'][:] lonobs = inptrobs.variables['lon'][:] if (varisobs[iv] == 'U10'): B0 = inptrobs.variables[varisobs[iv]][0, :, :] B1 = inptrobs.variables['V10'][0, :, :] B = (B0 * B0 + B1 * B1) B = B * cscaleobs[iv] B = np.sqrt(B) else: B = inptrobs.variables[varisobs[iv]][0, :, :] B = B * cscaleobs[iv] #************************************************ # create plot #************************************************ plotname = casedir + '/2D/Horizontal_' + varis[iv] + '_' + cseason plot2d[iv] = 'Horizontal_' + varis[iv] + '_' + cseason wks = Ngl.open_wks(ptype, plotname) Ngl.define_colormap(wks, 'cmocean_thermal') # Ngl.define_colormap(wks,'MPL_coolwarm') # ngl_define_colormap(wks,'prcp_1') plot = [] textres = Ngl.Resources() textres.txFontHeightF = 0.02 # Size of title. textres.txFont = _Font Ngl.text_ndc(wks, varis[iv], 0.1, .97, textres) pres = Ngl.Resources() pres.nglMaximize = True pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelBottom = 0.20 pres.nglPanelTop = 0.9 pres.pmLabelBarWidthF = 0.8 pres.nglFrame = False pres.nglPanelLabelBar = True # Turn on panel labelbar pres.nglPanelLabelBarLabelFontHeightF = 0.015 # Labelbar font height pres.nglPanelLabelBarHeightF = 0.0750 # Height of labelbar pres.nglPanelLabelBarWidthF = 0.700 # Width of labelbar pres.lbLabelFont = 'helvetica-bold' # Labelbar font pres.nglPanelTop = 0.935 pres.nglPanelFigureStrings = alpha pres.nglPanelFigureStringsJust = 'BottomRight' res = Ngl.Resources() res.nglDraw = False #-- don't draw plots res.nglFrame = False res.cnFillOn = True res.cnFillMode = 'RasterFill' res.cnLinesOn = False res.nglMaximize = True res.mpFillOn = True res.mpCenterLonF = 180 res.tiMainFont = _Font res.tiMainFontHeightF = 0.025 res.tiXAxisString = '' res.tiXAxisFont = _Font res.tiXAxisFontHeightF = 0.025 res.tiYAxisString = '' res.tiYAxisFont = _Font res.tiYAxisOffsetXF = 0.0 res.tiYAxisFontHeightF = 0.025 res.tmXBLabelFont = _Font res.tmYLLabelFont = _Font res.tiYAxisFont = _Font res.vpWidthF = 0.80 # set width and height res.vpHeightF = 0.40 res.vpXF = 0.04 res.vpYF = 0.30 res.cnInfoLabelOn = False res.cnFillOn = True res.cnLinesOn = False res.cnLineLabelsOn = False res.lbLabelBarOn = False # res.vcRefMagnitudeF = 5. # res.vcMinMagnitudeF = 1. # res.vcRefLengthF = 0.04 # res.vcRefAnnoOn = True#False # res.vcRefAnnoZone = 3 # res.vcRefAnnoFontHeightF = 0.02 # res.vcRefAnnoString2 ='' # res.vcRefAnnoOrthogonalPosF = -1.0 # res.vcRefAnnoArrowLineColor = 'blue' # change ref vector color # res.vcRefAnnoArrowUseVecColor = False # res.vcMinDistanceF = .05 # res.vcMinFracLengthF = . # res.vcRefAnnoParallelPosF = 0.997 # res.vcFillArrowsOn = True # res.vcLineArrowThicknessF = 3.0 # res.vcLineArrowHeadMinSizeF = 0.01 # res.vcLineArrowHeadMaxSizeF = 0.03 # res.vcGlyphStyle = 'CurlyVector' # turn on curley vectors # res@vcGlyphStyle ='Fillarrow' # res.vcMonoFillArrowFillColor = True # res.vcMonoLineArrowColor = True # res.vcLineArrowColor = 'green' # change vector color # res.vcFillArrowEdgeColor ='white' # res.vcPositionMode ='ArrowTail' # res.vcFillArrowHeadInteriorXF =0.1 # res.vcFillArrowWidthF =0.05 #default # res.vcFillArrowMinFracWidthF =.5 # res.vcFillArrowHeadMinFracXF =.5 # res.vcFillArrowHeadMinFracYF =.5 # res.vcFillArrowEdgeThicknessF = 2.0 res.mpFillOn = False res.cnLevelSelectionMode = 'ExplicitLevels' res.cnLevels = cntrs[iv][:] for im in range(0, ncases): ncdfs[im] = './data/' + cases[im] + '_site_location.nc' infiles[im] = filepath[im] + cases[im] + '/' + cases[ im] + '_' + cseason + '_climo.nc' inptrs = Dataset(infiles[im], 'r') # pointer to file1 lat = inptrs.variables['lat'][:] nlat = len(lat) lon = inptrs.variables['lon'][:] nlon = len(lon) area = inptrs.variables['area'][:] area_wgt = np.zeros(nlat) sits = np.linspace(0, nsite - 1, nsite) ncdf = Dataset(ncdfs[im], 'r') n = ncdf.variables['n'][:] idx_cols = ncdf.variables['idx_cols'][:] if (varis[iv] == 'PRECT'): A = inptrs.variables['PRECC'][ 0, :] + inptrs.variables['PRECL'][0, :] else: A = inptrs.variables[varis[iv]][0, :] if (varis[iv] == 'FLUT'): A = inptrs.variables['FLUT'][0, :] - inptrs.variables['FLNS'][ 0, :] else: A = inptrs.variables[varis[iv]][0, :] if (varis[iv] == 'U10'): A = inptrs.variables['U10'][0, :] * inptrs.variables['U10'][ 0, :] A = np.sqrt(A) else: A = inptrs.variables[varis[iv]][0, :] A_xy = A A_xy = A_xy * cscale[iv] ncdf.close() inptrs.close() if im == 0: dsizes = len(A_xy) field_xy = [[0 for col in range(dsizes)] for row in range(ncases)] field_xy[im][:] = A_xy res.lbLabelBarOn = False if (np.mod(im, 2) == 0): res.tiYAxisOn = True else: res.tiYAxisOn = False res.tiXAxisOn = False res.sfXArray = lon res.sfYArray = lat res.mpLimitMode = 'LatLon' res.mpMaxLonF = max(lon) res.mpMinLonF = min(lon) res.mpMinLatF = min(lat) res.mpMaxLatF = max(lat) res.tiMainString = 'GLB=' + str( np.sum(A_xy[:] * area[:] / np.sum(area))) textres.txFontHeightF = 0.015 Ngl.text_ndc(wks, alpha[im] + ' ' + casenames[im], 0.3, .135 - im * 0.03, textres) p = Ngl.contour_map(wks, A_xy, res) plot.append(p) # observation # res.nglLeftString = obsdataset[iv] # res@lbLabelBarOn = True # res@lbOrientation = 'vertical' # vertical label bars res.lbLabelFont = _Font res.tiYAxisOn = True res.tiXAxisOn = True res.tiXAxisFont = _Font rad = 4.0 * np.arctan(1.0) / 180.0 re = 6371220.0 rr = re * rad dlon = abs(lonobs[2] - lonobs[1]) * rr dx = dlon * np.cos(latobs * rad) jlat = len(latobs) dy = np.zeros(jlat, dtype=float) # close enough dy[0] = abs(lat[2] - lat[1]) * rr dy[1:jlat - 2] = abs(lat[2:jlat - 1] - lat[0:jlat - 3]) * rr * 0.5 dy[jlat - 1] = abs(lat[jlat - 1] - lat[jlat - 2]) * rr area_wgt = dx * dy # is_SE = False sum1 = 0 sum2 = 0 for j in range(0, jlat - 1): for i in range(0, len(lonobs) - 1): if (np.isnan(B[j][i]) != '--'): sum1 = sum1 + area_wgt[j] * B[j][i] sum2 = sum2 + area_wgt[j] glb = sum1 / sum2 res.sfXArray = lonobs res.sfYArray = latobs res.mpLimitMode = 'LatLon' res.mpMaxLonF = max(lonobs) res.mpMinLonF = min(lonobs) res.mpMinLatF = min(latobs) res.mpMaxLatF = max(latobs) res.tiMainString = 'GLB=' + str(glb) p = Ngl.contour_map(wks, B, res) if (iv == 0): poly_res = Ngl.Resources() poly_res.gsMarkerIndex = 16 poly_res.gsMarkerSizeF = 0.005 poly_res.gsMarkerColor = 'green' dum = Ngl.add_polymarker(wks, p, lons, lats, poly_res) plot.append(p) if (np.mod(ncases + 1, 2) == 1): Ngl.panel(wks, plot[:], [(ncases + 1) / 2 + 1, 2], pres) else: Ngl.panel(wks, plot[:], [(ncases + 1) / 2, 2], pres) Ngl.frame(wks) Ngl.destroy(wks) # Ngl.end() return plot2d
ycoord = [16.16,17.1,16.75,16.91,17.26] polyres.gsMarkerColor = "red" for gg in range(5): Ngl.polymarker(wks,xyplot,xcoord[gg],ycoord[gg],polyres) # 3rd set ycoord = [24.9,26.6,29.1,27.7] xcoord = [3.12,3.69,4.54,5.12] polyres.gsMarkerColor = "green" for gg in range(4): Ngl.polymarker(wks,xyplot,xcoord[gg],ycoord[gg],polyres) Ngl.draw(xyplot) # Ngl.draw_ndc_grid(wks) # For debug purposes. # # Draw a text string on side of plot. # txres.txFontHeightF = 0.01 txres.txAngleF = 90. Ngl.text_ndc(wks,"Central Antarctica",0.665,0.61,txres) Ngl.text_ndc(wks,"Tropical Atlantic", 0.665,0.75,txres) Ngl.text_ndc(wks,"North Atlantic", 0.665,0.86,txres) Ngl.frame(wks) # Now advance frame, we're done! Ngl.end()
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
# 注意必须将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. Ngl.destroy(wks)
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
import Ngl # # Draw four wind barbs of the same magnitude, but at different # locations and in different directions. # # Open a workstation. # wks_type = "ps" wks = Ngl.open_wks(wks_type, "wmbarb") # # Draw wind barbs. # x = [0.25, 0.75, 0.75, 0.25] # x,y,u,v can also be Numeric arrays. y = [0.25, 0.25, 0.75, 0.75] u = [50., -50., -50., 50.0] v = [50., 50., -50., -50.0] Ngl.wmsetp("wbs", 0.2) # Scale the size. Ngl.wmbarb(wks, x, y, u, v) # Draw barbs. Ngl.frame(wks) # Draw plot. # # Retrieve the value of the wbs parameter. # size = Ngl.wmgetp("wbs") print size Ngl.end()
def clubb_std_prf(ptype, cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs, casedir, varis, vname, cscale, chscale, pname): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = "Red" mkres.gsMarkerSizeF = 15. 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) ' ] infiles = ["" for x in range(ncases)] ncdfs = ["" for x in range(ncases)] nregions = nsite nvaris = len(varis) plotstd = ["" for x in range(nsite)] for ire in range(0, nsite): if not os.path.exists(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N'): os.mkdir(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N') plotname = casedir + '/' + str(lons[ire]) + 'E_' + str( lats[ire]) + 'N/' + pname + '_' + str(lons[ire]) + "E_" + str( lats[ire]) + "N_" + cseason plotstd[ire] = pname + '_' + str(lons[ire]) + "E_" + str( lats[ire]) + "N_" + cseason wks = Ngl.open_wks(ptype, plotname) Ngl.define_colormap(wks, "GMT_paired") plot = [] res = Ngl.Resources() res.nglMaximize = False if (lats[ire] > 0 and lons[ire] < 230): res.trYMinF = 400. res.trYMaxF = 1000. else: res.trYMinF = 700. res.trYMaxF = 1000. res.nglDraw = False res.nglFrame = False res.lgLabelFontHeightF = .02 # change font height res.lgPerimOn = False # no box around res.vpWidthF = 0.30 # set width and height res.vpHeightF = 0.30 res.vpXF = 0.04 res.vpYF = 0.30 res.tmYLLabelFont = _Font res.tmXBLabelFont = _Font res.tiYAxisFont = _Font res.tiXAxisFont = _Font res.tmXBLabelFontHeightF = 0.01 res.tmXBLabelFontThicknessF = 2.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) # res.xyMarkers = np.arange(16,40,1) # res.xyMarkerSizeF = 0.005 res.tiYAxisString = "Pressure [hPa]" 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') # B=inptrobs.variables[varisobs[iv]][:,(lats[ire]),(lons[ire])] # 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"): # B = inptrobs.variables['T'][0,:,(lats[ire]),(lons[ire])] # 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'][:] # B = inptrobs.variables[varisobs[iv]][0,:,(lats[ire]),(lons[ire])] # # 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['ilev'][:] 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( chscale[iv]) + inptrs.variables['T'].units else: tmp = inptrs.variables[varis[iv]][0, :, npoint] # tmp2=inptrs.variables['C6rt_Skw_fnc'][0,:,npoint] # tmp3=inptrs.variables['tau_zm'][0,:,npoint] # tmp4=inptrs.variables['tau_wpxp_zm'][0,:,npoint] theunits = str( chscale[iv]) + inptrs.variables[varis[iv]].units if (varis[iv] == 'tau_zm' or varis[iv] == 'tau_wp2_zm' \ or varis[iv] == 'tau_wp3_zm' or varis[iv] == 'tau_xp2_zm' \ or varis[iv] == 'tau_no_N2_zm' or varis[iv] == 'tau_wpxp_zm'): tmp = 1 / tmp tmp[0:10] = 0.0 theunits = str(chscale[iv]) + inptrs.variables[ varis[iv]].units + '^-1' A_field[im, :] = (A_field[im, :] + tmp[:] / n[ire]).astype( np.float32) A_field[im, :] = A_field[im, :] * cscale[iv] inptrs.close() res.tiXAxisString = vname[iv] + " Unit= " + theunits 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) plot.append(p) pres = Ngl.Resources() pres.nglFrame = False pres.txFont = _Font pres.nglMaximize = False pres.txFont = _Font # pres.nglPanelYWhiteSpacePercent = 5 # pres.nglPanelXWhiteSpacePercent = 5 # pres.wkPaperWidthF = 17 # in inches # pres.wkPaperHeightF = 28 # in inches pres.nglPanelTop = 0.935 pres.nglPanelFigureStrings = alphas pres.nglPanelFigureStringsJust = 'Topleft' pres.nglPanelFigureStringsFontHeightF = 0.015 pres.gsnPaperOrientation = "Landscape" txres = Ngl.Resources() txres.txFontHeightF = 0.02 txres.txFont = _Font Ngl.text_ndc( wks, "CLUBB VAR at " + str(lons[ire]) + "E," + str(lats[ire]) + "N", 0.5, 0.75, txres) Common_functions.create_legend(wks, casenames, 0.015, np.arange(3, 20, 2), 0.3, 0.59 + ncases * 0.01) Ngl.panel(wks, plot[:], [nvaris / 2, 2], pres) Ngl.frame(wks) Ngl.destroy(wks) return plotstd
line_res.gsLineThicknessF = 1.5 # line thickness scale line_res.gsLineDashPattern = 2 # dashed lines Ngl.polyline(wks,plot,lon2d[:,0],lat2d[:,0],line_res) Ngl.polyline(wks,plot,lon2d[:,-1],lat2d[:,-1],line_res) # # Add a text string explaining the lines. # text_res = Ngl.Resources() # text resources text_res.txFontHeightF = 0.03 # font height text_res.txFontColor = "Red" Ngl.text_ndc(wks,"dashed red line shows area with no data",0.5,0.17,text_res) Ngl.frame(wks) # Now advance frame. # # Add cyclic points. Since lat2d/lon2d are 2D arrays, make them # cyclic the same way you do the 2D data array. # u = Ngl.add_cyclic(urot) v = Ngl.add_cyclic(vrot) lon = Ngl.add_cyclic(lon2d) lat = Ngl.add_cyclic(lat2d) # # Specify new coordinate arrays for data. # resources.vfXArray = lon resources.vfYArray = lat
polyg = Ngl.add_polygon(wks1,map,x1d,y1d,pgres) #-- add a labelbar lbres = Ngl.Resources() lbres.vpWidthF = 0.85 lbres.vpHeightF = 0.15 lbres.lbOrientation = 'Horizontal' lbres.lbFillPattern = 'SolidFill' lbres.lbMonoFillPattern = 21 #-- must be 21 for color solid fill lbres.lbMonoFillColor = False #-- use multiple colors lbres.lbFillColors = colors #-- indices from loaded colormap lbres.lbBoxCount = len(colormap[colors,:]) lbres.lbLabelFontHeightF= 0.014 lbres.lbLabelAlignment = 'InteriorEdges' lbres.lbLabelStrings = labels lb = Ngl.labelbar_ndc(wks1,nlevs+1,labels,0.1,0.24,lbres) #-- maximize and draw the plot and advance the frame Ngl.maximize_plot(wks1, map) Ngl.draw(map) Ngl.frame(wks1) #-- get wallclock time t2 = time.time() print '' print 'Wallclock time: %0.3f seconds' % (t2-t1) print '' Ngl.end()
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 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
polyg = Ngl.add_polygon(wks1, map, x1d, y1d, pgres) #-- add a labelbar lbres = Ngl.Resources() lbres.vpWidthF = 0.85 lbres.vpHeightF = 0.15 lbres.lbOrientation = 'Horizontal' lbres.lbFillPattern = 'SolidFill' lbres.lbMonoFillPattern = 21 #-- must be 21 for color solid fill lbres.lbMonoFillColor = False #-- use multiple colors lbres.lbFillColors = colors #-- indices from loaded colormap lbres.lbBoxCount = len(colormap[colors, :]) lbres.lbLabelFontHeightF = 0.014 lbres.lbLabelAlignment = 'InteriorEdges' lbres.lbLabelStrings = labels lb = Ngl.labelbar_ndc(wks1, nlevs + 1, labels, 0.1, 0.24, lbres) #-- maximize and draw the plot and advance the frame Ngl.maximize_plot(wks1, map) Ngl.draw(map) Ngl.frame(wks1) #-- get wallclock time t2 = time.time() print('') print('Wallclock time: %0.3f seconds' % (t2 - t1)) print('') 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) Ngl.draw(xy)
def draw_3D_plot(ptype, clevel, cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs, casedir): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) if not os.path.exists(casedir + "/2D"): os.mkdir(casedir + "/2D") _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = "Red" mkres.gsMarkerSizeF = 15. infiles = ["" for x in range(ncases)] ncdfs = ["" for x in range(ncases)] varis = ["T", "OMEGA", "Z3"] varisobs = ["T", "OMEGA", "Z3"] alpha = ["A", "B", "C", "D", "E", "F"] nvaris = len(varis) cunits = [""] cscale = [1, 864, 1, 1, 1, 1] cscaleobs = [1, 1, 1, 1, 0.04] cntrs = np.zeros((nvaris, 11), np.float32) obsdataset = ["ERAI", "ERAI", "ERAI", "ERAI", "ERAI"] level = [ 1000., 925., 850., 700., 600., 500., 400., 300., 250., 200., 150., 100. ] plot3d = ["" for x in range(nvaris)] for iv in range(0, nvaris): # make plot for each field # Observational data if (obsdataset[iv] == "CCCM"): if (cseason == "ANN"): fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-" + cseason + ".nc" else: fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-2010-" + cseason + ".nc" else: if (varisobs[iv] == "PRECT"): fileobs = filepathobs + '/GPCP_' + cseason + '_climo.nc' else: fileobs = filepathobs + obsdataset[ iv] + '_' + cseason + '_climo.nc' inptrobs = Dataset(fileobs, 'r') latobs = inptrobs.variables['lat'][:] lonobs = inptrobs.variables['lon'][:] levobs = inptrobs.variables['lev'][:] levobs_idx = np.abs(levobs - clevel).argmin() B = inptrobs.variables[varisobs[iv]][0, levobs_idx, :, :] B = B * cscaleobs[iv] # cntrs= np.arange(np.min(B),np.max(B),12) if (varis[iv] == "OMEGA"): cntrs[iv, :] = [-50, -40, -30, -20, -10, 0, 10, 20, 30, 40, 50] if (varis[iv] == "Z3"): if (clevel == 500): cntrs[iv, :] = [ 5300, 5400, 5500, 5600, 5700, 5800, 5900, 6000, 6100, 6200, 6300 ] else: cntrs[iv, :] = [ 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300 ] if (varis[iv] == "T"): if (clevel == 500): cntrs[iv, :] = [ 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 310 ] else: cntrs[iv, :] = [ 292, 294, 296, 298, 300, 302, 304, 306, 308, 310, 312 ] if (varis[iv] == "Q"): if (clevel == 500): cntrs[iv, :] = [ 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 310 ] else: cntrs[iv, :] = [ 292, 294, 296, 298, 300, 302, 304, 306, 308, 310, 312 ] #************************************************ # create plot #************************************************ plotname = casedir + '/2D/Horizontal_' + varis[ iv] + '_' + cseason + str(clevel) plot3d[iv] = 'Horizontal_' + varis[iv] + '_' + cseason + str(clevel) wks = Ngl.open_wks(ptype, plotname) Ngl.define_colormap(wks, "amwg256") plot = [] textres = Ngl.Resources() textres.txFontHeightF = 0.02 # Size of title. textres.txFont = _Font Ngl.text_ndc(wks, varis[iv], 0.1, .97, textres) pres = Ngl.Resources() # pres.nglMaximize = True pres.nglFrame = False pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelBottom = 0.2 pres.nglPanelTop = 0.9 pres.nglPanelLabelBar = True pres.pmLabelBarWidthF = 0.8 pres.nglFrame = False pres.nglPanelLabelBar = True # Turn on panel labelbar pres.nglPanelLabelBarLabelFontHeightF = 0.015 # Labelbar font height pres.nglPanelLabelBarHeightF = 0.0750 # Height of labelbar pres.nglPanelLabelBarWidthF = 0.700 # Width of labelbar pres.lbLabelFont = "helvetica-bold" # Labelbar font pres.nglPanelTop = 0.93 pres.nglPanelFigureStrings = alpha pres.nglPanelFigureStringsJust = "BottomRight" res = Ngl.Resources() res.nglDraw = False #-- don't draw plots res.nglFrame = False res.cnFillOn = True res.cnFillMode = "RasterFill" res.cnLinesOn = False res.nglMaximize = True res.mpFillOn = True res.mpCenterLonF = 180 res.tiMainFont = _Font res.tiMainFontHeightF = 0.025 res.tiXAxisString = "" res.tiXAxisFont = _Font res.tiXAxisFontHeightF = 0.025 res.tiYAxisString = "" res.tiYAxisFont = _Font res.tiYAxisOffsetXF = 0.0 res.tiYAxisFontHeightF = 0.025 res.tmXBLabelFont = _Font res.tmYLLabelFont = _Font res.tiYAxisFont = _Font # res.nglStringFont = _Font # res.nglStringFontHeightF = 0.04 # res.nglRightString = ""#"Cloud Fraction" # res.nglScalarContour = True res.cnInfoLabelOn = False res.cnFillOn = True res.cnLinesOn = False res.cnLineLabelsOn = False res.lbLabelBarOn = False # res.vcRefMagnitudeF = 5. # res.vcMinMagnitudeF = 1. # res.vcRefLengthF = 0.04 # res.vcRefAnnoOn = True#False # res.vcRefAnnoZone = 3 # res.vcRefAnnoFontHeightF = 0.02 # res.vcRefAnnoString2 ="" # res.vcRefAnnoOrthogonalPosF = -1.0 # res.vcRefAnnoArrowLineColor = "blue" # change ref vector color # res.vcRefAnnoArrowUseVecColor = False # res.vcMinDistanceF = .05 # res.vcMinFracLengthF = . # res.vcRefAnnoParallelPosF = 0.997 # res.vcFillArrowsOn = True # res.vcLineArrowThicknessF = 3.0 # res.vcLineArrowHeadMinSizeF = 0.01 # res.vcLineArrowHeadMaxSizeF = 0.03 # res.vcGlyphStyle = "CurlyVector" # turn on curley vectors # res@vcGlyphStyle ="Fillarrow" # res.vcMonoFillArrowFillColor = True # res.vcMonoLineArrowColor = True # res.vcLineArrowColor = "green" # change vector color # res.vcFillArrowEdgeColor ="white" # res.vcPositionMode ="ArrowTail" # res.vcFillArrowHeadInteriorXF =0.1 # res.vcFillArrowWidthF =0.05 #default # res.vcFillArrowMinFracWidthF =.5 # res.vcFillArrowHeadMinFracXF =.5 # res.vcFillArrowHeadMinFracYF =.5 # res.vcFillArrowEdgeThicknessF = 2.0 res.mpFillOn = False res.cnLevelSelectionMode = "ExplicitLevels" res.cnLevels = cntrs[iv, :] for im in range(0, ncases): ncdfs[im] = './data/' + cases[im] + '_site_location.nc' infiles[im] = filepath[im] + '/' + cases[ im] + '_' + cseason + '_climo.nc' inptrs = Dataset(infiles[im], 'r') # pointer to file1 lat = inptrs.variables['lat'][:] nlat = len(lat) lon = inptrs.variables['lon'][:] nlon = len(lon) #area=inptrs.variables['area'][:] lev = inptrs.variables['lev'][:] lev_idx = np.abs(lev - clevel).argmin() area_wgt = np.zeros(nlat) # area_wgt[:] = gw[:] sits = np.linspace(0, nsite - 1, nsite) ncdf = Dataset(ncdfs[im], 'r') n = ncdf.variables['n'][:] idx_cols = ncdf.variables['idx_cols'][:] A = inptrs.variables[varis[iv]][0, lev_idx, :] A_xy = A A_xy = A_xy * cscale[iv] ncdf.close() inptrs.close() if im == 0: dsizes = len(A_xy) field_xy = [[0 for col in range(dsizes)] for row in range(ncases)] field_xy[im][:] = A_xy res.lbLabelBarOn = False if (np.mod(im, 2) == 0): res.tiYAxisOn = True else: res.tiYAxisOn = False res.tiXAxisOn = False res.sfXArray = lon res.sfYArray = lat res.mpLimitMode = "LatLon" res.mpMaxLonF = max(lon) res.mpMinLonF = min(lon) res.mpMinLatF = min(lat) res.mpMaxLatF = max(lat) #res.tiMainString = "GLB="+str(np.sum(A_xy[:]*area[:]/np.sum(area))) res.tiMainString = "GLB=" textres.txFontHeightF = 0.015 Ngl.text_ndc(wks, alpha[im] + " " + casenames[im], 0.3, .135 - im * 0.03, textres) p = Ngl.contour_map(wks, A_xy, res) plot.append(p) # observation # res.nglLeftString = obsdataset[iv] # res@lbLabelBarOn = True # res@lbOrientation = "vertical" # vertical label bars res.lbLabelFont = _Font res.tiYAxisOn = True res.tiXAxisOn = True res.tiXAxisFont = _Font rad = 4.0 * np.arctan(1.0) / 180.0 re = 6371220.0 rr = re * rad dlon = abs(lonobs[2] - lonobs[1]) * rr dx = dlon * np.cos(latobs * rad) jlat = len(latobs) dy = np.zeros(jlat, dtype=float) # close enough dy[0] = abs(lat[2] - lat[1]) * rr dy[1:jlat - 2] = abs(lat[2:jlat - 1] - lat[0:jlat - 3]) * rr * 0.5 dy[jlat - 1] = abs(lat[jlat - 1] - lat[jlat - 2]) * rr area_wgt = dx * dy # is_SE = False sum1 = 0 sum2 = 0 for j in range(0, jlat - 1): for i in range(0, len(lonobs) - 1): if (np.isnan(B[j][i]) != "--"): sum1 = sum1 + area_wgt[j] * B[j][i] sum2 = sum2 + area_wgt[j] res.sfXArray = lonobs res.sfYArray = latobs res.mpLimitMode = "LatLon" res.mpMaxLonF = max(lonobs) res.mpMinLonF = min(lonobs) res.mpMinLatF = min(latobs) res.mpMaxLatF = max(latobs) res.tiMainString = "GLB=" + str( sum1 / sum2) #Common_functions.area_avg(B, area_wgt,is_SE)) p = Ngl.contour_map(wks, B, res) plot.append(p) if (np.mod(ncases + 1, 2) == 1): Ngl.panel(wks, plot[:], [(ncases + 1) / 2 + 1, 2], pres) else: Ngl.panel(wks, plot[:], [(ncases + 1) / 2, 2], pres) Ngl.frame(wks) Ngl.destroy(wks) return plot3d
cnres.cnFillOn = True cnres.cnLinesOn = False cnres.cnLineLabelsOn = False cnres.cnFillMode = "CellFill" cnres.cnCellFillEdgeColor = "Black" cnres.cnMonoFillColor = True cnres.cnFillColor = "Transparent" cnres.cnCellFillMissingValEdgeColor = "Red" cnres.lbLabelBarOn = False cnres.tiMainString = "Pop Grid cells -- grid stride [::3,::3]" plot = Ngl.contour_map(wks,temp[:-2:3,:-2:3],cnres) Ngl.frame(wks) # # Now set up a vector resource variable. # vcres = Ngl.Resources() # # Set coordinate arrays for data. This is necessary in order to overlay # the vectors on a map. # vcres.vfXArray = lon vcres.vfYArray = lat vcres.mpProjection = "Orthographic" vcres.mpFillOn = True
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) Ngl.draw(xy)
import numpy as np import Ngl, Nio #-- open file and read variables f = Nio.open_file("/mnt/e/SYSU/data/NCEP/air.mon.mean.nc", "r") var = f.variables["air"][0, 0, :, :] lat = f.variables["lat"][:] lon = f.variables["lon"][:] wks = Ngl.open_wks("png", "/mnt/e/SYSU/p_py") #-- resource settings res = Ngl.Resources() res.nglFrame = False res.cnFillOn = True res.cnFillPalette = "NCL_default" res.cnLineLabelsOn = False res.lbOrientation = "horizontal" #-- horizontal labelbar res.sfXArray = lon res.sfYArray = lat #-- create the contour plot plot = Ngl.contour_map(wks, var, res) #-- write variable long_name and units to the plot txres = Ngl.Resources() txres.txFontHeightF = 0.012 Ngl.text_ndc(wks,f.variables["air"].attributes['long_name'],\ 0.14,0.82,txres) Ngl.text_ndc(wks,f.variables["air"].attributes['units'], \ 0.95,0.82,txres) #-- advance the frame Ngl.frame(wks) Ngl.end()
def draw_clubb_bgt(ptype, cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs, casedir, varis, vname, cscale, chscale, pname): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = "Red" mkres.gsMarkerSizeF = 15. infiles = ["" for x in range(ncases)] ncdfs = ["" for x in range(ncases)] nregions = nsite nvaris = len(varis) plotbgt = ["" for x in range(nsite * ncases)] 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) ' ] for ire in range(0, nsite): for im in range(0, ncases): if not os.path.exists(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N'): os.mkdir(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N') plotname = casedir + '/' + str(lons[ire]) + 'E_' + str( lats[ire]) + 'N/' + pname + '_' + casenames[im] + "_" + str( lons[ire]) + "E_" + str(lats[ire]) + "N_" + cseason plotbgt[im + ncases * ire] = pname + '_' + casenames[im] + "_" + str( lons[ire]) + "E_" + str(lats[ire]) + "N_" + cseason wks = Ngl.open_wks(ptype, plotname) Ngl.define_colormap(wks, "radar") plot = [] res = Ngl.Resources() res.nglDraw = False res.nglFrame = False res.nglScale = False # res.vpWidthF = 0.40 # set width and height # res.vpHeightF = 0.40 # res.vpXF = 0.04 # res.vpYF = 0.30 res.nglMaximize = False 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.02 res.tmXBLabelFontThicknessF = 1.0 res.xyMarkLineMode = "MarkLines" res.xyLineThicknesses = [ 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3., 2., 2., 2., 2, 2, 2, 2, 2, 2, 2 ] res.xyLineColors = np.arange(1, 16, 4) res.xyDashPatterns = np.arange(0, 24, 1) res.xyMarkers = np.arange(16, 40, 1) res.xyMarkerSizeF = 0.005 res.xyMarkerColors = np.arange(1, 16, 4) res.pmLegendDisplayMode = "NEVER" res.pmLegendSide = "top" # Change location of res.pmLegendParallelPosF = 0.75 # move units right res.pmLegendOrthogonalPosF = -0.65 # more neg = down res.pmLegendWidthF = 0.05 # Change width and res.pmLegendHeightF = 0.06 # height of legend. res.lgLabelFontHeightF = 0.03 # change font height res.lgLabelFontThicknessF = 1. # res.lgBoxMinorExtentF = 0.5 res.lgPerimOn = False res.tiYAxisString = "Pressure [hPa]" res.tmYLLabelFontHeightF = 0.02 res.trYReverse = True res1 = Ngl.Resources() res1 = res pres = Ngl.Resources() # pres.gsnPaperOrientation= "Landscape" # pres.wkPaperWidthF = 20 # in inches # pres.wkPaperHeightF = 28 # in inches pres.nglMaximize = False # pres.vpWidthF = 0.40 # set width and height # pres.vpHeightF = 0.40 pres.nglFrame = False pres.txFont = _Font pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 3 pres.nglPanelTop = .9 # pres.nglPanelBottom=0.3 # pres.nglPanelLeft= 0.2 # pres.nglPanelRight= 0.95 pres.nglPanelFigureStrings = alphas pres.nglPanelFigureStringsJust = 'Topleft' pres.nglPanelFigureStringsFontHeightF = 0.015 for iv in range(0, nvaris): if (varis[iv] == "rtp2" or varis[iv] == "thlp2"): budget_ends = ["_ta", "_tp", "_dp1"] budget_name = [ '~F10~turb adv', '~F10~turb prod', '~F10~dissipation' ] nterms = len(budget_ends) if (varis[iv] == "wprtp"): budget_ends = [ "_bt", "_ma", "_ta", "_tp", "_ac", "_bp", "_pr1", "_pr2", "_pr3", "_dp1", "_mfl", "_cl", "_sicl", "_pd", "_forcing" ] budget_name = budget_ends nterms = len(budget_ends) if (varis[iv] == "wpthlp"): budget_ends = ["_tp", "_bp", "_pr1"] budget_name = [ '~F10~turb prod', '~F10~buoy+pres', '~F10~ret to iso' ] nterms = len(budget_ends) if (varis[iv] == "rtpthlp"): budget_ends = [ "_bt", "_ma", "_ta", "_tp1", "_tp2", "_dp1", "_dp2", "_cl", "_sf", "_forcing" ] budget_name = budget_ends nterms = len(budget_ends) if (varis[iv] == "wp2"): budget_ends = ["_ta", "_bp", "_pr1", "_dp1", "_dp2"] budget_name = budget_ends nterms = len(budget_ends) if (varis[iv] == "wp3"): budget_ends = [ "_ta", "_tp", "_bp1", "_bp2", "_pr1", "_pr2", "_dp1" ] budget_name = budget_ends nterms = len(budget_ends) if (varis[iv] == "up2" or varis[iv] == "vp2"): budget_ends = [ "_bt", "_ma", "_ta", "_tp", "_dp1", "_dp2", "_pr1", "_pr2", "_cl", "_pd", "_sf" ] budget_name = budget_ends nterms = len(budget_ends) if (varis[iv] == "um" or varis[iv] == "vm"): budget_ends = ["_bt", "_ma", "_ta", "_gf", "_f"] budget_name = budget_ends nterms = len(budget_ends) if (varis[iv] == "thlm" or varis[iv] == "rtm"): budget_ends = ["_bt", "_ma", "_ta", "_cl", "_mc"] budget_name = budget_ends nterms = len(budget_ends) if (varis[iv] == 'tau_no_N2_zm'): budget_ends = ['tau_no_N2_zm', 'bkgnd', 'sfc', 'shear'] budget_name = [ '~F8~t~N~~F25~~B~noN2~N~', '~F8~t~N~~F25~~B~bkgnd~N~', '~F8~t~N~~F25~~B~shear~N~', '~F8~t~N~~F25~~B~shear~N~' ] nterms = len(budget_ends) if (varis[iv] == 'tau_xp2_zm'): budget_ends = ['tau_xp2_zm', 'tau_no_N2_zm'] budget_name = [ '~F8~t~N~~F25~~B~x`~S~2~N~~N~', '~F8~t~N~~F25~~B~noN2~N~' ] nterms = len(budget_ends) if (varis[iv] == 'tau_wp2_zm'): budget_ends = ['tau_wp2_zm', 'tau_no_N2_zm', 'bvpos'] budget_name = [ '~F8~t~N~~F25~~B~w`~S~2~N~~N~', '~F8~t~N~~F25~~B~noN2~N~', '~F8~t~N~~F25~~B~bv~N~' ] nterms = len(budget_ends) if (varis[iv] == 'tau_wpxp_zm'): budget_ends = [ 'tau_wpxp_zm', 'tau_no_N2_zm', 'bvpos', 'clear' ] budget_name = [ '~F8~t~N~~F25~~B~w`x`~N~', '~F8~t~N~~F25~~B~noN2~N~', '~F8~t~N~~F25~~B~bv~N~', '~F8~t~N~~F25~~B~clr~N~' ] nterms = len(budget_ends) if (varis[iv] == 'tau_wp3_zm'): budget_ends = [ 'tau_wp3_zm', 'tau_no_N2_zm', 'bvpos', 'clear' ] budget_name = [ '~F8~t~N~~F25~~B~w`~S~3~N~~N~', '~F8~t~N~~F25~~B~noN2~N~', '~F8~t~N~~F25~~B~bv~N~', '~F8~t~N~~F25~~B~clr~N~' ] nterms = len(budget_ends) ncdfs[im] = './data/' + cases[im] + '_site_location.nc' infiles[im] = filepath[im] + cases[im] + '/' + cases[ im] + '_' + cseason + '_climo.nc' inptrs = Dataset(infiles[im], 'r') # pointer to file1 lat = inptrs.variables['lat'][:] nlat = len(lat) lon = inptrs.variables['lon'][:] nlon = len(lon) ilev = inptrs.variables['ilev'][:] nilev = len(ilev) ncdf = Dataset(ncdfs[im], 'r') n = ncdf.variables['n'][:] idx_cols = ncdf.variables['idx_cols'][:, :] ncdf.close() A_field = np.zeros((nterms, nilev), np.float32) for it in range(0, nterms): for subc in range(0, n[ire]): npoint = idx_cols[ire, n[subc] - 1] - 1 varis_bgt = varis[iv] + budget_ends[it] tmp0 = inptrs.variables[varis[iv]][0, :, npoint] theunits0 = "~F25~" + inptrs.variables[varis[iv]].units if (varis[iv] == 'wpthlp' and budget_ends[it] == '_bp'): tmp = inptrs.variables[varis_bgt][ 0, :, npoint] + inptrs.variables['wpthlp_pr3'][ 0, :, npoint] else: tmp = inptrs.variables[varis_bgt][0, :, npoint] theunits = str( chscale[iv]) + "~F25~" + inptrs.variables[ varis[iv] + '_bt'].units if (varis[iv] == "wprtp" or varis[iv] == "thlp2"): tmp[0:10] = 0.0 tmp0[0:10] = 0.0 txres = Ngl.Resources() txres.txFontHeightF = 0.02 txres.txFont = _Font tmp = tmp * cscale[iv] A_field[it, :] = (A_field[it, :] + tmp[:] / n[ire]).astype(np.float32) inptrs.close() res.tiXAxisString = vname[iv] + ' Unit= ' + theunits if (varis[iv] == "wpthlp" or varis[iv] == "thlp2" or varis[iv] == "wp3" or varis[iv] == "wp2"): res1.tiXAxisString = vname[iv] + ' Unit= ' + theunits0 p0 = Ngl.xy(wks, tmp0, ilev, res1) plot.append(p0) if (varis[iv] == 'wpthlp'): if (lons[ire] < 230): res.trXMinF = -1. res.trXMaxF = 1. Common_functions.create_legend(wks, budget_name, 0.013, np.arange(1, 16, 4), 0.77, 0.85 - iv * 0.45) else: res.trXMinF = -0.4 res.trXMaxF = 0.4 Common_functions.create_legend(wks, budget_name, 0.013, np.arange(1, 16, 4), 0.77, 0.85 - iv * 0.45) if (varis[iv] == 'thlp2'): if (lons[ire] < 230): res.trXMinF = -2.8 res.trXMaxF = 2.8 Common_functions.create_legend(wks, budget_name, 0.013, np.arange(1, 16, 4), 0.77, 0.85 - iv * 0.45) else: res.trXMinF = -1. res.trXMaxF = 1. Common_functions.create_legend(wks, budget_name, 0.013, np.arange(1, 16, 4), 0.77, 0.85 - iv * 0.45) res.tiXAxisString = vname[iv] + ' Unit= ' + theunits p = Ngl.xy(wks, A_field, ilev, res) plot.append(p) del (res.trXMaxF) del (res.trXMinF) xp = np.mod(iv, 2) yp = int(iv / 2) Ngl.panel(wks, plot[:], [nvaris, 2], pres) txres = Ngl.Resources() txres.txFont = _Font txres.txFontHeightF = 0.02 Ngl.text_ndc( wks, casenames[im] + " BUDGET at " + str(lons[ire]) + "E," + str(lats[ire]) + "N", 0.5, 0.91, txres) Ngl.frame(wks) Ngl.destroy(wks) return (plotbgt)
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
def plot_contourmap(path, date, fcst_hours, variable, stat_processing_methods): ##### generate subpath and filename ##### subpath = 'run_{}{:02}{:02}{:02}/{}/'.format(\ date['year'], date['month'], date['day'], date['hour'], variable) filename1 = 'icon-eu-eps_europe_icosahedral_single-level_{}{:02}{:02}{:02}_{:03}_{}.grib2'.format(\ date['year'], date['month'], date['day'], date['hour'], fcst_hours[0], variable) filename2 = 'icon-eu-eps_europe_icosahedral_single-level_{}{:02}{:02}{:02}_{:03}_{}.grib2'.format(\ date['year'], date['month'], date['day'], date['hour'], fcst_hours[1], variable) ######################################################################## ### read data ### ######################################################################## ##### create empty numpy arrays ##### ##### 2 fcst_hours, 40 members, 75948 eu gridpoints ##### data_raw = np.empty((2, 40, 75948)) data_members = np.empty((40, 75948)) ##### every time in loop open next grib msg from grib file ##### ##### grib messages in dwd file are sorted by increasing member number ##### with open(path['base'] + path['data'] + subpath + filename1, 'rb') as file: for member in range(1, 41): print('read data from member {}'.format(member)) grib_msg_id = eccodes.codes_grib_new_from_file(file) data_raw[0, member - 1, :] = eccodes.codes_get_array( grib_msg_id, 'values') eccodes.codes_release(grib_msg_id) with open(path['base'] + path['data'] + subpath + filename2, 'rb') as file: for member in range(1, 41): print('read data from member {}'.format(member)) grib_msg_id = eccodes.codes_grib_new_from_file(file) data_raw[1, member - 1, :] = eccodes.codes_get_array( grib_msg_id, 'values') eccodes.codes_release(grib_msg_id) ##### take the difference of the two accumulated total precipitation arrays ##### data_members = data_raw[1, :, :] - data_raw[0, :, :] del data_raw ##### open icon-eps grid file ##### icongrid_file = nc.Dataset( path['base'] + path['grid'] + 'icon_grid_0028_R02B07_N02.nc', 'r') vlat = icongrid_file.variables['clat_vertices'][:].data * 180. / np.pi vlon = icongrid_file.variables['clon_vertices'][:].data * 180. / np.pi clat = icongrid_file.variables['clat'][:].data * 180. / np.pi clon = icongrid_file.variables['clon'][:].data * 180. / np.pi icongrid_file.close() for stat_processing in stat_processing_methods: ######################################################################## ### statistically process data ### ######################################################################## if stat_processing == 'mean': data_processed = data_members.mean(axis=0) elif stat_processing == 'max': data_processed = data_members.max(axis=0) elif stat_processing == 'min': data_processed = data_members.min(axis=0) elif stat_processing == '90p': data_processed = np.percentile(data_members, 90, axis=0) elif stat_processing == '75p': data_processed = np.percentile(data_members, 75, axis=0) elif stat_processing == '50p': data_processed = np.percentile(data_members, 50, axis=0) elif stat_processing == '25p': data_processed = np.percentile(data_members, 25, axis=0) elif stat_processing == '10p': data_processed = np.percentile(data_members, 10, axis=0) #print('shape of data_members: {}'.format(np.shape(data_members))) #print('shape of data_processed: {}'.format(np.shape(data_processed))) ######################################################################## ### plot data on world map ### ######################################################################## ##### set domain due to center point and radius ##### center_point = dict(lat=48.5, lon=9.0) radius = 1800 # domain radius in km around center_point domain = dict( lat_min=center_point['lat'] - radius / 111.2, lat_max=center_point['lat'] + radius / 111.2, lon_min=center_point['lon'] - radius / (111.2 * np.cos(center_point['lat'] * np.pi / 180)), lon_max=center_point['lon'] + radius / (111.2 * np.cos(center_point['lat'] * np.pi / 180)), ) ##### or set domain manually in deg N/E ##### '''domain = dict( lat_min = 0.0, lat_max = 20.0, lon_min = 0.0, lon_max = 20.0, )''' ##### set image size (should be squared) ##### ##### plotting area in pyngl can not exceed squared area even if plotting on rectangular images ##### ##### for obtaining rectangular plots on has to cut manually afterwards e.g. with pillow package ##### x_resolution = 800 y_resolution = 800 wks_res = Ngl.Resources() wks_res.wkWidth = x_resolution wks_res.wkHeight = y_resolution plot_name = 'contourplot_icon-eu-eps_tot_prec_{:02d}-{:02d}h_{}'.format(\ fcst_hours[0], fcst_hours[1], stat_processing) wks_type = 'png' wks = Ngl.open_wks(wks_type, path['base'] + path['plots'] + plot_name, wks_res) resources = Ngl.Resources( ) # create resources object containing all the plot settings resources.mpProjection = 'Hammer' # projection type resources.mpCenterLonF = (domain['lon_max'] + domain['lon_min'] ) / 2 # projection center point resources.mpCenterLatF = (domain['lat_max'] + domain['lat_min']) / 2 resources.mpLimitMode = 'latlon' resources.mpMinLonF = domain['lon_min'] resources.mpMaxLonF = domain['lon_max'] resources.mpMinLatF = domain['lat_min'] resources.mpMaxLatF = domain['lat_max'] ##### set plot area ##### resources.nglMaximize = False resources.vpXF = 0.05 resources.vpYF = 0.9 resources.vpWidthF = 0.7 resources.vpHeightF = 0.7 ##### set all map plot settings ##### resources.mpFillOn = True # turn on filled map areas resources.mpFillColors = [ 'pink', 'blue', 'white', 'white' ] # set colors for [FillValue, Ocean, Land , InlandWater] resources.mpDataBaseVersion = 'MediumRes' # quality of national borders resources.mpDataSetName = 'Earth..4' resources.mpOutlineBoundarySets = 'national' #resources.mpDataBaseVersion = 'HighRes' #resources.mpDataResolution = 'Fine' resources.mpGeophysicalLineThicknessF = 7.0 * x_resolution / 1000 # keep borders thickness resolution-independent resources.mpNationalLineThicknessF = 7.0 * x_resolution / 1000 #resources.mpGridAndLimbDrawOrder = 'postdraw' resources.mpGridAndLimbOn = False # turn off geographic coordinates grid #resources.mpLimbLineColor = 'black' #resources.mpLimbLineThicknessF = 10 #resources.mpGridLineColor = 'black' #resources.mpGridLineThicknessF = 1.0 #resources.mpGridSpacingF = 1 resources.mpPerimOn = True # turn on perimeter around plot resources.mpPerimLineColor = 'black' resources.mpPerimLineThicknessF = 8.0 * x_resolution / 1000 # keep perimeter thickness resolution-independent resources.tmXBOn = False # turn off location ticks around plot resources.tmXTOn = False resources.tmYLOn = False resources.tmYROn = False resources.sfDataArray = data_processed # data input file to plot resources.sfXArray = clon # array with cell center locations resources.sfYArray = clat resources.sfXCellBounds = vlon # array with cell vertices locations resources.sfYCellBounds = vlat resources.sfMissingValueV = 9999 # in case you want to mask values resources.cnFillOn = True resources.cnFillMode = 'CellFill' #resources.cnCellFillEdgeColor = 'black' # uncomment this for plotting the cell edges resources.cnMissingValFillColor = 'black' resources.cnFillPalette = 'WhiteBlueGreenYellowRed' # color palette resources.cnLevelSelectionMode = 'ManualLevels' minlevel = 0.0 # min level of colorbar maxlevel = 50.0 # max level of colorbar numberoflevels = 250 # number of levels of colorbar, max. 250 with this color palette resources.cnMinLevelValF = minlevel resources.cnMaxLevelValF = maxlevel resources.cnLevelSpacingF = (maxlevel - minlevel) / numberoflevels resources.cnLinesOn = False # turn off contour lines resources.cnLineLabelsOn = False # turn off contour labels ##### set resources for a nice colorbar ##### resources.lbLabelBarOn = True resources.lbAutoManage = False resources.lbOrientation = 'vertical' resources.lbLabelOffsetF = 0.05 #resources.lbBoxMinorExtentF = 0.2 resources.lbLabelStride = 25 # print a tick every 25 levels resources.lbLabelFontHeightF = 0.016 resources.lbBoxSeparatorLinesOn = False resources.lbBoxLineThicknessF = 4.0 #resources.lbBoxEndCapStyle = 'TriangleBothEnds' resources.lbLabelAlignment = 'BoxCenters' resources.lbTitleString = 'mm' resources.lbTitleFontHeightF = 0.016 resources.lbTitlePosition = 'Right' resources.lbTitleDirection = 'Across' resources.lbTitleAngleF = 90.0 resources.lbTitleExtentF = 0.1 resources.lbTitleOffsetF = -0.15 resources.nglFrame = False # hold on frame because will plot text afterwards on same plot Ngl.contour_map(wks, data_processed, resources) # plot the actual plot ##### plot title text ##### text = '{:02d}-{:02d}h Total Precipitation {}, ICON-EPS run {:02}.{:02}.{} {:02}Z'.format(\ fcst_hours[0], fcst_hours[1], stat_processing,\ date['day'], date['month'], date['year'], date['hour']) x = 0.5 y = 0.95 text_res_1 = Ngl.Resources() text_res_1.txFontHeightF = 0.018 text_res_1.txJust = 'TopCenter' Ngl.text_ndc(wks, text, x, y, text_res_1) Ngl.frame(wks) # advance frame Ngl.destroy( wks ) # delete workspace to free memory, relevant if plotting various plots in one script print('plotted "{}.png"'.format(plot_name)) return
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
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 lres.lbTitleFontHeightF = 0.01 # title font height Ngl.labelbar_ndc (wks,4,labels,0.23,0.15,lres) Ngl.frame(wks) # Advance the frame. Ngl.end()
def draw_e3sm_bgt (ptype,cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs,casedir,dpsc): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = "Red" mkres.gsMarkerSizeF = 15. infiles = ["" for x in range(ncases)] ncdfs = ["" for x in range(ncases)] nregions = nsite varis = [ "DCQ","DCCLDLIQ","DCCLDICE","PTEQ","PTTEND","DTCOND"] nvaris = len(varis) cscale = [1E8, 1E8, 1E8, 1E8, 1E4, 1E4] chscale = ['1E-8', '1E-8', '1E-8', '1E-8', '1E-4', '1E-4'] plote3smbgt=["" for x in range(nsite*ncases)] for ire in range (0, nsite): for im in range (0,ncases): if not os.path.exists(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N'): os.mkdir(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N') plotname = casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N/E3SM_Budgets_'+casenames[im]+"_"+str(lons[ire])+"E_"+str(lats[ire])+"N_"+cseason plote3smbgt[im+ncases*ire] = 'E3SM_Budgets_'+casenames[im]+"_"+str(lons[ire])+"E_"+str(lats[ire])+"N_"+cseason wks= Ngl.open_wks(ptype,plotname) Ngl.define_colormap(wks,"radar") plot = [] res = Ngl.Resources() res.nglDraw = False res.nglFrame = False res.lgLabelFontHeightF = .012 # change font height res.lgPerimOn = False # no box around res.vpWidthF = 0.30 # set width and height res.vpHeightF = 0.30 # res.txFontHeightF = .01 # res.vpXF = 0.04 # res.vpYF = 0.30 res.tmYLLabelFont = 12 res.tmXBLabelFont = 12 res.tmXBLabelFontHeightF = 0.01 res.tmXBLabelFontThicknessF = 1.0 res.xyMarkLineMode = "MarkLines" res.xyLineThicknesses = [2.0, 2.0, 2.0, 2.0, 2.0, 2.0,2.,2.,2.,2.,2,2,2,2,2,2,2] res.xyLineColors = np.arange(2,16,2) res.xyDashPatterns = np.arange(0,24,1) res.xyMarkers = np.arange(16,40,1) res.xyMarkerSizeF = 0.005 res.xyMarkerColors = np.arange(2,16,2) res.pmLegendDisplayMode = "ALWAYS" res.pmLegendSide = "top" # Change location of res.pmLegendParallelPosF = 0.6 # move units right res.pmLegendOrthogonalPosF = -0.55 # more neg = down res.pmLegendWidthF = 0.2 # Decrease width res.pmLegendHeightF = 0.1 # Decrease height res.lgBoxMinorExtentF = 0.1 # Shorten the legend lines res.lgLabelFontHeightF = 0.015 # Change the font size res.lgPerimOn = True res.tiYAxisString = "PRESSURE" res.trYReverse = True pres = Ngl.Resources() pres.nglMaximize = True pres.wkWidth = 2000 pres.wkHeight = 2000 pres.nglFrame = False pres.txFont = 12 pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelTop = 0.93 for iv in range (0, nvaris): if (varis[iv] == "DCQ" ): if (dpsc[im] == "zm" ): budget_ends = ["MPDQ", "RVMTEND_CLUBB","ZMDQ", "EVAPQZM"] else: budget_ends = ["MPDQ", "RVMTEND_CLUBB"] nterms = len (budget_ends) if (varis[iv] == "DTCOND" ): if (dpsc[im] == "zm" ): budget_ends = ["STEND_CLUBB", "MPDT", "DPDLFT","ZMDT", "EVAPTZM", "ZMMTT"] else: budget_ends = ["STEND_CLUBB", "MPDT", "DPDLFT"] nterms = len (budget_ends) if (varis[iv] == "PTTEND") : budget_ends = ["DTCOND", "QRS", "QRL", "TTGW"] nterms = len (budget_ends) if (varis[iv] == "PTEQ") : if (dpsc[im] == "zm" ): budget_ends = ["MPDQ", "RVMTEND_CLUBB","ZMDQ", "EVAPQZM"] else: budget_ends = ["MPDQ", "RVMTEND_CLUBB"] nterms = len (budget_ends) if (varis[iv] == "DCCLDLIQ") : if (dpsc[im] == "zm" ): budget_ends = ["MPDLIQ", "RCMTEND_CLUBB", "DPDLFLIQ","ZMDLIQ"] else: budget_ends = ["MPDLIQ", "RCMTEND_CLUBB", "DPDLFLIQ"] nterms = len (budget_ends) if (varis[iv] == "DCCLDICE") : if (dpsc[im] == "zm" ): budget_ends = ["MPDICE", "RIMTEND_CLUBB", "DPDLFICE","ZMDICE"] else: budget_ends = ["MPDICE", "RIMTEND_CLUBB", "DPDLFICE"] nterms = len (budget_ends) ncdfs[im] = './data/'+cases[im]+'_site_location.nc' infiles[im]= filepath[im]+cases[im]+'/'+cases[im]+'_'+cseason+'_climo.nc' inptrs = Dataset(infiles[im],'r') # pointer to file1 lat=inptrs.variables['lat'][:] nlat=len(lat) lon=inptrs.variables['lon'][:] nlon=len(lon) ilev=inptrs.variables['lev'][:] nilev=len(ilev) ncdf= Dataset(ncdfs[im],'r') n =ncdf.variables['n'][:] idx_cols=ncdf.variables['idx_cols'][:,:] ncdf.close() A_field = np.zeros((nterms,nilev),np.float32) theunits=str(chscale[iv])+"x"+inptrs.variables[varis[iv]].units res.tiMainString = varis[iv]+" "+theunits for it in range(0, nterms): for subc in range( 0, n[ire]): varis_bgt= budget_ends[it] npoint=idx_cols[ire,n[subc]-1]-1 tmp=inptrs.variables[varis_bgt][0,:,npoint] #/n[ire] tmp=tmp*cscale[iv] if (varis_bgt == "MPDT" or varis_bgt == "STEND_CLUBB" ): tmp=tmp/1004 A_field[it,:] = (A_field[it,:]+tmp[:]/n[ire]).astype(np.float32 ) inptrs.close() res.xyExplicitLegendLabels = budget_ends[:] p = Ngl.xy(wks,A_field,ilev,res) plot.append(p) xp=np.mod(iv,2) yp=int(iv/2) Ngl.panel(wks,plot[:],[nvaris/2,2],pres) txres = Ngl.Resources() txres.txFont = _Font txres.txFontHeightF = 0.020 Ngl.text_ndc(wks,casenames[im]+" BUDGET at" +str(lons[ire])+"E,"+str(lats[ire])+"N",0.5,0.95,txres) Ngl.frame(wks) Ngl.destroy(wks) return (plote3smbgt)