def plot_variable(self,variable_name,i_time=0,i_depth=0,output_path=None): variable = getattr(self,variable_name) if variable is None: raise ValueError(f'Requested variable {variable_name} to plot is empty in ModelData.') if len(variable.dimensions) == 3: plot_values = variable.values[i_time,:,:] if len(variable.dimensions) == 4: plot_values = variable.values[i_time,i_depth,:,:] mpl.rc('font',family='arial') fig = plt.figure(figsize=(12,8)) ax = plt.gca(projection=ccrs.PlateCarree()) c = ax.contourf(self.lon.values,self.lat.values,plot_values,transform=ccrs.PlateCarree()) ax.coastlines() # colorbar pos = ax.get_position() cbax = fig.add_axes([pos.x0+pos.width+0.01,pos.y0,0.02,pos.height]) cbar = fig.colorbar(c,label=f'{variable.name} [{variable.units}]',cax=cbax) # grid parallels = np.arange(-80,90,20) meridians = np.arange(-180,190,60) lon_formatter = cticker.LongitudeFormatter() lat_formatter = cticker.LatitudeFormatter() ax.set_xticks(meridians,crs=ccrs.PlateCarree()) ax.set_xticklabels(meridians) ax.xaxis.set_major_formatter(lon_formatter) ax.set_yticks(parallels,crs=ccrs.PlateCarree()) ax.set_yticklabels(parallels) ax.yaxis.set_major_formatter(lat_formatter) ax.set_frame_on(True) if output_path is not None: plt.savefig(output_path,bbox_inches='tight',dpi=300) plt.show()
def label_lats(labels, ax): ax.set_yticks(labels, crs=ccrs.PlateCarree()) lat_formatter = cticker.LatitudeFormatter() ax.yaxis.set_major_formatter(lat_formatter) ax.grid(False) return ax
def plot_map(geometry, events): """ Plot map. :param geometry: :param events: """ stamen_terrain = img_tiles.Stamen('terrain-background') fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection=stamen_terrain.crs) ax.add_image(stamen_terrain, 10) if events: eq = [] for event in events: eq.append([event.longitude, event.latitude]) eq = np.array(eq).T ax.scatter(eq[0], eq[1], label='Event', transform=ccrs.PlateCarree(), color='#555555', edgecolors='k', linewidth=0.3, marker='o', s=10) if geometry: geom = [] network = geometry[0].network for station in geometry: geom.append([station.longitude, station.latitude]) geom = np.array(geom).T ax.scatter(geom[0], geom[1], label=network, transform=ccrs.PlateCarree(), color='#c72c2c', edgecolors='k', linewidth=0.1, marker='v', s=40) xmin, xmax = ax.get_xlim() ymin, ymax = ax.get_ylim() conv = ProjectionConverter(stamen_terrain.crs, ccrs.PlateCarree()) xmin, ymin = conv.convert(xmin, ymin) xmax, ymax = conv.convert(xmax, ymax) xticks = ticker.LongitudeLocator(nbins=2)._raw_ticks(xmin, xmax) yticks = ticker.LatitudeLocator(nbins=3)._raw_ticks(ymin, ymax) ax.set_xticks(xticks, crs=ccrs.PlateCarree()) ax.set_yticks(yticks, crs=ccrs.PlateCarree()) ax.xaxis.set_major_formatter( ticker.LongitudeFormatter(zero_direction_label=True)) ax.yaxis.set_major_formatter(ticker.LatitudeFormatter()) ax.legend() plt.show()
def label_latlon(ax,lons,lats): # Longitude labels ax.set_xticks(lons, crs=ccrs.PlateCarree()) lon_formatter = cticker.LongitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) # Latitude labels ax.set_yticks(lats, crs=ccrs.PlateCarree()) lat_formatter = cticker.LatitudeFormatter() ax.yaxis.set_major_formatter(lat_formatter)
def plot_grid(self, extent=None, points=[]): #Create figure and axis objects. Also use stock image from cartopy fig, ax = pp.subplots(nrows=1, ncols=1, subplot_kw={"projection": self.proj}) ax.stock_img() #Add gridlines gl = ax.gridlines(crs=self.pcp, draw_labels=False, linewidth=1, linestyle=":", color="grey") if (extent == None): #Only do fancy gridline format for default plot. #Format meridions gl.xlocator = mticker.FixedLocator(numpy.linspace(-180, 180, 13)) ax.set_xticks(numpy.linspace(-150, 180, 12), crs=self.pcp) ax.set_xticklabels(numpy.linspace(-150, 180, 12)) ax.xaxis.set_major_formatter(cticker.LongitudeFormatter()) #Format parallels gl.ylocator = mticker.FixedLocator(numpy.linspace(-90, 90, 7)) ax.set_yticks(numpy.linspace(-90, 90, 7), crs=self.pcp) ax.set_yticklabels(numpy.linspace(-90, 90, 7)) ax.yaxis.set_major_formatter(cticker.LatitudeFormatter()) else: gl.xlabels_bottom = True gl.ylabels_left = True gl.xformatter = cmg.LONGITUDE_FORMATTER gl.yformatter = cmg.LATITUDE_FORMATTER #Add user defined points for pt in points: #Now plot the point ax.scatter(pt[0], pt[1], color="red", transform=self.pcp) #Change map extent if requested if (extent != None): #First must transform extent corners llc = self.proj.transform_point(extent[0], extent[2], self.pcp) urc = self.proj.transform_point(extent[1], extent[3], self.pcp) #Now can set extent ax.set_extent((llc[0], urc[0], llc[1], urc[1]), crs=self.proj) #Display image pp.show() #Returning return
def plot_grid(self, gid=1, lc=False, points=[]): ### Plot subset region #Create figure and axis objects fig, ax = pp.subplots(nrows=1, ncols=1, subplot_kw={"projection": self.pcp}) #Add continents and states ax.coastlines() ax.add_feature(self.states) ax.stock_img() #Set extent and make gridlines gl = ax.gridlines(crs=self.pcp, draw_labels=False, linewidth=1, linestyle=":", color="grey") if self.subset: #If subsetting is on ax.set_extent(self.extent, crs=self.pcp) gl.xlabels_bottom = True gl.ylabels_left = True gl.xformatter = cmg.LONGITUDE_FORMATTER gl.yformatter = cmg.LATITUDE_FORMATTER else: #If no analysis region is set (i.e. working with full hrrr domain) #Format meridions gl.xlocator = mticker.FixedLocator(numpy.linspace(-180, 180, 13)) ax.set_xticks(numpy.linspace(-150, 180, 12), crs=self.pcp) ax.set_xticklabels(numpy.linspace(-150, 180, 12)) ax.xaxis.set_major_formatter(cticker.LongitudeFormatter()) #Format parallels gl.ylocator = mticker.FixedLocator(numpy.linspace(-90, 90, 7)) ax.set_yticks(numpy.linspace(-90, 90, 7), crs=self.pcp) ax.set_yticklabels(numpy.linspace(-90, 90, 7)) ax.yaxis.set_major_formatter(cticker.LatitudeFormatter()) #Returning return (fig, ax)
def _draw_grid(self, nlon=10, nlat=10): lon_formatter = cticker.LongitudeFormatter() lat_formatter = cticker.LatitudeFormatter() if self.lon_range and self.lat_range: dlon = (self.lon_range[-1] - self.lon_range[0]) / nlon dlat = (self.lat_range[-1] - self.lat_range[0]) / nlat if self.meridians is None: self.meridians = np.arange(self.lon_range[0], self.lon_range[-1] + dlon, dlon) if self.parallels is None: self.parallels = np.arange(self.lat_range[0], self.lat_range[-1] + dlat, dlat) else: dlon = 360. / nlon dlat = 180. / nlat if self.meridians is None: self.meridians = np.arange(-180, 180 + dlon, dlon) if self.parallels is None: self.parallels = np.arange(-80, 80 + dlat, dlat) self.ax.set_xticks(self.meridians, crs=ccrs.PlateCarree()) if self.xmarkers == 'off': self.ax.set_xticklabels([]) self.ax.set_axisbelow(False) else: self.ax.set_xticklabels(self.meridians) self.ax.xaxis.set_major_formatter(lon_formatter) self.ax.set_yticks(self.parallels, crs=ccrs.PlateCarree()) if self.ymarkers == 'off': self.ax.set_yticklabels([]) else: self.ax.set_yticklabels(self.parallels) self.ax.yaxis.set_major_formatter(lat_formatter) if self.xmarkers == 'top': self.ax.xaxis.tick_top() if self.ymarkers == 'right': self.ax.yaxis.tick_right() self.ax.grid(b=True, linewidth=0.5, color='k', linestyle=':', zorder=20)
def draw_gridlines(ax, lon_0, bound_box): ''' Draw gridlines and ticks on the map''' if bound_box.count(None) == len(bound_box): #no zoom yticks = np.arange(-90, 100, 10) if lon_0 == 0: xticks = np.arange(-180, 200, 20) else: right_limit = (180 + lon_0) left_limit = (-180 + lon_0) xticks = np.arange(left_limit, right_limit, 20) for ind, val in enumerate(xticks): if val > 180: xticks[ind] = val - 360 if val < -180: xticks[ind] = val + 360 else: #Zoomed plot #Call custom functions to determine gridlines based on # the size of the bounding box yticks = get_yticks(bound_box) xticks = get_xticks(bound_box) ax.set_xticks(xticks, crs=ccrs.PlateCarree()) ax.set_xticklabels(xticks, fontsize=5, fontstretch='condensed') ax.set_yticks(yticks, crs=ccrs.PlateCarree()) ax.set_yticklabels(yticks, fontsize=5) ax.yaxis.tick_left() lon_formatter = cticker.LongitudeFormatter() lat_formatter = cticker.LatitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) ax.yaxis.set_major_formatter(lat_formatter) ax.grid(linewidth=.5, color='white', alpha=0.7, linestyle='dotted') return ax
def _cartopy_map_and_grid(ax, lon_range=[-180, 180], lat_range=[-80, 90], dx=60, dy=20, resolution=None): if resolution is None: ax.add_feature(cftr.LAND, facecolor='#A3A3A3', edgecolor='k', zorder=2) else: ax.coastlines(resolution=resolution, color='k', linewidth=1, zorder=2) ax.set_extent([lon_range[0], lon_range[1], lat_range[0], lat_range[1]], ccrs.PlateCarree()) lon_formatter = cticker.LongitudeFormatter() lat_formatter = cticker.LatitudeFormatter() meridians = np.arange(lon_range[0], lon_range[1], dx) parallels = np.arange(lat_range[0], lat_range[1], dy) ax.set_xticks(meridians, crs=ccrs.PlateCarree()) ax.set_xticklabels(meridians) ax.xaxis.set_major_formatter(lon_formatter) ax.set_yticks(parallels, crs=ccrs.PlateCarree()) ax.set_yticklabels(parallels) ax.yaxis.set_major_formatter(lat_formatter) ax.grid(b=True, linewidth=2, color='k', linestyle='-')
data, transform=ccrs.PlateCarree(), cmap='PRGn', extend='both') # Add coastlines ax.coastlines() # Define the xticks for longitude ax.set_xticks(np.arange(-180, 181, 60), crs=ccrs.PlateCarree()) lon_formatter = cticker.LongitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) # Define the yticks for latitude ax.set_yticks(np.arange(-90, 91, 30), crs=ccrs.PlateCarree()) lat_formatter = cticker.LatitudeFormatter() ax.yaxis.set_major_formatter(lat_formatter) # Add colorbar cbar = plt.colorbar(cs) # Add title plt.title('NCAR-CCSM4 Week 1 Precip anom') # In[8]: #this is identifying a new section of the map to plot dim = ds.sel(lat=slice(25, 60), lon=slice(180, 300)) # In[9]:
def plot_corr_maps(corr_xr, mask_xr=None, map_proj=None, row_dim='split', col_dim='lag', clim='relaxed', hspace=-0.6, size=2.5, cbar_vert=-0.01, units='units', cmap=None, clevels=None, cticks_center=None, drawbox=None, subtitles=None, zoomregion=None, lat_labels=True): ''' zoombox = tuple(east_lon, west_lon, south_lat, north_lat) ''' #%% # # default parameters # row_dim='split'; col_dim='lag'; clim='relaxed'; hspace=-0.6; # size=2.5; cbar_vert=-0.01; units='units'; cmap=None; # clevels=None; cticks_center=None; # drawbox=None; subtitles=None; lat_labels=True; # if map_proj is None: cen_lon = int(corr_xr.longitude.mean().values) map_proj = ccrs.LambertCylindrical(central_longitude=cen_lon) if row_dim not in corr_xr.dims: corr_xr = corr_xr.expand_dims(row_dim, 0) if mask_xr is not None: mask_xr = mask_xr.expand_dims(row_dim, 0) if col_dim not in corr_xr.dims: corr_xr = corr_xr.expand_dims(col_dim, 0) if mask_xr is not None: mask_xr = mask_xr.expand_dims(col_dim, 0) var_n = corr_xr.name rows = corr_xr[row_dim].values cols = corr_xr[col_dim].values rename_dims = {row_dim: 'row', col_dim: 'col'} rename_dims_inv = {'row': row_dim, 'col': col_dim} plot_xr = corr_xr.rename(rename_dims) if mask_xr is not None: plot_mask = mask_xr.rename(rename_dims) dim_coords = plot_xr.squeeze().dims dim_coords = [d for d in dim_coords if d not in ['latitude', 'longitude']] rename_subs = {d: rename_dims_inv[d] for d in dim_coords} lat = plot_xr.latitude lon = plot_xr.longitude zonal_width = abs(lon[-1] - lon[0]).values g = xr.plot.FacetGrid(plot_xr, col='col', row='row', subplot_kws={'projection': map_proj}, sharex=True, sharey=True, aspect=(lon.size) / lat.size, size=size) figheight = g.fig.get_figheight() # ============================================================================= # Coordinate labels # ============================================================================= import cartopy.mpl.ticker as cticker longitude_labels = np.linspace(np.min(lon), np.max(lon), 6, dtype=int) longitude_labels = np.array( sorted(list(set(np.round(longitude_labels, -1))))) latitude_labels = np.linspace(lat.min(), lat.max(), 4, dtype=int) latitude_labels = sorted(list(set(np.round(latitude_labels, -1)))) g.set_ticks(max_xticks=5, max_yticks=5, fontsize='large') g.set_xlabels(label=[str(el) for el in longitude_labels]) g.fig.subplots_adjust(hspace=hspace) if clevels is None: class MidpointNormalize(mcolors.Normalize): def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False): self.midpoint = midpoint mcolors.Normalize.__init__(self, vmin, vmax, clip) def __call__(self, value, clip=None): # I'm ignoring masked values and all kinds of edge cases to make a # simple example... x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1] return np.ma.masked_array(np.interp(value, x, y)) if clim == 'relaxed': vmin_ = np.nanpercentile(plot_xr, 1) vmax_ = np.nanpercentile(plot_xr, 99) elif type(clim) == tuple: vmin_, vmax_ = clim else: vmin_ = plot_xr.min() - 0.01 vmax_ = plot_xr.max() + 0.01 vmin = np.round(float(vmin_), decimals=2) vmax = np.round(float(vmax_), decimals=2) clevels = np.linspace(-max(abs(vmin), vmax), max(abs(vmin), vmax), 17) # choose uneven number for # steps norm = MidpointNormalize(midpoint=0, vmin=clevels[0], vmax=clevels[-1]) ticksteps = 4 else: clevels = clevels norm = None ticksteps = 1 if cmap is None: cmap = plt.cm.RdBu_r else: cmap = cmap for col, c_label in enumerate(cols): xrdatavar = plot_xr.sel(col=c_label) if abs(lon[-1] - 360) <= (lon[1] - lon[0]): xrdatavar = extend_longitude(xrdatavar) for row, r_label in enumerate(rows): print( f"\rPlotting Corr maps {var_n}, {row_dim} {r_label}, {col_dim} {c_label}", end="") plotdata = xrdatavar.sel(row=r_label).rename(rename_subs).squeeze() if mask_xr is not None: xrmaskvar = plot_mask.sel(col=c_label) if abs(lon[-1] - 360) <= (lon[1] - lon[0]): xrmaskvar = extend_longitude(xrmaskvar) plotmask = xrmaskvar.sel(row=r_label) # if plotdata is already masked (with nans): p_nans = int(100 * plotdata.values[np.isnan(plotdata.values)].size / plotdata.size) if mask_xr is not None: # field not completely masked? all_masked = (plotmask.values == False).all() if all_masked == False: if p_nans < 90: plotmask.plot.contour( ax=g.axes[row, col], transform=ccrs.PlateCarree(), subplot_kws={'projection': map_proj}, colors=['black'], linewidths=np.round(zonal_width / 150, 1) + 0.3, levels=[float(vmin), float(vmax)], add_colorbar=False) # try: # im = plotdata.plot.contourf(ax=g.axes[row,col], transform=ccrs.PlateCarree(), # center=0, # levels=clevels, cmap=cmap, # subplot_kws={'projection':map_proj},add_colorbar=False) # except ValueError: # print('could not draw contourf, shifting to pcolormesh') # if no signifcant regions, still plot corr values, but the causal plot must remain empty if mask_xr is None or all_masked == False or (all_masked and 'tigr' not in c_label): im = plotdata.plot.pcolormesh( ax=g.axes[row, col], transform=ccrs.PlateCarree(), center=0, levels=clevels, cmap=cmap, subplot_kws={'projection': map_proj}, add_colorbar=False) elif all_masked and 'tigr' in c_label: g.axes[row, col].text(0.5, 0.5, 'No regions significant', horizontalalignment='center', fontsize='x-large', verticalalignment='center', transform=g.axes[row, col].transAxes) g.axes[row, col].set_extent([lon[0], lon[-1], lat[0], lat[-1]], ccrs.PlateCarree()) # ============================================================================= # Draw (rectangular) box # ============================================================================= if drawbox is not None: from shapely.geometry.polygon import LinearRing def get_ring(coords): '''tuple in format: west_lon, east_lon, south_lat, north_lat ''' west_lon, east_lon, south_lat, north_lat = coords lons_sq = [west_lon, west_lon, east_lon, east_lon] lats_sq = [north_lat, south_lat, south_lat, north_lat] ring = [LinearRing(list(zip(lons_sq, lats_sq)))] return ring if isinstance(drawbox[1], tuple): ring = get_ring(drawbox[1]) elif isinstance(drawbox[1], list): ring = drawbox[1] if drawbox[0] == g.axes.size or drawbox[0] == 'all': g.axes[row, col].add_geometries(ring, ccrs.PlateCarree(), facecolor='none', edgecolor='green', linewidth=2, linestyle='dashed') # ============================================================================= # Subtitles # ============================================================================= if subtitles is not None: fontdict = dict({'fontsize': 18, 'fontweight': 'bold'}) g.axes[row, col].set_title(subtitles[row, col], fontdict=fontdict, loc='center') # ============================================================================= # set coordinate ticks # ============================================================================= # rcParams['axes.titlesize'] = 'xx-large' if map_proj.proj4_params['proj'] in ['merc', 'eqc', 'cea']: ax = g.axes[row, col] ax.set_xticks(longitude_labels[:-1], crs=ccrs.PlateCarree()) ax.set_xticklabels(longitude_labels[:-1], fontsize=12) lon_formatter = cticker.LongitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) g.axes[row, col].set_yticks(latitude_labels, crs=ccrs.PlateCarree()) if lat_labels == True: g.axes[row, col].set_yticklabels(latitude_labels, fontsize=12) lat_formatter = cticker.LatitudeFormatter() g.axes[row, col].yaxis.set_major_formatter(lat_formatter) else: fake_labels = [' ' * len(str(l)) for l in latitude_labels] g.axes[row, col].set_yticklabels(fake_labels, fontsize=12) g.axes[row, col].grid(linewidth=1, color='black', alpha=0.3, linestyle='--') g.axes[row, col].set_ylabel('') g.axes[row, col].set_xlabel('') g.axes[row, col].coastlines(color='black', alpha=0.3, facecolor='grey', linewidth=2) if corr_xr.name is not None: if corr_xr.name[:3] == 'sst': g.axes[row, col].add_feature(cfeature.LAND, facecolor='grey', alpha=0.3) # if row == rows.size-1: # last_ax = g.axes[row,col] # lay out settings plt.tight_layout(pad=1.1 - 0.02 * rows.size, h_pad=None, w_pad=None, rect=None) # height colorbor 1/10th of height of subfigure height = g.axes[-1, 0].get_position().height / 10 bottom_ysub = (figheight / 40) / (rows.size * 2) + cbar_vert # bottom_ysub = last_ax.get_position(original=False).bounds[1] # bottom cbar_ax = g.fig.add_axes([0.25, bottom_ysub, 0.5, height]) #[left, bottom, width, height] if units == 'units' and 'units' in corr_xr.attrs: clabel = corr_xr.attrs['units'] elif units != 'units' and units is not None: clabel = units else: clabel = '' if cticks_center is None: plt.colorbar(im, cax=cbar_ax, orientation='horizontal', norm=norm, label=clabel, ticks=clevels[::ticksteps], extend='neither') else: norm = mcolors.BoundaryNorm(boundaries=clevels, ncolors=256) cbar = plt.colorbar(im, cbar_ax, cmap=cmap, orientation='horizontal', extend='neither', norm=norm, label=clabel) cbar.set_ticks(clevels + 0.5) ticklabels = np.array(clevels + 1, dtype=int) cbar.set_ticklabels(ticklabels, update_ticks=True) cbar.update_ticks() if zoomregion is not None: ax.set_extent(zoomregion, crs=ccrs.PlateCarree()) ax.set_xlim(zoomregion[2:]) ax.set_ylim(zoomregion[:2]) print("\n") #%% return
import netCDF4 import calendar import datetime import csv import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from matplotlib.patches import Polygon import cartopy import cartopy.feature as cfeature import cartopy.mpl.gridliner as gridliner import matplotlib.ticker as mticker import cartopy.mpl.ticker as cartopyticker lon_formatter = cartopyticker.LongitudeFormatter() lat_formatter = cartopyticker.LatitudeFormatter() coast = cfeature.GSHHSFeature(scale="i") import warnings import matplotlib.cbook import logging warnings.filterwarnings("ignore", category=matplotlib.cbook.mplDeprecation) import matplotlib as mpl plt.rcParams.update({ 'savefig.dpi': 300, 'figure.edgecolor': 'w', 'figure.facecolor': 'w', 'savefig.edgecolor': 'w', 'savefig.facecolor': 'w',
def plot_corr_maps(corr_xr, mask_xr=None, map_proj=None, row_dim='split', col_dim='lag', clim='relaxed', hspace=-0.6, wspace=0.02, size=2.5, cbar_vert=-0.01, units='units', cmap=None, clevels=None, clabels=None, cticks_center=None, cbar_tick_dict: dict = {}, drawbox=None, title=None, title_fontdict: dict = None, subtitles: np.ndarray = None, subtitle_fontdict: dict = None, zoomregion=None, aspect=None, n_xticks=5, n_yticks=3, x_ticks: Union[bool, np.ndarray] = None, y_ticks: Union[bool, np.ndarray] = None, add_cfeature: str = None, scatter: np.ndarray = None, col_wrap: int = None, textinmap: list = None): ''' zoomregion = tuple(east_lon, west_lon, south_lat, north_lat) ''' #%% # default parameters # mask_xr=None ; row_dim='split'; col_dim='lag'; clim='relaxed'; wspace=.03; # size=2.5; cbar_vert=-0.01; units='units'; cmap=None; hspace=-0.6; # clevels=None; clabels=None; cticks_center=None; cbar_tick_dict={}; map_proj=None ; # drawbox=None; subtitles=None; title=None; lat_labels=True; zoomregion=None # aspect=None; n_xticks=5; n_yticks=3; title_fontdict=None; x_ticks=None; # y_ticks=None; add_cfeature=None; textinmap=None; scatter=None; col_wrap=None if map_proj is None: cen_lon = int(corr_xr.longitude.mean().values) map_proj = ccrs.LambertCylindrical(central_longitude=cen_lon) if row_dim not in corr_xr.dims: corr_xr = corr_xr.expand_dims(row_dim, 0) if mask_xr is not None and row_dim not in mask_xr.dims: mask_xr = mask_xr.expand_dims(row_dim, 0) if col_dim not in corr_xr.dims: corr_xr = corr_xr.expand_dims(col_dim, 0) if mask_xr is not None and col_dim not in mask_xr.dims: mask_xr = mask_xr.expand_dims(col_dim, 0) var_n = corr_xr.name rows = corr_xr[row_dim].values cols = corr_xr[col_dim].values rename_dims = {row_dim: 'row', col_dim: 'col'} rename_dims_inv = {'row': row_dim, 'col': col_dim} plot_xr = corr_xr.rename(rename_dims) if mask_xr is not None: plot_mask = mask_xr.rename(rename_dims) dim_coords = plot_xr.squeeze().dims dim_coords = [d for d in dim_coords if d not in ['latitude', 'longitude']] rename_subs = {d: rename_dims_inv[d] for d in dim_coords} lat = plot_xr.latitude lon = plot_xr.longitude zonal_width = abs(lon[-1] - lon[0]).values if aspect is None: aspect = (lon.size) / lat.size if col_wrap is None: g = xr.plot.FacetGrid(plot_xr, col='col', row='row', subplot_kws={'projection': map_proj}, sharex=True, sharey=True, aspect=aspect, size=size) else: g = xr.plot.FacetGrid(plot_xr, col='col', subplot_kws={'projection': map_proj}, sharex=True, sharey=True, aspect=aspect, size=size, col_wrap=col_wrap) figheight = g.fig.get_figheight() # ============================================================================= # Coordinate labels # ============================================================================= import cartopy.mpl.ticker as cticker g.set_ticks(fontsize='large') if x_ticks is None or x_ticks is False: #auto-ticks, if False, will be masked longitude_labels = np.linspace(np.min(lon), np.max(lon), n_xticks, dtype=int) longitude_labels = np.array( sorted(list(set(np.round(longitude_labels, -1))))) else: longitude_labels = x_ticks # if x_ticks==False -> no ticklabels if y_ticks is None or y_ticks is False: #auto-ticks, if False, will be masked latitude_labels = np.linspace(lat.min(), lat.max(), n_yticks, dtype=int) latitude_labels = sorted(list(set(np.round(latitude_labels, -1)))) else: latitude_labels = y_ticks # if y_ticks==False -> no ticklabels g.fig.subplots_adjust(hspace=hspace, wspace=wspace) if clevels is None: class MidpointNormalize(mcolors.Normalize): def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False): self.midpoint = midpoint mcolors.Normalize.__init__(self, vmin, vmax, clip) def __call__(self, value, clip=None): # I'm ignoring masked values and all kinds of edge cases to make a # simple example... x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1] return np.ma.masked_array(np.interp(value, x, y)) if clim == 'relaxed': vmin_ = np.nanpercentile(plot_xr, 1) vmax_ = np.nanpercentile(plot_xr, 99) elif type(clim) == tuple: vmin_, vmax_ = clim else: vmin_ = plot_xr.min() - 0.01 vmax_ = plot_xr.max() + 0.01 vmin = np.round(float(vmin_), decimals=2) vmax = np.round(float(vmax_), decimals=2) clevels = np.linspace(-max(abs(vmin), vmax), max(abs(vmin), vmax), 17) # choose uneven number for # steps else: vmin_ = np.nanpercentile(plot_xr, 1) vmax_ = np.nanpercentile(plot_xr, 99) vmin = np.round(float(vmin_), decimals=2) vmax = np.round(float(vmax_), decimals=2) clevels = clevels if cmap is None: cmap = plt.cm.RdBu_r else: cmap = cmap for col, c_label in enumerate(cols): xrdatavar = plot_xr.sel(col=c_label) dlon = abs(lon[1] - lon[0]) if abs(lon[-1] - 360) <= dlon and lon[0] < dlon: xrdatavar = extend_longitude(xrdatavar) for row, r_label in enumerate(rows): if col_wrap is not None: row = np.repeat(list(range(g.axes.shape[0])), g.axes.shape[1])[col] col = (list(range(col_wrap)) * g.axes.shape[0])[col] print( f"\rPlotting Corr maps {var_n}, {row_dim} {r_label}, {col_dim} {c_label}", end="\n") plotdata = xrdatavar.sel(row=r_label).rename(rename_subs).squeeze() if mask_xr is not None: xrmaskvar = plot_mask.sel(col=c_label) if abs(lon[-1] - 360) <= (lon[1] - lon[0]) and lon[0] == 0: xrmaskvar = extend_longitude(xrmaskvar) plotmask = xrmaskvar.sel(row=r_label) # if plotdata is already masked (with nans): p_nans = int(100 * plotdata.values[np.isnan(plotdata.values)].size / plotdata.size) if mask_xr is not None: # field not completely masked? all_masked = (plotmask.values == False).all() if all_masked == False: if p_nans != 100: plotmask.plot.contour( ax=g.axes[row, col], transform=ccrs.PlateCarree(), linestyles=['solid'], colors=['black'], linewidths=np.round(zonal_width / 150, 1) + 0.3, levels=[float(vmin), float(vmax)], add_colorbar=False) # try: # im = plotdata.plot.contourf(ax=g.axes[row,col], transform=ccrs.PlateCarree(), # center=0, # levels=clevels, cmap=cmap, # subplot_kws={'projection':map_proj},add_colorbar=False) # except ValueError: # print('could not draw contourf, shifting to pcolormesh') # if no signifcant regions, still plot corr values, but the causal plot must remain empty if mask_xr is None or all_masked == False or (all_masked and 'tigr' not in str(c_label)): im = plotdata.plot.pcolormesh(ax=g.axes[row, col], transform=ccrs.PlateCarree(), center=0, levels=clevels, cmap=cmap, add_colorbar=False) # subplot_kws={'projection':map_proj}) elif all_masked and 'tigr' in c_label: g.axes[row, col].text(0.5, 0.5, 'No regions significant', horizontalalignment='center', fontsize='x-large', verticalalignment='center', transform=g.axes[row, col].transAxes) # ============================================================================= # Draw (rectangular) box # ============================================================================= if drawbox is not None: from shapely.geometry.polygon import LinearRing def get_ring(coords): '''tuple in format: west_lon, east_lon, south_lat, north_lat ''' west_lon, east_lon, south_lat, north_lat = coords lons_sq = [west_lon, west_lon, east_lon, east_lon] lats_sq = [north_lat, south_lat, south_lat, north_lat] ring = [LinearRing(list(zip(lons_sq, lats_sq)))] return ring if isinstance(drawbox[1], tuple): ring = get_ring(drawbox[1]) elif isinstance(drawbox[1], list): ring = drawbox[1] if drawbox[0] == g.axes.size or drawbox[0] == 'all': g.axes[row, col].add_geometries(ring, ccrs.PlateCarree(), facecolor='none', edgecolor='green', linewidth=2, linestyle='dashed', zorder=4) elif type(drawbox[0]) is tuple: row_box, col_box = drawbox[0] if row == row_box and col == col_box: g.axes[row, col].add_geometries(ring, ccrs.PlateCarree(), facecolor='none', edgecolor='green', linewidth=2, linestyle='dashed', zorder=4) # ============================================================================= # Add text in plot - list([ax_loc, list(tuple(lon,lat,text,kwrgs))]) # ============================================================================= if textinmap is not None: for list_t in textinmap: if list_t[0] == g.axes.size or list_t[0] == 'all': row_text, col_text = row, col if type(list_t[0]) is tuple: row_text, col_text = list_t[0] if type(list_t[1]) is not list: list_t[1] = [list_t[1]] for t in list_t[1]: # loop if multiple textboxes per plot lontext, lattext, text, kwrgs = t # lon in degrees west-east kwrgs.update( dict(horizontalalignment='center', transform=ccrs.Geodetic()) ) # standard settings g.axes[row_text, col_text].text(int(lontext), int(lattext), text, **kwrgs) # ============================================================================= # Add scatter points list([[ax_loc, list(np_array_xy, kwrgs)]]) # ============================================================================= if scatter is not None: for list_s in scatter: loc_ax = list_s[0] if loc_ax == g.axes.size or loc_ax == 'all': # ax_loc row_text, col_text = row, col else: row_text, col_text = loc_ax np_array_xy = list_s[1][ 0] # lon, lat coords - shape=(points, 2) kwrgs_scatter = list_s[1][1] g.axes[row_text, col_text].scatter(x=np_array_xy[:, 0], y=np_array_xy[:, 1], transform=ccrs.PlateCarree(), **kwrgs_scatter) # ============================================================================= # Subtitles # ============================================================================= if subtitles is not None: if subtitle_fontdict is None: subtitle_fontdict = dict({'fontsize': 16}) g.axes[row, col].set_title(np.array(subtitles)[row, col], fontdict=subtitle_fontdict, loc='center') # ============================================================================= # Format coordinate ticks # ============================================================================= if map_proj.proj4_params['proj'] in ['merc', 'eqc', 'cea']: ax = g.axes[row, col] # x-ticks and labels ax.set_xticks(longitude_labels[:], crs=ccrs.PlateCarree()) if x_ticks is not False: ax.set_xticklabels(longitude_labels[:], fontsize=12) lon_formatter = cticker.LongitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) else: fake_labels = [' ' * len(str(l)) for l in longitude_labels] g.axes[row, col].set_xticklabels(fake_labels, fontsize=12) # y-ticks and labels g.axes[row, col].set_yticks(latitude_labels, crs=ccrs.PlateCarree()) if y_ticks is not False: g.axes[row, col].set_yticklabels(latitude_labels, fontsize=12) lat_formatter = cticker.LatitudeFormatter() g.axes[row, col].yaxis.set_major_formatter(lat_formatter) else: fake_labels = [' ' * len(str(l)) for l in latitude_labels] g.axes[row, col].set_yticklabels(fake_labels, fontsize=12) # ============================================================================= # Gridlines # ============================================================================= if type(y_ticks) is bool and type(x_ticks) is bool: if np.logical_and(y_ticks == False, x_ticks == False): # if no ticks, then also no gridlines pass # else: # gl = g.axes[row,col].grid(linewidth=1, color='black', alpha=0.3, # linestyle='--', zorder=4) else: gl = g.axes[row, col].gridlines(crs=ccrs.PlateCarree(), linewidth=.5, color='black', alpha=0.15, linestyle='--', zorder=4) gl.xlocator = mticker.FixedLocator( (longitude_labels % 360 + 540) % 360 - 180) gl.ylocator = mticker.FixedLocator(latitude_labels) g.axes[row, col].set_ylabel('') g.axes[row, col].set_xlabel('') g.axes[row, col].coastlines(color='black', alpha=0.3, facecolor='grey', linewidth=2) # black outline subplot g.axes[row, col].spines['geo'].set_edgecolor('black') if corr_xr.name is not None: if corr_xr.name[:3] == 'sst': g.axes[row, col].add_feature(cfeature.LAND, facecolor='grey', alpha=0.3, zorder=0) if add_cfeature is not None: g.axes[row, col].add_feature(cfeature.__dict__[add_cfeature], facecolor='grey', alpha=0.3, zorder=4) if zoomregion is not None: g.axes[row, col].set_extent(zoomregion, crs=ccrs.PlateCarree()) else: g.axes[row, col].set_extent([lon[0], lon[-1], lat[0], lat[-1]], crs=ccrs.PlateCarree()) # ============================================================================= # lay-out settings FacetGrid and colorbar # ============================================================================= # height colorbor 1/10th of height of subfigure height = g.axes[-1, 0].get_position().height / 10 bottom_ysub = (figheight / 40) / (rows.size * 2) + cbar_vert cbar_ax = g.fig.add_axes([0.25, bottom_ysub, 0.5, height]) #[left, bottom, width, height] if units == 'units' and 'units' in corr_xr.attrs: clabel = corr_xr.attrs['units'] elif units != 'units' and units is not None: clabel = units else: clabel = '' if cticks_center is None: if clabels is None: clabels = clevels[::2] plt.colorbar( im, cax=cbar_ax, orientation='horizontal', # norm=norm, label=clabel, ticks=clabels, extend='neither') else: cbar = plt.colorbar(im, cbar_ax, orientation='horizontal', extend='neither', label=clabel) cbar.set_ticks(clevels + 0.5) cbar.set_ticklabels(np.array(clevels + 1, dtype=int), update_ticks=True) cbar.update_ticks() cbar_ax.tick_params(**cbar_tick_dict) if title is not None: if title_fontdict is None: title_fontdict = dict({'fontsize': 18, 'fontweight': 'bold'}) g.fig.suptitle(title, **title_fontdict) # plt.tight_layout(pad=1.1-0.02*rows.size, h_pad=None, w_pad=None, rect=None) # print("\n") #%% return g.fig
def test_sfc_modis_09a1(fdir): date = datetime.datetime(2017, 8, 13) filename_tag = 'h11v05' fnames = download_modis_https(date, '6/MOD09A1', filename_tag, day_interval=8, fdir_out='data', run=True) extent = [-80.0, -77.5, 32.5, 35.0] mod09 = modis_09a1(fnames=fnames, extent=extent) lon_2d, lat_2d, surf_ref_2d = grid_modis_by_extent( mod09.data['lon']['data'], mod09.data['lat']['data'], mod09.data['ref']['data'][0, ...], extent=extent) # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ import cartopy import cartopy.crs as ccrs import cartopy.feature as cfeature import cartopy.mpl.ticker as cticker import matplotlib.ticker as mticker from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER fig = plt.figure(figsize=(8, 6)) ax1 = fig.add_subplot(111, projection=ccrs.PlateCarree()) ax1.coastlines(color='r', linewidth=1.0, resolution='10m') ax1.set_extent(extent) ax1.scatter(mod09.data['lon']['data'], mod09.data['lat']['data'], c=mod09.data['ref']['data'][0, ...], cmap='Greys_r', s=4, vmin=0.0, vmax=0.1, transform=ccrs.PlateCarree()) # ax1.imshow(surf_ref_2d.T, extent=extent, cmap='Greys_r', origin='lower', vmin=0.0, vmax=0.1, transform=ccrs.PlateCarree()) ax1.set_xticks(np.arange(-80.0, -77.0, 0.5), crs=ccrs.PlateCarree()) ax1.set_yticks(np.arange(32.5, 35.1, 0.5), crs=ccrs.PlateCarree()) lon_formatter = cticker.LongitudeFormatter() lat_formatter = cticker.LatitudeFormatter() ax1.xaxis.set_major_formatter(lon_formatter) ax1.yaxis.set_major_formatter(lat_formatter) ax1.grid(linewidth=1.0, color='blue', alpha=0.8, linestyle='--') plt.savefig('mod09a1_sfc.png', bbox_inches='tight') plt.show() exit() # --------------------------------------------------------------------- # --------------------------------------------------------------------- # lon_2d, lat_2d, surf_ref_2d = grid_modis_by_extent(mod09.data['lon']['data'], mod09.data['lat']['data'], mod09.data['ref']['data'][0, ...], extent=extent) # mod09.data['alb_2d'] = dict(data=surf_ref_2d, name='Surface albedo', units='N/A') # mod09.data['lon_2d'] = dict(data=lon_2d, name='Longitude', units='degrees') # mod09.data['lat_2d'] = dict(data=lat_2d, name='Latitude' , units='degrees') fname_sfc = '%s/sfc.pk' % fdir sfc0 = sfc_sat(sat_obj=mod09, fname=fname_sfc, extent=extent, verbose=True) sfc_2d = mca_sfc_2d(atm_obj=atm0, sfc_obj=sfc0, fname='%s/sfc_2d.bin' % fdir) tags = ['']
def finalfigure(xrdata, file_name, kwrgs): #%% import cartopy.feature as cfeature from shapely.geometry.polygon import LinearRing import cartopy.mpl.ticker as cticker import matplotlib as mpl map_proj = ccrs.PlateCarree(central_longitude=220) lons = xrdata.longitude.values lats = xrdata.latitude.values strvars = [' {} '.format(var) for var in list(xrdata.dims)] var = [var for var in strvars if var not in ' longitude latitude '][0] var = var.replace(' ', '') g = xr.plot.FacetGrid(xrdata, col=var, col_wrap=kwrgs['column'], sharex=True, sharey=True, subplot_kws={'projection': map_proj}, aspect= (xrdata.longitude.size) / xrdata.latitude.size, size=3.5) figwidth = g.fig.get_figwidth() ; figheight = g.fig.get_figheight() lon_tick = xrdata.longitude.values dg = abs(lon_tick[1] - lon_tick[0]) periodic = (np.arange(0, 360, dg).size - lon_tick.size) < 1 and all(lon_tick > 0) longitude_labels = np.linspace(np.min(lon_tick), np.max(lon_tick), 6, dtype=int) longitude_labels = np.array(sorted(list(set(np.round(longitude_labels, -1))))) # longitude_labels = np.concatenate([ longitude_labels, [longitude_labels[-1]], [180]]) # longitude_labels = [-150, -70, 0, 70, 140, 140] latitude_labels = np.linspace(xrdata.latitude.min(), xrdata.latitude.max(), 4, dtype=int) latitude_labels = sorted(list(set(np.round(latitude_labels, -1)))) g.set_ticks(max_xticks=5, max_yticks=5, fontsize='small') g.set_xlabels(label=[str(el) for el in longitude_labels]) if kwrgs['clevels'] == 'default': vmin = np.round(float(xrdata.min())-0.01,decimals=2) ; vmax = np.round(float(xrdata.max())+0.01,decimals=2) clevels = np.linspace(-max(abs(vmin),vmax),max(abs(vmin),vmax),17) # choose uneven number for # steps else: vmin=kwrgs['vmin'] vmax=kwrgs['vmax'] clevels = np.linspace(vmin, vmax,kwrgs['steps']) cmap = kwrgs['cmap'] n_plots = xrdata[var].size for n_ax in np.arange(0,n_plots): ax = g.axes.flatten()[n_ax] # print(n_ax) if periodic == True: plotdata = plot_maps.extend_longitude(xrdata[n_ax]) else: plotdata = xrdata[n_ax].squeeze() im = plotdata.plot.pcolormesh(ax=ax, cmap=cmap, transform=ccrs.PlateCarree(), subplot_kws={'projection': map_proj}, levels=clevels, add_colorbar=False) ax.coastlines(color='black', alpha=0.3, facecolor='grey') ax.add_feature(cfeature.LAND, facecolor='grey', alpha=0.1) ax.set_extent([lons[0], lons[-1], lats[0], lats[-1]], ccrs.PlateCarree()) if kwrgs['subtitles'] == None: pass else: fontdict = dict({'fontsize' : 18, 'fontweight' : 'bold'}) ax.set_title(kwrgs['subtitles'][n_ax], fontdict=fontdict, loc='center') if 'drawbox' in kwrgs.keys(): lons_sq = [-215, -215, -130, -130] #[-215, -215, -125, -125] #[-215, -215, -130, -130] lats_sq = [50, 20, 20, 50] ring = LinearRing(list(zip(lons_sq , lats_sq ))) ax.add_geometries([ring], ccrs.PlateCarree(), facecolor='none', edgecolor='green', linewidth=3.5) if 'ax_text' in kwrgs.keys(): ax.text(0.0, 1.01, kwrgs['ax_text'][n_ax], verticalalignment='bottom', horizontalalignment='left', transform=ax.transAxes, color='black', fontsize=15) if map_proj.proj4_params['proj'] in ['merc', 'eqc']: # print(True) ax.set_xticks(longitude_labels[:-1], crs=ccrs.PlateCarree()) ax.set_xticklabels(longitude_labels[:-1], fontsize=12) lon_formatter = cticker.LongitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) ax.set_yticks(latitude_labels, crs=ccrs.PlateCarree()) ax.set_yticklabels(latitude_labels, fontsize=12) lat_formatter = cticker.LatitudeFormatter() ax.yaxis.set_major_formatter(lat_formatter) ax.grid(linewidth=1, color='black', alpha=0.3, linestyle='--') ax.set_xlabel('') ax.set_ylabel('') else: pass plt.tight_layout() if 'title_h' in kwrgs.keys(): title_height = kwrgs['title_h'] else: title_height = 0.98 g.fig.text(0.5, title_height, kwrgs['title'], fontsize=20, fontweight='heavy', transform=g.fig.transFigure, horizontalalignment='center',verticalalignment='top') if 'adj_fig_h' in kwrgs.keys(): g.fig.set_figheight(figheight*kwrgs['adj_fig_h'], forward=True) if 'adj_fig_w' in kwrgs.keys(): g.fig.set_figwidth(figwidth*kwrgs['adj_fig_w'], forward=True) if 'cbar_vert' in kwrgs.keys(): cbar_vert = 0 + kwrgs['cbar_vert'] else: cbar_vert = 0 if 'cbar_hght' in kwrgs.keys(): # height colorbor 1/10th of height of subfigure cbar_h = g.axes[-1,-1].get_position().height / 10 cbar_hght = cbar_h + kwrgs['cbar_hght'] if 'wspace' in kwrgs.keys(): g.fig.subplots_adjust(wspace=kwrgs['wspace']) if 'hspace' in kwrgs.keys(): g.fig.subplots_adjust(hspace=kwrgs['hspace']) if 'extend' in kwrgs.keys(): extend = kwrgs['extend'][0] else: extend = 'neither' # new cbar positioning y0 = ax.figbox.bounds[1] cbar_ax = g.fig.add_axes([0.25, -y0 + 0.1*y0, 0.5, cbar_hght], label='cbar') if 'clim' in kwrgs.keys(): #adjust the range of colors shown in cbar cnorm = np.linspace(kwrgs['clim'][0],kwrgs['clim'][1],11) vmin = kwrgs['clim'][0] else: cnorm = clevels norm = mpl.colors.BoundaryNorm(boundaries=cnorm, ncolors=256) # cbar = mpl.colorbar.ColorbarBase(cbar_ax, cmap=cmap, orientation='horizontal', # extend=extend, ticks=cnorm, norm=norm) cbar = plt.colorbar(im, cbar_ax, cmap=cmap, orientation='horizontal', extend=extend, norm=norm) if 'cticks_center' in kwrgs.keys(): cbar = plt.colorbar(im, cbar_ax, cmap=cmap, orientation='horizontal', extend=extend, norm=norm) cbar.set_ticks(clevels + 0.5) ticklabels = np.array(clevels+1, dtype=int) cbar.set_ticklabels(ticklabels, update_ticks=True) cbar.update_ticks() if 'extend' in kwrgs.keys(): if kwrgs['extend'][0] == 'min': cbar.cmap.set_under(cbar.to_rgba(kwrgs['vmin'])) cbar.set_label(xrdata.attrs['units'], fontsize=16) cbar.ax.tick_params(labelsize=14) #%% if kwrgs['savefig'] != False: g.fig.savefig(file_name ,dpi=250, bbox_inches='tight') #%% return
def plotc(var,lon=[],lat=[],title='',clf=[],cl=[], cmap='coolwarm',lon1=[],lon2=[],lat1=[],lat2=[],bar=1,p=1,m=1,lmask=0, center=[],alpha=.95, ax=[],fig=[]): if len(lon)<1: lon=var.lon; if len(lat)<1: lat=var.lat; if nanmax(lon)>355: if nanmax(lon)<360: var, lon = add_cyclic_point(var, coord=lon) # if lon1== -180: # if lon2==180: # if nanmax(lon)>182: # lon1=0 # lon2=359.99 try: len(lon1) lon1=lon[0] except: lon1=lon1 try: len(lon2) lon2=lon[-1] except: lon2=lon2 if lon2>359.9: lon2=359.9 try: len(lat1) lat1=lat[0] except: lat1=lat1 try: len(lat2) lat2=lat[-1] except: lat2=lat2 # if lon1== -180: # if lon2==180: # if lat1==-90: # if lat2==90: # lon1=nanmin(lon) # lon2=nanmax(lon) # lat1=nanmin(lat) # lat2=nanmax(lat) try: len(center) if lon[0]<0: center=0 if lon[0]>-1: center=180 except: center=center-.01 try: len(ax); ax=plt.axes(projection=ccrs.PlateCarree(central_longitude=center)) except: ax=ax ax.set_extent([lon1,lon2,lat1,lat2], crs=ccrs.PlateCarree(central_longitude=center)) ax.coastlines(linewidth=.6) parallels = arange(lat1,lat2+1, (lat2-lat1)//4) meridians = arange(lon1,lon2,(lon2-lon1)//4) if (abs(lat2-lat1))>89: parallels = arange(-90,90+1,30) if (abs(lon2-lon1))>179: if lon1<0: meridians = arange(-180,180+1,60) if lon1>-1: meridians = arange(0,360+1,60) # if lmask==1: # ax.fillcontinents(color='white', lake_color='white', ax=None, zorder=None, alpha=None) if m==1: ax.set_yticks(parallels, crs=ccrs.PlateCarree()) lat_formatter = cticker.LatitudeFormatter() ax.yaxis.set_major_formatter(lat_formatter) if p==1: ax.set_xticks(meridians, crs=ccrs.PlateCarree()) lon_formatter = cticker.LongitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) ax.set_extent([lon1,lon2,lat1,lat2], crs=ccrs.PlateCarree(central_longitude=center)) if len(cl)==1: if len(clf)>1: csf = ax.contourf(lon,lat,var,clf,extend='both',cmap=cmap,transform = ccrs.PlateCarree() , alpha=alpha) if bar==1: try: len(fig); cb = plt.colorbar(csf,orientation='horizontal',extend='both', pad=.1, aspect=40, shrink=.85, label='') except: cb= fig.colorbar(csf,ax=ax, orientation='horizontal',extend='both',pad=.1,aspect=40, shrink=.85, label='') cs = ax.contour(lon,lat,var,cl,colors='k',linewidths=0.3,transform = ccrs.PlateCarree() , alpha=alpha) #plt.clabel(cs, inline=True, fmt='%1.1f', fontsize=6, colors='k') else: csf = ax.contourf(lon,lat,var,extend='both',cmap=cmap,transform = ccrs.PlateCarree() , alpha=alpha) #cb = ax.colorbar(csf,orientation='horizontal',extend='both', pad=.1, aspect=40, shrink=.85, label='',size="3%", pad="9%") if bar==1: try: len(fig); cb = plt.colorbar(csf,orientation='horizontal',extend='both', pad=.1, aspect=40, shrink=.85, label='') except: cb= fig.colorbar(csf,ax=ax, orientation='horizontal',extend='both',pad=.1,aspect=40, shrink=.85, label='') cs = ax.contour(lon,lat,var,colors='k',linewidths=0.3,transform = ccrs.PlateCarree() , alpha=alpha) #plt.clabel(cs, inline=True, fmt='%1.1f', fontsize=6, colors='k') else: if len(clf)>1: csf = ax.contourf(lon,lat,var,clf,extend='both',cmap=cmap,transform = ccrs.PlateCarree() , alpha=alpha) if bar==1: try: len(fig); cb = plt.colorbar(csf,orientation='horizontal',extend='both', pad=.1, aspect=40, shrink=.85, label='') except: cb= fig.colorbar(csf,ax=ax, orientation='horizontal',extend='both',pad=.1,aspect=40, shrink=.85, label='') else: csf = ax.contourf(lon,lat,var,extend='both',cmap=cmap,transform = ccrs.PlateCarree() , alpha=alpha) #cb = ax.colorbar(csf,orientation='horizontal',extend='both', pad=.1, aspect=40, shrink=.85, label='',size="3%", pad="9%") if bar==1: try: len(fig); cb = plt.colorbar(csf,orientation='horizontal',extend='both', pad=.1, aspect=40, shrink=.85, label='') except: cb= fig.colorbar(csf,ax=ax, orientation='horizontal',extend='both',pad=.1,aspect=40, shrink=.85, label='') #plt.clabel(cs, inline=True, fmt='%1.1f', fontsize=6, colors='k') # plt.title(title,fontsize=9) ax.set_title(title,fontsize=9) return(fig, ax)