def create_map(wks): #---Map resources res = Ngl.Resources() # map resources res.nglDraw = False # don't draw map res.nglFrame = False # don't advance frame res.mpDataBaseVersion = "MediumRes" # better map outlines res.mpLimitMode = "LatLon" res.mpMaxLatF = -20 # select subregion res.mpMinLatF = -62 res.mpMinLonF = -78 res.mpMaxLonF = -25 res.mpOutlineOn = True res.mpGridAndLimbOn = False res.mpFillOn = True res.mpLandFillColor = "beige" res.mpOceanFillColor = "paleturquoise1" res.mpInlandWaterFillColor = "paleturquoise1" res.tmYROn = True # Turn on right tickmarks res.tmXTOn = True # Turn on top tickmarks res.tiMainString = "Trajectories colored by salinity (ppt)" res.tiMainFontHeightF = 0.02 map = Ngl.map(wks,res) # Draw map. return map
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
mpres.nglFrame = False #-- do it later after adding subtitles. mpres.mpGridAndLimbOn = False #-- don't draw grid lines mpres.mpGeophysicalLineThicknessF = 2. #-- map outlines thicker #mpres.pmTitleDisplayMode = "Always" #mpres.mpLimitMode = "LatLon" #-- map limit mode #mpres.mpMinLonF = -60. #-- minimum lon #mpres.mpMaxLonF = 60. #-- maximum lon #mpres.mpMinLatF = 0. #-- minimum lat #mpres.mpMaxLatF = 90. #-- maximum lat mpres.tiMainString = "ICON data - gsSegments" #-- title string #-- create map map = Ngl.map(wks1,mpres) Ngl.draw(map) #-- draw the empty map #-- assign array which will hold the color indices of the cells colors = range(3,ncol+3) #-- create color indices gscolors = np.ones((ncells,),dtype=np.int) #-- assign array containing zeros gscolors = -1*np.array(gscolors) #-- initialize to transparent color #-- lowest level polygons vlow = Ngl.ind(var < levels[0]) for k in xrange(0,len(vlow)-1): if not np.all(var[vlow] == var._FillValue): for kk in vlow: gscolors[kk] = 3 print "finished level 0 -- " + str(len(vlow)) + " polygons considered - gscolors " + str(colors[0])
res.mpMinLonF = lontr res.mpMaxLonF = lonbl res.mpMinLatF = lattr res.mpMaxLatF = latbl res.mpOutlineBoundarySets = "AllBoundaries" res.mpNationalLineColor = -1 res.mpNationalLineThicknessF = 2.0 res.mpGeophysicalLineColor = -1 res.mpGeophysicalLineThicknessF = 2.0 res.mpGridLatSpacingF = 5.0 res.mpGridLonSpacingF = 5.0 res.mpGridLineThicknessF = 2.0 res.mpGridLineColor = colour res.cnMonoLineColor = True grid_plot = ngl.map(wks, res) ngl.maximize_plot(wks, grid_plot) ngl.draw(grid_plot) ngl.frame(wks) ngl.destroy(wks) del res os.system('mogrify -trim grid_' + colour + '_' + region + '.png') # if region == "WA" or region == "unknownWA": # os.system('mogrify -trim grid_'+colour+'_'+region+'.png') # os.system('mogrify -resize 886x600 grid_'+colour+'_'+region+'.png') # elif region == "EA" or region == "unknownEA": # os.system('mogrify -trim grid_'+colour+'_'+region+'.png')
# This example produces two visualizations: # 1.) Cylindrical Equidistant projection # 2.) Mollweide projection # # Notes: # import Ngl wks_type = "ps" wks = Ngl.open_wks(wks_type,"map1") projections = ["CylindricalEquidistant","Mollweide"] mpres = Ngl.Resources() # Indicate you want to set some # resources. mpres.mpShapeMode = "FreeAspect" # Allow the aspect ratio to be # changed. mpres.vpWidthF = 0.8 # Make the aspect ratio square. mpres.vpHeightF = 0.8 mpres.pmTitleDisplayMode = "Always" # Force the title to appear. for i in xrange(len(projections)): mpres.mpProjection = projections[i] mpres.tiMainString = projections[i] map = Ngl.map(wks,mpres) Ngl.end()
wks_type = "ps" wks = Ngl.open_wks(wks_type,"map2") mpres = Ngl.Resources() mpres.nglFrame = False # Don't advance frame after plot is drawn. mpres.nglDraw = False # Don't draw plot just yet. mpres.mpProjection = "Orthographic" mpres.mpCenterLatF = 30. mpres.mpCenterLonF = 160. mpres.mpCenterRotF = 60. mpres.mpLabelsOn = False mpres.mpPerimOn = False map = Ngl.map(wks,mpres) # Create map. gsres = Ngl.Resources() gsres.gsLineColor = "black" gsres.gsLineThicknessF = 2.0 gsres.gsLineLabelFont = "helvetica-bold" gsres.gsLineLabelFontHeightF = 0.02 gsres.gsLineLabelFontColor = "black" gsres.gsFillIndex = 0 gsres.gsEdgesOn = False # Tropical zone gsres.gsFillColor = 87
#-- set resources res = Ngl.Resources() res.nglDraw = False #-- don't draw the plot yet res.nglFrame = False #-- don't advance the frame yet res.mpFillOn = True res.mpOutlineOn = False res.mpOceanFillColor = "Transparent" res.mpLandFillColor = "Gray80" res.mpInlandWaterFillColor = "Gray80" res.mpGridAndLimbOn = False #-- don't draw grid lines res.pmTickMarkDisplayMode = "Always" #-- turn on map tickmark #-- create the map, but don't draw it yet map = Ngl.map(wks, res) #---------------------------------------------------------------- #-- polyline coordinates (Germany) #---------------------------------------------------------------- x = [6., 15., 15., 6., 6.] y = [47.5, 47.5, 54.5, 54.5, 47.5] #-- polyline resources plres = Ngl.Resources() plres.gsLineThicknessF = 2.0 #-- set line thickness plres.gsLineColor = "red" #-- set line color #-- add polyline to map box_1 = Ngl.add_polyline(wks, map, x, y, plres)
def make_test(wrf_file=None, fixed_case=None): if wrf_file is not None: ncfile = NetCDF(wrf_file) lats, lons, proj_params = get_proj_params(ncfile) proj = getproj(lats=lats, lons=lons, **proj_params) name_suffix = basename(wrf_file) elif fixed_case is not None: name_suffix = fixed_case if fixed_case == "south_rot": lats, lons, proj = nz_proj() elif fixed_case == "arg_rot": lats, lons, proj = argentina_proj() elif fixed_case == "south_polar": lats, lons, proj = south_polar_proj() elif fixed_case == "north_polar": lats, lons, proj = north_polar_proj() elif fixed_case == "dateline_rot": lats, lons, proj = dateline_rot_proj() print("wrf proj4: {}".format(proj.proj4())) if PYNGL: # PyNGL plotting wks_type = bytes("png") wks = Ngl.open_wks(wks_type, bytes("pyngl_{}".format(name_suffix))) mpres = proj.pyngl() map = Ngl.map(wks, mpres) Ngl.delete_wks(wks) if BASEMAP: # Basemap plotting fig = plt.figure(figsize=(10, 10)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # Define and plot the meridians and parallels min_lat = np.amin(lats) max_lat = np.amax(lats) min_lon = np.amin(lons) max_lon = np.amax(lons) parallels = np.arange(np.floor(min_lat), np.ceil(max_lat), (max_lat - min_lat) / 5.0) meridians = np.arange(np.floor(min_lon), np.ceil(max_lon), (max_lon - min_lon) / 5.0) bm = proj.basemap() bm.drawcoastlines(linewidth=.5) #bm.drawparallels(parallels,labels=[1,1,1,1],fontsize=10) #bm.drawmeridians(meridians,labels=[1,1,1,1],fontsize=10) print("basemap proj4: {}".format(bm.proj4string)) plt.savefig("basemap_{}.png".format(name_suffix)) plt.close(fig) if CARTOPY: # Cartopy plotting fig = plt.figure(figsize=(10, 10)) ax = plt.axes([0.1, 0.1, 0.8, 0.8], projection=proj.cartopy()) print("cartopy proj4: {}".format(proj.cartopy().proj4_params)) ax.coastlines('50m', linewidth=0.8) #print proj.x_extents() #print proj.y_extents() ax.set_xlim(proj.cartopy_xlim()) ax.set_ylim(proj.cartopy_ylim()) ax.gridlines() plt.savefig("cartopy_{}.png".format(name_suffix)) plt.close(fig)
setlist.wkColorMap = colormap #-- set color map to new colormap array setlist.wkBackgroundColor = 'white' #-- has to be set when wkColorMap is set to colormap array setlist.wkForegroundColor = 'black' #-- has to be set when wkColorMap is set to colormap array Ngl.set_values(wks1,setlist) #-- set map resources mpres = Ngl.Resources() mpres.nglDraw = False #-- turn off plot draw and frame advance. We will mpres.nglFrame = False #-- do it later after adding subtitles. mpres.mpGridAndLimbOn = False mpres.mpGeophysicalLineThicknessF = 2. mpres.pmTitleDisplayMode = 'Always' mpres.tiMainString = 'PyNGL: unstructured grid ICON' #-- create only a map map = Ngl.map(wks1,mpres) Ngl.draw(map) #-- assign and initialize array which will hold the color indices of the cells gscolors = -1*(np.ones((ncells,),dtype=np.int)) #-- assign array containing zeros; init to transparent: -1 #-- set color index of all cells in between levels for m in xrange(0,nlevs): vind = [] #-- empty list for color indices for i in xrange(0,ncells-1): if (varM[i] >= levels[m] and varM[i] < levels[m+1]): gscolors[i] = colors[m+1] vind.append(i) print 'finished level %3d' % m , ' -- %5d ' % len(vind) , ' polygons considered - gscolors %3d' % colors[m] del vind
res.mpOutlineOn = True res.mpLandFillColor = 2 res.mpOceanFillColor = 3 res.mpGridAndLimbOn = False res.vpXF = 0.05 res.vpYF = 0.95 res.vpWidthF = 0.8 res.vpHeightF = 0.8 res.tmXBTickStartF = -75 res.tmXBTickEndF = -25 res.tmYROn = True res.tmXTOn = True res.tmXBLabelFontHeightF = 0.02 res.tmYLLabelFontHeightF = 0.02 res.mpProjection = "CylindricalEquidistant" map = Ngl.map(wks,res) # Draw map. # # Main title. # txres = Ngl.Resources() txres.txFontHeightF = 0.025 txres.txFontColor = 1 txres.txFont = 22 Ngl.text_ndc(wks,"Trajectories colored by salinity (ppt)",0.52,0.90,txres) del txres # # Manually draw a labelbar using colors 4-12. #
respn.cnLowLabelsOn = True respn.cnLowLabelFontHeightF = 0.01 respn.cnHighLabelFontHeightF = 0.01 respn.cnLowLabelPerimOn = False respn.cnHighLabelPerimOn = False respn.cnConpackParams = ["HLX:128,HLY:128"] if model_name == "hrdps": respn.cnConpackParams = ["HLX:256,HLY:256"] respn.cnLowLabelBackgroundColor = "Transparent" respn.cnHighLabelBackgroundColor = "Transparent" respn.cnLevelSpacingF = 2 respn.cnLineLabelFontHeightF = 0.006 respn.cnLineLabelBackgroundColor = "Transparent" respn.cnInfoLabelOn = False map_plot = Ngl.map(wks, resmp) plot_fill = Ngl.contour(wks, 3.6E6 * field[:, :, 0], resources) #plt.hist(3.6E6*field[:,:,0].flatten(),range(1,20)) #plt.savefig('RC.png') fst_data = read_fst(file, "PN", 0, fhour, yy) field = fst_data[0] lat = fst_data[1] lon = fst_data[2] respn.sfXArray = lon respn.sfYArray = lat plot_line = Ngl.contour(wks, field[:, :, 0], respn) Ngl.overlay(map_plot, plot_fill)
res.nglDraw = False # Zoom in on France. res.mpLimitMode = "LatLon" res.mpMinLatF = 41 res.mpMaxLatF = 51.1 res.mpMinLonF = -5.15 res.mpMaxLonF = 9.6 res.mpFillOn = False res.mpOutlineOn = False res.tiMainString = filename res.tiMainFontHeightF = 0.015 # Make font slightly smaller. plot = Ngl.map(wks, res) # Just create map, don't draw it. #************************************************* # Section to add polylines to map. #************************************************* plres = Ngl.Resources() # resources for polylines plres.gsLineColor = "navyblue" plres.gsLineThicknessF = 2.0 # default is 1.0 plres.gsSegments = segments[:, 0] # This can be slow. Need to investigate. lnid = Ngl.add_polyline(wks, plot, lon, lat, plres) Ngl.draw(plot) # This draws map and attached polylines Ngl.frame(wks) # Advance frame.
#---Attach blank plot with special labels to map plot, and return resBMP = Ngl.Resources() resBMP.mpProjection = "CylindricalEquidistant" # Change the map projection. resBMP.mpCenterLonF = 0. # Rotate the projection. resBMP.mpGridAndLimbOn = False resBMP.pmLabelBarDisplayMode = "Always" resBMP.lbPerimOn = False resBMP.nglDraw = False resBMP.nglFrame = False resBMP.mpOutlineBoundarySets = "AllBoundaries" resBMP.mpLimitMode = "LatLon" # Limit the map view. resBMP.mpMinLonF = plotstartlon resBMP.mpMaxLonF = plotendlon resBMP.mpMinLatF = plotstartlat resBMP.mpMaxLatF = plotendlat plot.append(Ngl.map(wks, resBMP)) else: resMP = Ngl.Resources() #resMP = initcontourplot(resMP,plotstartlat,plotstartlon,plotendlat,plotendlon,Tlats.values,Tlons.values) #resMP.nglYAxisType = "LinearAxis" #resMP.nglXAxisType = "LinearAxis" resMP.cnFillOn = True resMP.cnFillMode = "AreaFill" resMP.gsnAddCyclic = True resMP.MissingValFillColor = "white" resMP.sfMissingValueV = -9999 resMP.mpGridMaskMode = "MaskLand" resMP.nglDraw = False resMP.nglFrame = False
def ens_spread_map(var1var2): recoverpath = dict(base = '/', temp = 'data/additional_data/temp/{}/'.format(ex_op_str)) # load all dictionaries and strings from json file # json_filename = 'ensemble_spread_maps_{}_dicts_strings.json'.format(var1var2) with open(recoverpath['base'] + recoverpath['temp'] + json_filename, 'r') as f: path, domain, variable1, variable2, model, run, hour = json.load(f) # load numpy arrays # numpyarrays_filename = 'ensemble_spread_maps_{}_ndarrays_outofloop.npz'.format(var1var2) with open(path['base'] + path['temp'] + numpyarrays_filename, 'rb') as f: with np.load(f) as loadedfile: clat = loadedfile['clat'] clon = loadedfile['clon'] vlat = loadedfile['vlat'] vlon = loadedfile['vlon'] ll_lat = loadedfile['ll_lat'] ll_lon = loadedfile['ll_lon'] numpyarrays_filename = 'ensemble_spread_maps_{}_ndarrays_withinloop.npz'.format(var1var2) with open(recoverpath['base'] + recoverpath['temp'] + numpyarrays_filename, 'rb') as f: with np.load(f) as loadedfile: data_array1 = loadedfile['data_array1'] data_array2 = loadedfile['data_array2'] #print('loaded all vars') # example plot_name: icon-eu-eps_2020070512_mslp_mean_spread_europe_000h plot_name = '{}_{:4d}{:02d}{:02d}{:02d}_{}_{}_{:03d}h'.format( model, run['year'], run['month'], run['day'], run['hour'], var1var2, domain['name'], hour) # plot basic map with borders # wks_res = Ngl.Resources() wks_res.wkWidth = domain['plot_width'] wks_res.wkHeight = domain['plot_width'] # the whitespace above and below the plot will be cut afterwards filename_colorpalette = 'colormap_WhiteBeigeGreenBlue_12.txt' with open(path['base'] + path['colorpalette'] + filename_colorpalette, 'r') as f: lines = f.readlines() rgb_colors = [] rgb_colors.append([1, 1, 1]) rgb_colors.append([0, 0, 0]) rgb_colors.append([.5, .5, .5]) for line in lines: rgb_colors.append([float(line[0:3])/255, float(line[4:7])/255, float(line[8:11])/255]) rgb_colors.append(rgb_colors[-1]) wks_res.wkColorMap = np.array(rgb_colors) if variable1['name'] == 'gph_500hPa' : levels1 = np.arange(0, 12.1, 1) elif variable1['name'] == 'mslp' : levels1 = np.arange(0, 12.1, 1) elif variable1['name'] == 't_850hPa' : levels1 = np.arange(0, 6.1, 0.5) wks_type = 'png' wks = Ngl.open_wks(wks_type, path['base'] + path['plots'] + plot_name, wks_res) mpres = Ngl.Resources() mpres.mpProjection = domain['projection'] if domain['limits_type'] == 'radius': mpres.mpLimitMode = 'LatLon' mpres.mpCenterLonF = domain['centerlon'] mpres.mpCenterLatF = domain['centerlat'] cutout_plot = dict( lat_min = float(np.where(domain['centerlat'] - domain['radius'] / 111.2 < -90, -90, domain['centerlat'] - domain['radius'] / 111.2)), lat_max = float(np.where(domain['centerlat'] + domain['radius'] / 111.2 > 90, 90, domain['centerlat'] + domain['radius'] / 111.2)), ) cutout_plot['lon_min'] = float(np.where(cutout_plot['lat_min'] <= -90 or cutout_plot['lat_max'] >= 90, 0, domain['centerlon'] - domain['radius'] \ / (111.2 * np.cos(domain['centerlat']*np.pi/180)))) cutout_plot['lon_max'] = float(np.where(cutout_plot['lat_min'] <= -90 or cutout_plot['lat_max'] >= 90, 360, domain['centerlon'] + domain['radius'] \ / (111.2 * np.cos(domain['centerlat']*np.pi/180)))) mpres.mpMinLonF = cutout_plot['lon_min'] mpres.mpMaxLonF = cutout_plot['lon_max'] mpres.mpMinLatF = cutout_plot['lat_min'] mpres.mpMaxLatF = cutout_plot['lat_max'] elif domain['limits_type'] == 'deltalatlon': mpres.mpLimitMode = 'LatLon' mpres.mpCenterLonF = 0 mpres.mpCenterLatF = 0 mpres.mpMinLonF = domain['centerlon'] - domain['deltalon_deg'] mpres.mpMaxLonF = domain['centerlon'] + domain['deltalon_deg'] mpres.mpMinLatF = domain['centerlat'] - domain['deltalat_deg'] mpres.mpMaxLatF = domain['centerlat'] + domain['deltalat_deg'] elif domain['limits_type'] == 'angle': mpres.mpLimitMode = 'Angles' mpres.mpCenterLonF = domain['centerlon'] mpres.mpCenterLatF = domain['centerlat'] mpres.mpLeftAngleF = domain['angle'] mpres.mpRightAngleF = domain['angle'] mpres.mpTopAngleF = domain['angle'] mpres.mpBottomAngleF = domain['angle'] mpres.nglMaximize = False mpres.vpXF = 0.001 mpres.vpYF = 1.00 mpres.vpWidthF = 0.88 mpres.vpHeightF = 1.00 mpres.mpMonoFillColor = 'True' mpres.mpFillColor = -1 mpres.mpFillOn = True mpres.mpGridAndLimbOn = False mpres.mpGreatCircleLinesOn = False mpres.mpDataBaseVersion = 'MediumRes' mpres.mpDataSetName = 'Earth..4' mpres.mpOutlineBoundarySets = 'national' mpres.mpGeophysicalLineColor = 'black' mpres.mpNationalLineColor = 'black' mpres.mpGeophysicalLineThicknessF = 1.0 * domain['plot_width'] / 1000 mpres.mpNationalLineThicknessF = 1.0 * domain['plot_width'] / 1000 mpres.mpPerimOn = True mpres.mpPerimLineColor = 'black' mpres.mpPerimLineThicknessF = 6.0 * domain['plot_width'] / 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 # settings for variable1 / shading # v1res = Ngl.Resources() v1res.sfDataArray = data_array1 v1res.sfXArray = clon v1res.sfYArray = clat v1res.sfXCellBounds = vlon v1res.sfYCellBounds = vlat v1res.sfMissingValueV = 9999 v1res.cnMissingValFillColor = 'Gray80' v1res.cnLinesOn = False # Turn off contour lines. v1res.cnFillOn = True v1res.cnFillMode = 'CellFill' #v1res.cnFillOpacityF = 0.5 #v1res.cnFillDrawOrder = 'Predraw' 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.14 # 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' #if variable1['name'] == 'prec_rate' : # 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 = 'ExternalEdges' if variable2['name'] == 'mslp': v1res.lbLabelStride = 1 elif variable2['name'] == 'gph_500hPa': v1res.lbLabelStride = 1 elif variable2['name'] == 't_850hPa': v1res.lbLabelStride = 2 v1res.nglFrame = False v1res.nglDraw = False # settings for variable2 / thin contourlines # v2res = Ngl.Resources() v2res.sfDataArray = data_array2 v2res.sfXArray = ll_lon v2res.sfYArray = ll_lat v2res.sfMissingValueV = 9999 #v2res.trGridType = 'TriangularMesh' v2res.cnFillOn = False v2res.cnLinesOn = True v2res.cnLineLabelsOn = True v2res.cnLineLabelInterval = 1 v2res.cnLineLabelPlacementMode = 'Constant' v2res.cnLineDashSegLenF = 0.25 v2res.cnLabelDrawOrder = 'PostDraw' # necessary to make everything visible v2res.cnLineThicknessF = 3.0 * domain['plot_width'] / 1000 v2res.cnInfoLabelOn = False v2res.cnSmoothingOn = False v2res.cnSmoothingDistanceF = 0.01 v2res.cnSmoothingTensionF = 0.1 if variable2['name'] == 'mslp': v2res.cnLevelSpacingF = 2 v2res.cnLineLabelFontHeightF = 0.008 v2res.cnLineDashSegLenF = 0.18 v2res.cnLineLabelInterval = 2 elif variable2['name'] == 'gph_500hPa': v2res.cnLevelSpacingF = 4 v2res.cnLineLabelFontHeightF = 0.008 elif variable2['name'] == 't_850hPa': v2res.cnLevelSpacingF = 2 v2res.cnLineLabelFontHeightF = 0.009 v2res.cnLineDashSegLenF = 0.18 v2res.cnLevelSelectionMode = 'ManualLevels' #v2res.cnLevels = levels2 #v2res.cnRasterSmoothingOn = True v2res.nglFrame = False v2res.nglDraw = False # settings for variable2 / thick contourlines # v3res = Ngl.Resources() v3res.sfDataArray = data_array2 v3res.sfXArray = ll_lon v3res.sfYArray = ll_lat v3res.sfMissingValueV = 9999 #v3res.trGridType = 'TriangularMesh' v3res.cnFillOn = False v3res.cnLinesOn = True v3res.cnLineLabelsOn = True v3res.cnLineLabelInterval = 1 v3res.cnLineLabelPlacementMode = 'Constant' v3res.cnLineDashSegLenF = 0.25 v3res.cnLabelDrawOrder = 'PostDraw' # necessary to make everything visible v3res.cnLineThicknessF = 5.0 * domain['plot_width'] / 1000 v3res.cnLineLabelFontHeightF = 0.010 v3res.cnInfoLabelOn = False v3res.cnSmoothingOn = False #v3res.cnSmoothingDistanceF = 0.01 #v3res.cnSmoothingTensionF = 0.1 v3res.cnLevelSelectionMode = 'ManualLevels' #v3res.cnLevels = levels2 #v3res.cnRasterSmoothingOn = True if variable2['name'] == 'mslp': v3res.cnLevelSpacingF = 10 v3res.cnLineLabelFontHeightF = 0.008 v3res.cnLineDashSegLenF = 0.18 v3res.cnLineLabelInterval = 2 elif variable2['name'] == 'gph_500hPa': v3res.cnLevelSpacingF = 16 v3res.cnLineLabelFontHeightF = 0.008 v3res.cnLevelSelectionMode = 'ExplicitLevels' v3res.cnLevels = np.arange(520, 600, 16) elif variable2['name'] == 't_850hPa': v3res.cnLevelSpacingF = 6 v3res.cnLineLabelFontHeightF = 0.009 v3res.cnLineDashSegLenF = 0.18 v3res.nglFrame = False v3res.nglDraw = False # settings for unit text # text_str = variable1['unit'] text_res_1 = Ngl.Resources() text_res_1.txFontColor = 'black' text_res_1.txFontHeightF = 0.013 #text_x = 0.965 text_x = 0.972 text_y = 0.837 #0.865 # put everything together # basic_map = Ngl.map(wks, mpres) v1plot = Ngl.contour(wks, data_array1, v1res) v2plot = Ngl.contour(wks, data_array2, v2res) v3plot = Ngl.contour(wks, data_array2, v3res) Ngl.overlay(basic_map, v1plot) Ngl.overlay(basic_map, v2plot) Ngl.overlay(basic_map, v3plot) Ngl.draw(basic_map) Ngl.text_ndc(wks, text_str, text_x, text_y, text_res_1) Ngl.frame(wks) Ngl.delete_wks(wks) # 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() return
def double_contourplot(var1var2, model): recoverpath = dict(base='/', temp='data/additional_data/temp/{}/'.format(ex_op_str)) # load all dictionaries and strings from json file # json_filename = 'deterministic_overview_maps_{}_{}_dicts_strings.json'.format( model, var1var2) with open(recoverpath['base'] + recoverpath['temp'] + json_filename, 'r') as f: path, domain, variable1, variable2, run, hour = json.load(f) # load numpy arrays # if variable1['load_global_field']: numpyarrays_filename = 'deterministic_overview_maps_{}_{}_ndarrays_outofloop.npz'.format( model, var1var2) if model == 'icon-eu-det': with open(path['base'] + path['temp'] + numpyarrays_filename, 'rb') as f: with np.load(f) as loadedfile: clat = loadedfile['clat'] clon = loadedfile['clon'] elif model == 'icon-global-det': if not variable1['load_global_field']: with open(path['base'] + path['temp'] + numpyarrays_filename, 'rb') as f: with np.load(f) as loadedfile: ll_lat = loadedfile['ll_lat'] ll_lon = loadedfile['ll_lon'] elif variable2['name'] == '': with open(path['base'] + path['temp'] + numpyarrays_filename, 'rb') as f: with np.load(f) as loadedfile: clat = loadedfile['clat'] clon = loadedfile['clon'] vlat = loadedfile['vlat'] vlon = loadedfile['vlon'] else: with open(path['base'] + path['temp'] + numpyarrays_filename, 'rb') as f: with np.load(f) as loadedfile: clat = loadedfile['clat'] clon = loadedfile['clon'] vlat = loadedfile['vlat'] vlon = loadedfile['vlon'] ll_lat = loadedfile['ll_lat'] ll_lon = loadedfile['ll_lon'] numpyarrays_filename = 'deterministic_overview_maps_{}_{}_ndarrays_withinloop.npz'.format( model, var1var2) with open( recoverpath['base'] + recoverpath['temp'] + numpyarrays_filename, 'rb') as f: with np.load(f) as loadedfile: data_array1 = loadedfile['data_array1'] if variable2['name'] != '': data_array2 = loadedfile['data_array2'] #print('loaded all vars') if domain['limits_type'] == 'radius': margin_deg = 20 elif domain['limits_type'] == 'deltalatlon' or domain[ 'limits_type'] == 'angle': margin_deg = 20 if model == 'icon-eu-det': data_array1_cut, clat_cut, clon_cut, vlat_cut, vlon_cut = data_array1, clat, clon, None, None elif model == 'icon-global-det': data_array_dims = '2d' [data_array1_cut], clat_cut, clon_cut, vlat_cut, vlon_cut = \ cut_by_domain(domain, variable1['grid'], data_array_dims, [data_array1], clat, clon, vlat, vlon, margin_deg) if variable2['name'] != '': [data_array2_cut], ll_lat_cut, ll_lon_cut = \ cut_by_domain(domain, variable2['grid'], data_array_dims, [data_array2], ll_lat, ll_lon, None, None, margin_deg) #data_array2_cut, ll_lat_cut, ll_lon_cut = data_array2, ll_lat, ll_lon else: # if load_global_field == False if variable1['name'][:2] == 'pv'\ and variable1['name'][-1:] == 'K': iso_theta_value = float(variable1['name'][3:6]) data_array1_cut, clat_cut, clon_cut \ = calc_pv_on_theta(model, domain, variable1['grid'], run, hour, iso_theta_value) elif variable1['name'][:5] == 'theta'\ and variable1['name'][-3:] == 'PVU': iso_pv_value = float(variable1['name'][6:9]) data_array1_cut, clat_cut, clon_cut \ = calc_theta_on_pv(model, domain, variable1['grid'], run, hour, iso_pv_value) # example plot_name: icon-global-det_2020070512_prec_rate_mslp_europe_000h.png plot_name = '{}_{:4d}{:02d}{:02d}{:02d}_{}_{}_{:03d}h'.format( model, run['year'], run['month'], run['day'], run['hour'], var1var2, domain['name'], hour) # plot basic map with borders # if variable1['name'] == 'prec_rate'\ or variable1['name'] == 'prec_6h': filename_colorpalette = 'colorscale_prec_rate.txt' with open(path['base'] + path['colorpalette'] + filename_colorpalette, 'r') as f: lines = f.readlines() rgb_colors = [] rgb_colors.append([0, 0, 0, 0]) # color for under the lowest value, transparent for i, line in enumerate(lines): rgb_colors.append([ float(line[0:3]) / 255, float(line[4:7]) / 255, float(line[8:11]) / 255, 1 ]) rgb_colors.append( rgb_colors[-1] ) # add highest loaded color to color for over the highest value levels1 = ([0.1, 0.2, 0.3, 0.5, 1, 2, 3, 5, 10, 20, 30, 50]) lbStride_value = 1 elif variable1['name'] == 't_850hPa': rgb_colors = [] rgb_colors.append( [0, 0, 0]) # placeholder for color for under the lowest value for i in range(10): rgb_colors.append( list( cmasher.take_cmap_colors('cmr.flamingo', 10, cmap_range=(0.45, 0.88))[i])) for i in range(2, 12): rgb_colors.append( list( palettable.colorbrewer.sequential.Purples_9. get_mpl_colormap(N=14)(i)[:3])) rgb_colors.append(list(np.array([60, 53, 139]) / 255)) rgb_colors.append(list(np.array([65, 69, 171]) / 255)) rgb_colors.append(list(np.array([68, 86, 199]) / 255)) for i in range(2, 19): rgb_colors.append( list( palettable.colorbrewer.diverging.Spectral_10. get_mpl_colormap(N=19).reversed()(i)[:3])) for i in range(1, 11): rgb_colors.append( list( palettable.cartocolors.sequential.Burg_7.get_mpl_colormap( N=11).reversed()(i)[:3])) rgb_colors[0] = rgb_colors[ 1] # copy lowest loaded color to color for under the lowest value rgb_colors.append( rgb_colors[-1] ) # add highest loaded color to color for over the highest value rgb_colors[31] = list(np.array([255, 255, 160]) / 255) rgb_colors[32] = list(np.array([247, 230, 128]) / 255) levels1 = np.arange(-25, 25 + 1, 1) lbStride_value = 5 elif variable1['name'] == 'theta_e_850hPa': rgb_colors = [] rgb_colors.append( [0, 0, 0]) # placeholder for color for under the lowest value for i in range(5): rgb_colors.append( list( cmasher.take_cmap_colors('cmr.flamingo', 5, cmap_range=(0.65, 0.93))[i])) for i in range(4, 13): rgb_colors.append( list( palettable.colorbrewer.sequential.Purples_9. get_mpl_colormap(N=16)(i)[:3])) for i in range(26): rgb_colors.append( list( palettable.colorbrewer.diverging.Spectral_10. get_mpl_colormap(N=26).reversed()(i)[:3])) for i in range(1, 11): rgb_colors.append( list( palettable.cartocolors.sequential.Burg_7.get_mpl_colormap( N=11).reversed()(i)[:3])) for i in range(2, 2 + 5): rgb_colors.append( list( palettable.scientific.sequential.Turku_10.get_mpl_colormap( N=12).reversed()(i)[:3])) rgb_colors[0] = rgb_colors[ 1] # copy lowest loaded color to color for under the lowest value rgb_colors.append( rgb_colors[-1] ) # add highest loaded color to color for over the highest value rgb_colors[27] = list(np.array([255, 255, 160]) / 255) rgb_colors[28] = list(np.array([247, 237, 128]) / 255) levels1 = np.arange(-20, 90 + 1, 2) lbStride_value = 5 elif variable1['name'] == 'wind_300hPa': rgb_colors = [] rgb_colors.append([0, 0, 0, 0]) # color for under the lowest value, transparent for i in range(1, 8): rgb_colors.append( list( palettable.cmocean.sequential.Ice_10.get_mpl_colormap( N=10).reversed()(i)[:3]) + [1]) rgb_colors.append( rgb_colors[-1] ) # add highest loaded color to color for over the highest value levels1 = (list(range(120, 330 + 1, 30))) lbStride_value = 1 elif variable1['name'] == 'cape_ml': rgb_colors = [] rgb_colors.append([0, 0, 0, 0]) # color for under the lowest value, transparent for i in range(2, 7): rgb_colors.append( list( palettable.scientific.sequential.Tokyo_7.get_mpl_colormap( N=7)(i)[:3]) + [1]) for i in range(1, 17, 3): rgb_colors.append( list( palettable.cmocean.sequential.Thermal_20.get_mpl_colormap( N=22).reversed()(i)[:3]) + [1]) for i in range(9, 18, 4): rgb_colors.append( list( palettable.cmocean.sequential.Ice_20.get_mpl_colormap( N=20)(i)[:3]) + [1]) rgb_colors.append( rgb_colors[-1] ) # add highest loaded color to color for over the highest value rgb_colors[1] = list(np.array([138, 98, 110]) / 255) + [1] rgb_colors[10] = list(np.array([142, 69, 139]) / 255) + [1] #levels1 = ([0,100,200,350,530,750,1000,1300,1630,2000,2400,2850,3330,3850,4400,5000]) # follows (wmax)**2 levels1 = ([ 100, 200, 350, 500, 750, 1000, 1300, 1600, 2000, 2400, 2800, 3300, 3800, 4400, 5000 ]) # rounded to be pretty lbStride_value = 1 #rgb_arr = np.array(rgb_colors) #np.savetxt("colorpalette_marco_cape_ml.txt", np.around(rgb_arr[3:-1]*255,0), fmt='%2d', delimiter = ",") elif variable1['name'] == 'synth_bt_ir10.8': filename_colorpalette = 'rainbowIRsummer.txt' with open(path['base'] + path['colorpalette'] + filename_colorpalette, 'r') as f: lines = f.readlines() rgb_colors = [] rgb_colors.append(list(np.array([118, 39, 118]) / 255)) for i, line in enumerate(lines): if i % 14 == 0 and i > 70: rgb_colors.append( [float(line[:10]), float(line[11:21]), float(line[22:32])]) rgb_colors.append(list(np.array([35, 244, 255]) / 255)) num_bw_colors = 30 for i in range(num_bw_colors + 1): rgb_colors.append([ 1 - i / num_bw_colors, 1 - i / num_bw_colors, 1 - i / num_bw_colors ]) rgb_colors.append( rgb_colors[-1] ) # add highest loaded color to color for over the highest value levels1 = (list(range(-90, -20, 1)) + list(range(-20, 40 + 1, 2))) lbStride_value = 10 elif variable1['name'] == 'prec_24h'\ or variable1['name'] == 'prec_sum': filename_colorpalette = 'colorscale_prec24h.txt' with open(path['base'] + path['colorpalette'] + filename_colorpalette, 'r') as f: lines = f.readlines() rgb_colors = [] rgb_colors.append([0, 0, 0, 0]) # color for under the lowest value, transparent for i, line in enumerate(lines): rgb_colors.append([ float(line[0:3]) / 255, float(line[4:7]) / 255, float(line[8:11]) / 255, 1 ]) rgb_colors.append( rgb_colors[-1] ) # add highest loaded color to color for over the highest value levels1 = ([ 1, 10, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 250, 300, 400 ]) lbStride_value = 1 elif variable1['name'] == 'vmax_10m': filename_colorpalette = 'colorscale_vmax.txt' with open(path['base'] + path['colorpalette'] + filename_colorpalette, 'r') as f: lines = f.readlines() rgb_colors = [] rgb_colors.append( [0, 0, 0]) # placeholder for color for under the lowest value for i in range(0, 11): # load colors from palettable rgb_colors.append( list( cmasher.take_cmap_colors('cmr.chroma', 11, cmap_range=(0.20, 0.95))[::-1][i])) for i in range(0, 3): # load colors from palettable rgb_colors.append( list( cmasher.take_cmap_colors('cmr.freeze', 3, cmap_range=(0.40, 0.90))[i])) for i in range(0, 2): # load colors from palettable rgb_colors.append( list( cmasher.take_cmap_colors('cmr.flamingo', 2, cmap_range=(0.55, 0.80))[::-1][i])) rgb_colors[0] = rgb_colors[ 1] # copy lowest loaded color to color for under the lowest value rgb_colors.append( rgb_colors[-1] ) # add highest loaded color to color for over the highest value levels1 = ([ 0, 6, 12, 20, 29, 39, 50, 62, 75, 89, 103, 118, 154, 178, 209, 251, 300 ]) lbStride_value = 1 elif variable1['name'] == 'shear_200-850hPa': filename_colorpalette = 'colorscale_shear_200-850hPa.txt' with open(path['base'] + path['colorpalette'] + filename_colorpalette, 'r') as f: lines = f.readlines() rgb_colors = [] rgb_colors.append([1, 1, 1]) for i, line in enumerate(lines): rgb_colors.append([ float(line[0:3]) / 255, float(line[4:7]) / 255, float(line[8:11]) / 255 ]) rgb_colors.append([0, 0, 1]) levels1 = (list(np.arange(0, 30, 2.5)) + list(range(30, 50 + 1, 5)) + [99]) lbStride_value = 1 elif variable1['name'][:2] == 'pv'\ and variable1['name'][-1:] == 'K': filename_colorpalette = 'colorscale_ipv_eth.txt' with open(path['base'] + path['colorpalette'] + filename_colorpalette, 'r') as f: lines = f.readlines() rgb_colors = [] rgb_colors.append( [0, 0, 0]) # placeholder for color for under the lowest value for i, line in enumerate(lines): rgb_colors.append([ float(line[0:3]) / 255, float(line[4:7]) / 255, float(line[8:11]) / 255 ]) rgb_colors[0] = rgb_colors[ 1] # copy lowest loaded color to color for under the lowest value rgb_colors.append( rgb_colors[-1] ) # add highest loaded color to color for over the highest value levels1 = ([-1, -0.5, 0.2, 0.7, 1, 1.5, 2, 3, 4, 5, 6, 7, 8, 9, 10]) lbStride_value = 1 elif variable1['name'][:5] == 'theta'\ and variable1['name'][-3:] == 'PVU': rgb_colors = [] rgb_colors.append( [0, 0, 0]) # placeholder for color for under the lowest value for i in range(30): rgb_colors.append( list( palettable.colorbrewer.diverging.RdYlBu_10. get_mpl_colormap(N=30)(i)[:3])) rgb_colors[0] = rgb_colors[ 1] # copy lowest loaded color to color for under the lowest value rgb_colors.append( rgb_colors[-1] ) # add highest loaded color to color for over the highest value levels1 = np.arange(270, 420 + 1, 5) #levels1 = np.arange(300, 360+1, 20) lbStride_value = 2 mpres = Ngl.Resources() mpres.mpProjection = domain['projection'] if domain['limits_type'] == 'radius': mpres.mpLimitMode = 'LatLon' mpres.mpCenterLonF = domain['centerlon'] mpres.mpCenterLatF = domain['centerlat'] cutout_plot = dict( lat_min=float( np.where(domain['centerlat'] - domain['radius'] / 111.2 < -90, -90, domain['centerlat'] - domain['radius'] / 111.2)), lat_max=float( np.where(domain['centerlat'] + domain['radius'] / 111.2 > 90, 90, domain['centerlat'] + domain['radius'] / 111.2)), ) cutout_plot['lon_min'] = float(np.where(cutout_plot['lat_min'] <= -90 or cutout_plot['lat_max'] >= 90, 0, domain['centerlon'] - domain['radius'] \ / (111.2 * np.cos(domain['centerlat']*np.pi/180)))) cutout_plot['lon_max'] = float(np.where(cutout_plot['lat_min'] <= -90 or cutout_plot['lat_max'] >= 90, 360, domain['centerlon'] + domain['radius'] \ / (111.2 * np.cos(domain['centerlat']*np.pi/180)))) mpres.mpMinLonF = cutout_plot['lon_min'] mpres.mpMaxLonF = cutout_plot['lon_max'] mpres.mpMinLatF = cutout_plot['lat_min'] mpres.mpMaxLatF = cutout_plot['lat_max'] elif domain['limits_type'] == 'deltalatlon': mpres.mpLimitMode = 'LatLon' mpres.mpCenterLonF = 0 mpres.mpCenterLatF = 0 mpres.mpMinLonF = domain['centerlon'] - domain['deltalon_deg'] mpres.mpMaxLonF = domain['centerlon'] + domain['deltalon_deg'] mpres.mpMinLatF = domain['centerlat'] - domain['deltalat_deg'] mpres.mpMaxLatF = domain['centerlat'] + domain['deltalat_deg'] elif domain['limits_type'] == 'angle': mpres.mpLimitMode = 'Angles' mpres.mpCenterLonF = domain['centerlon'] mpres.mpCenterLatF = domain['centerlat'] mpres.mpLeftAngleF = domain['angle'] mpres.mpRightAngleF = domain['angle'] mpres.mpTopAngleF = domain['angle'] mpres.mpBottomAngleF = domain['angle'] mpres.nglMaximize = False mpres.vpXF = 0.001 mpres.vpYF = 1.00 mpres.vpWidthF = 0.88 mpres.vpHeightF = 1.00 mpres.mpLandFillColor = list(np.array([255, 225, 171]) / 255) mpres.mpOceanFillColor = [1, 1, 1] mpres.mpInlandWaterFillColor = [1, 1, 1] mpres.mpFillOn = True mpres.mpGridAndLimbOn = False mpres.mpGreatCircleLinesOn = False mpres.mpDataBaseVersion = 'MediumRes' mpres.mpDataSetName = 'Earth..4' mpres.mpOutlineBoundarySets = 'national' mpres.mpGeophysicalLineColor = 'black' mpres.mpNationalLineColor = 'black' mpres.mpGeophysicalLineThicknessF = 1.5 * domain['plot_width'] / 1000 mpres.mpNationalLineThicknessF = 1.5 * domain['plot_width'] / 1000 mpres.mpPerimOn = True mpres.mpPerimLineColor = 'black' mpres.mpPerimLineThicknessF = 8.0 * domain['plot_width'] / 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 # settings for variable1 / shading # v1res = Ngl.Resources() v1res.nglFrame = False v1res.nglDraw = False v1res.sfDataArray = data_array1_cut v1res.sfXArray = clon_cut v1res.sfYArray = clat_cut v1res.sfMissingValueV = 9999 #v1res.cnFillBackgroundColor = 'transparent' v1res.cnMissingValFillColor = 'Gray80' v1res.cnFillColors = np.array(rgb_colors) v1res.cnLinesOn = False v1res.cnFillOn = True v1res.cnLineLabelsOn = False if not variable1['load_global_field']: v1res.cnFillMode = 'RasterFill' elif model == 'icon-eu-det': v1res.cnFillMode = 'RasterFill' elif model == 'icon-global-det': v1res.cnFillMode = 'CellFill' v1res.sfXCellBounds = vlon_cut v1res.sfYCellBounds = vlat_cut #v1res.cnFillOpacityF = 0.5 #v1res.cnFillDrawOrder = 'Predraw' v1res.cnLevelSelectionMode = 'ExplicitLevels' v1res.cnLevels = levels1 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.2 # make a little more space at top for the unit label v1res.lbRightMarginF = 0.0 v1res.lbBottomMarginF = 0.05 v1res.lbLeftMarginF = -0.35 v1res.cnLabelBarEndStyle = 'ExcludeOuterBoxes' #if variable1['name'] == 'prec_rate' : # 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 = 'ExternalEdges' v1res.lbLabelStride = lbStride_value # settings for variable2 / contourlines # if variable2['name'] != '': v2res = Ngl.Resources() v2res.nglFrame = False v2res.nglDraw = False v2res.sfDataArray = data_array2_cut v2res.sfXArray = ll_lon_cut #ll_lon_cyclic v2res.sfYArray = ll_lat_cut v2res.sfMissingValueV = 9999 #v2res.trGridType = 'TriangularMesh' v2res.cnFillOn = False v2res.cnLinesOn = True v2res.cnLineLabelsOn = True v2res.cnLineLabelPlacementMode = 'Constant' v2res.cnLabelDrawOrder = 'PostDraw' v2res.cnInfoLabelOn = False v2res.cnSmoothingOn = False v2res.cnLevelSelectionMode = 'ExplicitLevels' v2res.cnLineThicknessF = 3.0 * domain['plot_width'] / 1000 v2res.cnLineLabelFontHeightF = 0.008 v2res.cnLineDashSegLenF = 0.25 v3res = Ngl.Resources() v3res.nglFrame = False v3res.nglDraw = False v3res.sfDataArray = data_array2_cut v3res.sfXArray = ll_lon_cut #ll_lon_cyclic v3res.sfYArray = ll_lat_cut v3res.sfMissingValueV = 9999 #v3res.trGridType = 'TriangularMesh' v3res.cnFillOn = False v3res.cnLinesOn = True v3res.cnLineLabelsOn = True v3res.cnLineLabelPlacementMode = 'Constant' v3res.cnLabelDrawOrder = 'PostDraw' v3res.cnInfoLabelOn = False v3res.cnSmoothingOn = False v3res.cnLevelSelectionMode = 'ExplicitLevels' v3res.cnLineThicknessF = 5.0 * domain['plot_width'] / 1000 v3res.cnLineLabelFontHeightF = 0.008 v3res.cnLineDashSegLenF = 0.25 if variable2['name'] == 'mslp': v2res.cnLevels = np.arange(900, 1100, 2) v2res.cnLineLabelInterval = 1 v3res.cnLevels = np.arange(900, 1100, 10) v3res.cnLineLabelInterval = 1 elif variable2['name'] == 'gph_300hPa': v2res.cnLevels = np.arange(780, 1000, 6) v2res.cnLineLabelInterval = 1 v3res.cnLevels = np.arange(780, 1000, 24) v3res.cnLineLabelInterval = 1 elif variable2['name'] == 'gph_850hPa': v2res.cnLevels = np.arange(100, 180, 2) v2res.cnLineLabelInterval = 2 v3res.cnLevels = np.arange(100, 180, 10) v3res.cnLineLabelInterval = 2 elif variable2['name'] == 'gph_700hPa': v2res.cnLevels = np.arange(472, 633, 2) v2res.cnLineLabelInterval = 1 v3res.cnLevels = np.arange(472, 633, 8) v3res.cnLineLabelInterval = 1 elif variable2['name'] == 'gph_500hPa': v2res.cnLevels = np.arange(472, 633, 4) v2res.cnLineLabelInterval = 1 v3res.cnLevels = np.arange(472, 633, 16) v3res.cnLineLabelInterval = 1 elif variable2['name'] == 'shear_0-6km': v4res = Ngl.Resources() v4res.nglFrame = False v4res.nglDraw = False v4res.sfDataArray = data_array2_cut v4res.sfXArray = ll_lon_cut #ll_lon_cyclic v4res.sfYArray = ll_lat_cut v4res.sfMissingValueV = 9999 #v4res.trGridType = 'TriangularMesh' v4res.cnFillOn = False v4res.cnLinesOn = True v4res.cnLineLabelsOn = True v4res.cnLineLabelPlacementMode = 'Constant' v4res.cnLabelDrawOrder = 'PostDraw' v4res.cnInfoLabelOn = False v4res.cnSmoothingOn = False v4res.cnLevelSelectionMode = 'ExplicitLevels' v4res.cnLineLabelFontHeightF = 0.008 v4res.cnLineDashSegLenF = 0.25 v5res = Ngl.Resources() v5res.nglFrame = False v5res.nglDraw = False v5res.sfDataArray = data_array2_cut v5res.sfXArray = ll_lon_cut #ll_lon_cyclic v5res.sfYArray = ll_lat_cut v5res.sfMissingValueV = 9999 #54res.trGridType = 'TriangularMesh' v5res.cnFillOn = False v5res.cnLinesOn = True v5res.cnLineLabelsOn = True v5res.cnLineLabelPlacementMode = 'Constant' v5res.cnLabelDrawOrder = 'PostDraw' v5res.cnInfoLabelOn = False v5res.cnSmoothingOn = False v5res.cnLevelSelectionMode = 'ExplicitLevels' v5res.cnLineLabelFontHeightF = 0.008 v5res.cnLineDashSegLenF = 0.25 v2res.cnLevels = [10] v2res.cnLineLabelInterval = 1 v2res.cnLineDashSegLenF = 0.15 v2res.cnLineThicknessF = 2.4 * domain['plot_width'] / 1000 v3res.cnLevels = [15] v3res.cnLineLabelInterval = 1 v3res.cnLineThicknessF = 4.5 * domain['plot_width'] / 1000 v3res.cnLineDashSegLenF = 0.15 v3res.cnLineThicknessF = 3.6 * domain['plot_width'] / 1000 v4res.cnLevels = [20] v4res.cnLineLabelInterval = 1 v4res.cnLineDashSegLenF = 0.15 v4res.cnLineThicknessF = 5.4 * domain['plot_width'] / 1000 v5res.cnLevels = [25] v5res.cnLineLabelInterval = 1 v5res.cnLineDashSegLenF = 0.15 v5res.cnLineThicknessF = 8.0 * domain['plot_width'] / 1000 ''' these are settings for some experiment with lows/highs min/max pressure labels: v2res.cnLineLabelsOn = True v2res.cnLabelDrawOrder = 'PostDraw' v2res.cnLineLabelPerimOn = False v2res.cnLineLabelBackgroundColor = 'transparent' v2res.cnLineLabelPlacementMode = 'Computed' v2res.cnLineLabelDensityF = 0.2 v2res.cnLineLabelFontHeightF = 0.010 #v2res.cnLineDashSegLenF = 0.25 v2res.cnLowLabelsOn = True #v2res.cnLowLabelPerimOn = False v2res.cnLowLabelString = '$ZDV$hPa' #v2res.cnLowLabelFontColor = 'black' v2res.cnLowLabelBackgroundColor = 'white''' # settings for unit text # if variable1['name'][:2] == 'pv'\ and (domain['name'] == 'southern_south_america'\ or domain['name'] == 'south_pole'): text_str = variable1['unit'] + ' * -1' else: text_str = variable1['unit'] text_res_1 = Ngl.Resources() text_res_1.txFontColor = 'black' text_res_1.txFontHeightF = 0.013 text_x = 0.965 text_y = domain['text_y'] # settings for description label # res_text_descr = Ngl.Resources() res_text_descr.txJust = 'CenterLeft' res_text_descr.txFontHeightF = 0.01 res_text_descr.txFontColor = 'black' res_text_descr.txBackgroundFillColor = 'white' res_text_descr.txPerimOn = True res_text_descr.txPerimColor = 'black' text_descr_str1 = 'ICON-Global-Deterministic from {:02d}.{:02d}.{:4d} {:02d}UTC +{:d}h, '.format( run['day'], run['month'], run['year'], run['hour'], hour) if variable2['name'] == '': text_descr_str2 = 'Contours: {} in {}'.format(variable1['name'], variable1['unit']) else: text_descr_str2 = 'Contours: {} in {}, Lines: {} in {}'.format( variable1['name'], variable1['unit'], variable2['name'], variable2['unit']) text_descr_x = 0.02 text_descr_y = domain['text_y'] - 0.005 # override settings for specific cases # if domain['name'] == 'mediterranean': mpres.mpPerimLineThicknessF /= 1.5 mpres.mpGeophysicalLineThicknessF /= 1.5 mpres.mpNationalLineThicknessF /= 1.5 mpres.vpWidthF = 0.94 v1res.lbLabelFontHeightF = 0.005 v1res.pmLabelBarWidthF = 0.04 v1res.lbLeftMarginF = -0.50 if variable2['name'] != '': v2res.cnLineThicknessF /= 1.5 v2res.cnLineLabelFontHeightF /= 1.5 v3res.cnLineThicknessF /= 1.5 v3res.cnLineLabelFontHeightF /= 1.5 v2res.cnLineDashSegLenF = 0.12 v3res.cnLineDashSegLenF = 0.12 text_res_1.txFontHeightF = 0.007 text_x = 0.980 res_text_descr.txFontHeightF = 0.007 text_descr_x = 0.005 elif domain['name'] == 'north_pole' or domain['name'] == 'south_pole': if variable2['name'] == 'mslp': v2res.cnLevels = np.arange(900, 1100, 4) v3res.cnLevels = np.arange(900, 1100, 20) elif variable2['name'] == 'gph_300hPa': v2res.cnLevels = np.arange(780, 1000, 12) v3res.cnLevels = np.arange(780, 1000, 48) elif variable2['name'] == 'gph_500hPa': v2res.cnLevels = np.arange(472, 633, 8) v3res.cnLevels = np.arange(472, 633, 32) elif variable2['name'] == 'gph_700hPa': v2res.cnLevels = np.arange(472, 633, 8) v3res.cnLevels = np.arange(472, 633, 32) elif variable2['name'] == 'gph_850hPa': v2res.cnLevels = np.arange(102, 180, 4) v3res.cnLevels = np.arange(102, 180, 20) elif domain['name'] == 'Argentina_Central' or domain[ 'name'] == 'Argentina_Central_cerca': if variable2['name'] == 'gph_850hPa': v2res.cnLevels = np.arange(100, 180, 1) v3res.cnLevels = np.arange(100, 180, 5) v2res.cnLineLabelInterval = 1 wks_res = Ngl.Resources() wks_res.wkWidth = domain['plot_width'] wks_res.wkHeight = domain[ 'plot_width'] # the whitespace above and below the plot will be cut afterwards #wks_res.wkColorMap = np.array(rgb_colors) wks_type = 'png' wks = Ngl.open_wks(wks_type, path['base'] + path['plots'] + plot_name, wks_res) basic_map = Ngl.map(wks, mpres) # plot subnational borders for some domains # '''shp_filenames = [] if domain['name'] == 'southern_south_america'\ or domain['name'] == 'arg_uru_braz'\ or domain['name'] == 'argentina_central'\ or domain['name'] == 'argentina_central_cerca': shp_filenames.append(['gadm36_ARG_1.shp', 0.3]) shp_filenames.append(['gadm36_BRA_1.shp', 0.3]) shp_filenames.append(['gadm36_CHL_1.shp', 0.3]) elif domain['name'] == 'north_america': shp_filenames.append(['gadm36_USA_1.shp', 0.3]) shp_filenames.append(['gadm36_CAN_1.shp', 0.3]) shp_filenames.append(['gadm36_MEX_1.shp', 0.3]) elif domain['name'] == 'eastern_asia': shp_filenames.append(['gadm36_CHN_1.shp', 0.3]) for shp_filename, lineThickness in shp_filenames: shpf = Nio.open_file(path['base'] + path['shapefiles'] + shp_filename, 'r') shpf_lon = np.ravel(shpf.variables['x'][:]) shpf_lat = np.ravel(shpf.variables['y'][:]) shpf_segments = shpf.variables['segments'][:, 0] plres = Ngl.Resources() plres.gsLineColor = 'black' plres.gsLineThicknessF = lineThickness plres.gsSegments = shpf_segments Ngl.add_polyline(wks, basic_map, shpf_lon, shpf_lat, plres)''' # put everything together # contourshades_plot = Ngl.contour(wks, data_array1_cut, v1res) if variable2['name'] != '': contourlines_minor_plot = Ngl.contour(wks, data_array2_cut, v2res) contourlines_major_plot = Ngl.contour(wks, data_array2_cut, v3res) if variable2['name'] == 'shear_0-6km': contourlines_major2_plot = Ngl.contour(wks, data_array2_cut, v4res) contourlines_major3_plot = Ngl.contour(wks, data_array2_cut, v5res) Ngl.overlay(basic_map, contourshades_plot) if variable2['name'] != '': Ngl.overlay(basic_map, contourlines_minor_plot) Ngl.overlay(basic_map, contourlines_major_plot) if variable2['name'] == 'shear_0-6km': Ngl.overlay(basic_map, contourlines_major2_plot) Ngl.overlay(basic_map, contourlines_major3_plot) Ngl.draw(basic_map) Ngl.text_ndc(wks, text_str, text_x, text_y, text_res_1) #Ngl.text_ndc(wks, text_descr_str1 + text_descr_str2, text_descr_x, text_descr_y, res_text_descr) Ngl.frame(wks) Ngl.delete_wks(wks) # 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() return
res.mpLimitMode = "LatLon" # Limit map via lat/lon res.mpGridMaskMode = "MaskNotOcean" # Draw grid over ocean. res.mpOceanFillColor = -1 res.mpGridLineDashPattern = 7 res.tiMainFont = "helvetica" res.tiMainFontHeightF = 0.02 res.tiMainString = "Provinces of China" res.mpMinLatF = 17 res.mpMaxLatF = 55 res.mpMinLonF = 72 res.mpMaxLonF = 136 plot = Ngl.map(wks, res) # Create the map plot res.mpFillOn = True # Turn on map fill res.mpFillBoundarySets = "National" res.mpFillAreaSpecifiers = boundaries res.tiMainString = "States of India" res.mpMinLatF = 6 res.mpMaxLatF = 38 res.mpMinLonF = 65 res.mpMaxLonF = 100 Ngl.map(wks, res) Ngl.end()
''' from __future__ import print_function import Ngl wks = Ngl.open_wks("png", "plot_mptick_3") #-- open workstation mpres = Ngl.Resources() #-- resource object mpres.mpFillOn = True #-- turn map fill on mpres.mpOutlineOn = True #-- outline map mpres.mpOceanFillColor = "Transparent" #-- set ocean fill color to transparent mpres.mpLandFillColor = "Gray90" #-- set land fill color to gray mpres.mpInlandWaterFillColor = "Gray90" #-- set inland water fill color to gray mpres.mpProjection = "CylindricalEquidistant" #-- map projection mpres.mpGridAndLimbOn = False #-- turn off grid lines mpres.pmTickMarkDisplayMode = "Always" #-- turn on built-in tickmarks mpres.mpLimitMode = "LatLon" mpres.mpMinLonF = -65. #-- set min lon mpres.mpMaxLonF = -63. #-- set max lon mpres.mpMinLatF = 10. #-- set min lat mpres.mpMaxLatF = 11. #-- set max lat mpres.mpDataBaseVersion = "HighRes" #-- turn on highres coastline mpres.tiMainString = "Map database HighRes (RANGS) and~C~Built-in tickmarks that include minutes" map = Ngl.map(wks, mpres) #-- create the plot Ngl.end()
res.mpOceanFillColor = "transparent" res.mpLandFillColor = "transparent" res.mpInlandWaterFillColor = "transparent" res.mpOutlineOn = True res.mpGridAndLimbOn = False res.pmTickMarkDisplayMode = "Never" res.tiMainFontHeightF = 0.012 res.tiMainString = " ~F22~Climate divisions colored by 3rd field~C~~F21~climdivcorr.24.8.154.75.267.22.53.59.data" res.nglDraw = False res.nglFrame = False map = Ngl.map(wks,res) # # Get all of the area names associated with Earth..3 and the # corresponding group numbers. The area names will be of the # format "Arkansas : 01", where "01" is the climate division number. # # The group numbers are essentially color index values that were # chosen such that adjacent areas will not have the same color # (if you choose to color each one randomly). # # For example, Arkansas has 9 climate divisions, with the following # groups: # Arkansas : 01, group 7 # Arkansas : 02, group 8 # Arkansas : 03, group 7
# # TickMark resources. # res.tmBorderThicknessF = 5 # res.tmXBLabelFontAspectF = 2 res.tmXBLabelFontHeightF = 0.015 res.tmXBLabelFontThicknessF = 100 res.tmXBMajorThicknessF = 5 res.tmXBMajorLengthF = 0.01 res.tmYLLabelFontThicknessF = 100 res.tmYLMajorThicknessF = 5 plot = Ngl.map(wks, res) # Create the map plot, but don't advance frame. # # add specific out line # # attribute of polyline lnres = Ngl.Resources() lnres.gsLineColor = "red" lnres.gsLineThicknessF = 6.0 # 3x as thick lnres.gsLineDashPattern = 0 # china east lonCN = [112, 122] latCN = [22, 37] cnEast_bndry_lon = np.ravel([lonCN[0], lonCN[0], lonCN[1], lonCN[1], lonCN[0]]) cnEast_bndry_lat = np.ravel([latCN[0], latCN[1], latCN[1], latCN[0], latCN[0]])
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
wks = Ngl.open_wks("png", "plot_scatter_3") res = Ngl.Resources() res.nglFrame = False #-- don't advance the frame res.nglMaximize = True #-- maximize plot res.tiMainString = "Locations of stations" #-- add title res.mpLimitMode = "LatLon" res.mpMinLatF = lat.min() res.mpMaxLatF = lat.max() res.mpMinLonF = lon.min() res.mpMaxLonF = lon.max() #-- first plot map = Ngl.map(wks, res) #-- create the map plot, don't draw mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = "Brown" Ngl.polymarker(wks, map, lon, lat, mkres) Ngl.frame(wks) #-- second plot res.mpMinLatF = 22. res.mpMaxLatF = 60. res.mpMinLonF = -125. res.mpMaxLonF = -65.
res.mpMaskAreaSpecifiers = ["Conterminous US"] # don't fill here res.mpGridAndLimbOn = False # no lat/lon lines # # Increase the viewport size (make the map bigger). # res.vpWidthF = 0.93 res.vpHeightF = 0.93 res.vpXF = 0.05 res.vpYF = 0.99 res.nglDraw = False # don't draw the plots now res.nglFrame = False # or advance the frame res.mpProjection = "LambertConformal" plot = Ngl.map(wks,res) # create the map plot # # Polygon resources. # res_poly = Ngl.Resources() res_poly.gsEdgesOn = True # draw border around polygons. res_poly.gsEdgeColor = "black" # # Prepare to draw the polygons. # random.seed(10) # set a seed for the random number generator # # Get the polygon data and fill polygons with random colors in
res.mpGridAndLimbOn = True res.pmTickMarkDisplayMode = "Never" res.mpProjection = "CylindricalEquidistant" res.mpLimitMode = "LatLon" # Limit the map view. res.mpMinLonF = lontr res.mpMaxLonF = lonbl res.mpMinLatF = lattr res.mpMaxLatF = latbl res.mpOutlineBoundarySets = "AllBoundaries" res.mpNationalLineColor = colour res.mpNationalLineThicknessF = 2.0 res.mpGeophysicalLineColor = colour res.mpGeophysicalLineThicknessF = 2.0 res.mpGridLatSpacingF = 5.0 res.mpGridLonSpacingF = 5.0 res.mpGridLineThicknessF = 2.0 res.cnMonoLineColor = True map_plot = ngl.map(wks,res) ngl.maximize_plot(wks, map_plot) ngl.draw(map_plot) ngl.frame(wks) ngl.destroy(wks) del res os.system('mogrify -trim map_'+colour+'_'+region+'.png') # os.system('mogrify -resize 1350x900 map_'+colour+'_'+region+'.png')
if args.grid_only: print('Plot Grid only') config = Ngl.Resources() config.nglFrame = False config.nglDraw = False config.mpProjection = "Orthographic" config.mpLimitMode = "LatLon" config.mpMinLonF = 0 config.mpMaxLonF = 18 config.mpMinLatF = 43 config.mpMaxLatF = 50 map = Ngl.map(wks,config) ecx = numpy.ravel( vlon[ edge_vertices-1 ], order='F' ) ecy = numpy.ravel( vlat[ edge_vertices-1 ], order='F' ) lines_cfg = Ngl.Resources() lines_cfg.gsSegments = numpy.arange(0, edge_vertices.size, 2) poly = Ngl.add_polyline(wks, map, ecx, ecy, lines_cfg) Ngl.draw(map) Ngl.frame(wks) Ngl.end() sys.exit() # regular plot
# Main code #---------------------------------------------------------------------- lon_spacing = 40 lat_spacing = 20 wks_type = "png" wks = Ngl.open_wks(wks_type,"map3") #---Create and draw map; note how lat/lon spacing doesn't line up with tickmarks res = Ngl.Resources() res.mpGridLatSpacingF = lat_spacing res.mpGridLonSpacingF = lat_spacing res.tiMainString = "Default map tickmarks and grid lines" map = Ngl.map(wks,res) del res #---Create map again, but turn off grid lines and tickmarks res = Ngl.Resources() res.nglDraw = False # Don't draw map res.nglFrame = False # Don't advance frame res.mpGridAndLimbOn = False # Will add own grid lines res.pmTickMarkDisplayMode = "Never" # Will add own labels res.tiMainString = "Custom map labels and grid lines" map = Ngl.map(wks,res) # Won't get drawn just yet #---Add custom tickmarks and grid lines labels = add_map_tickmarks(wks,map,lat_spacing,lon_spacing)
#---Open file for graphics wks_type = "png" wks = Ngl.open_wks(wks_type, "wmstnm03") # # Draw a world map. # mpres = Ngl.Resources() mpres.nglFrame = False mpres.mpSatelliteDistF = 1.3 mpres.mpOutlineBoundarySets = "USStates" mpres.mpCenterLatF = 40. mpres.mpCenterLonF = -97. mpres.mpCenterRotF = 35. mpres.mpProjection = "Satellite" map = Ngl.map(wks, "Satellite", mpres) # # In the middle of Nebraska, draw a wind barb for a north wind # with a magnitude of 15 knots. # Ngl.wmbarbmap(wks, 42., -99., 0., -15.) # # Draw the station model data at the selected cities. The call # to wmsetp informs wmstnm that the wind barbs will be drawn over # a map. To illustrate the adjustment for plotting the model # data over a map, all winds are from the north. # Ngl.wmsetp("ezf", 1) Ngl.wmstnm(wks, city_lats, city_lons, imdat)
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)
# Zoom in on South America. res.mpLimitMode = "LatLon" res.mpMinLatF = -60 res.mpMaxLatF = 15 res.mpMinLonF = -90 res.mpMaxLonF = -30 res.mpFillOn = True res.mpLandFillColor = "NavajoWhite" res.mpOceanFillColor = "SlateGray2" res.tiMainString = "Stream network data for South America" res.tiMainFontHeightF = 0.015 # Make font slightly smaller. plot = Ngl.map(wks, res) # Draw map, but don't advance frame. #************************************************* # Section to add polylines to map. #************************************************* f = Nio.open_file(filename, "r") # Open shapefile lon = numpy.ravel(f.variables["x"][:]) lat = numpy.ravel(f.variables["y"][:]) segments = f.variables["segments"][:, 0] plres = Ngl.Resources() # resources for polylines plres.gsLineColor = "blue" plres.gsSegments = segments id = Ngl.add_polyline(wks, plot, lon, lat, plres)
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
cfres.cnLinesOn = False # Turn off contour lines. cfres.cnLineLabelsOn = False # Turn off contour line labels. cfres.lbOrientation = "Horizontal" # horizontal labelbar cfres.lbLabelFontHeightF = 0.012 # Decrease font size. cfres.pmLabelBarOrthogonalPosF = -0.05 # Move labelbar up. clres.cnLineLabelsOn = False # Turn off contour line labels. clres.cnLineDashPatterns = 3 # dashed contour lines clres.cnLineThicknessF = 3. # triple thick contour lines clres.cnInfoLabelOrthogonalPosF = -0.15 # Move info label up. # # Create the various plots. They will not get drawn because # nglDraw is set to False for all of them. # map_plot = Ngl.map(wks,mpres) vector_plot = Ngl.vector(wks,ua,va,vcres) line_contour_plot = Ngl.contour(wks,pa,clres) fill_contour_plot = Ngl.contour(wks,ta,cfres) # # Overlay everything on the map plot. # Ngl.overlay(map_plot,fill_contour_plot) Ngl.overlay(map_plot,line_contour_plot) Ngl.overlay(map_plot,vector_plot) # # Change the title. # srlist = Ngl.Resources()
wks_type = "png" wks = Ngl.open_wks(wks_type, "map2") mpres = Ngl.Resources() mpres.nglFrame = False # Don't advance frame after plot is drawn. mpres.nglDraw = False # Don't draw plot just yet. mpres.mpProjection = "Orthographic" mpres.mpCenterLatF = 30. mpres.mpCenterLonF = 160. mpres.mpCenterRotF = 60. mpres.mpLabelsOn = False mpres.mpPerimOn = False map = Ngl.map(wks, mpres) # Create map. gsres = Ngl.Resources() gsres.gsLineColor = "black" gsres.gsLineThicknessF = 2.0 gsres.gsLineLabelFont = "helvetica-bold" gsres.gsLineLabelFontHeightF = 0.02 gsres.gsLineLabelFontColor = "black" gsres.gsFillIndex = 0 gsres.gsEdgesOn = False # Tropical zone gsres.gsFillColor = 87
tres.sfXArray = lon tres.sfYArray = lat #-- plot resources for the rhumidity plot rres = Ngl.Resources() rres.nglDraw = False #-- don't draw plot rres.nglFrame = False #-- don't advance frame rres.cnInfoLabelOrthogonalPosF = 0.13 #-- move info label upward rres.sfXArray = lon rres.sfYArray = lat #-- generate tplot, but don't draw it yet print("-- map --") map = Ngl.map(wks, mpres) #-- generate tplot, but don't draw it yet print("-- tplot --") tplot = Ngl.contour(wks, t, tres) #-- generate plot2, but don't draw it yet print("-- rplot --") rplot = Ngl.contour(wks, rhum, rres) #-- overlay rplot on tplot print("-- overlay tplot --") Ngl.overlay(map, tplot) print("-- overlay rplot --") Ngl.overlay(map, rplot)
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))
res.mpRightCornerLatF = 50 # right corner res.mpRightCornerLonF = -64 # right corner res.mpFillOn = True # Turn on fill for map areas. res.mpLandFillColor = "LightGray" res.mpOceanFillColor = "Cyan" res.mpInlandWaterFillColor = "Cyan" res.pmTickMarkDisplayMode = "Always" # Turn on map tickmarks res.tiMainString = "Percentage unemployment, by state" res.nglDraw = False # don't draw the plots now res.nglFrame = False # or advance the frame plot = Ngl.map(wks,res) # create the map plot # # Read data off shapefile. Must have states.shp, states.dbf, # and states.prj file in this directory. # dirc = Ngl.pynglpath("data") f = Nio.open_file(os.path.join(dirc,"shp","states.shp"), "r") # Open shapefile segments = f.variables["segments"][:] geometry = f.variables["geometry"][:] segsDims = segments.shape geomDims = geometry.shape # # Read global attributes #
res.mpLimitMode = "LatLon" # Limit map via lat/lon res.mpGridMaskMode = "MaskNotOcean" # Draw grid over ocean. res.mpOceanFillColor = -1 res.mpGridLineDashPattern = 7 res.tiMainFont = "helvetica" res.tiMainFontHeightF = 0.02 res.tiMainString = "Provinces of China" res.mpMinLatF = 17 res.mpMaxLatF = 55 res.mpMinLonF = 72 res.mpMaxLonF = 136 plot = Ngl.map(wks, res) # Create the map plot res.mpFillOn = True # Turn on map fill res.mpFillBoundarySets = "National" res.mpFillAreaSpecifiers = boundaries res.tiMainString = "States of India" res.mpMinLatF = 6 res.mpMaxLatF = 38 res.mpMinLonF = 65 res.mpMaxLonF = 100 Ngl.map(wks, res) Ngl.end()