def test_offset(): crs = ccrs.EqualEarth() crs_offset = ccrs.EqualEarth(false_easting=1234, false_northing=-4321) other_args = {'ellps=WGS84', 'lon_0=0', 'x_0=1234', 'y_0=-4321'} check_proj_params('eqearth', crs_offset, other_args) assert tuple(np.array(crs.x_limits) + 1234) == crs_offset.x_limits assert tuple(np.array(crs.y_limits) - 4321) == crs_offset.y_limits
def plot_difference_EqualEarth(var, DJF_mask, JJA_mask): """ Plot the 1 x 3 figures using EqualEarth projection """ fig = plt.figure(figsize=(16, 4)) ax1 = plt.subplot(131, projection=ccrs.EqualEarth()) im1 = DJF_mask[var].plot(ax=ax1, transform=ccrs.PlateCarree(), vmax=100, vmin=0, add_colorbar=False) ax1.coastlines() plt.colorbar(im1, orientation="horizontal", pad=0.15) #plt.show() ax2 = plt.subplot(132, projection=ccrs.EqualEarth()) im2 = JJA_mask[var].plot(ax=ax2, transform=ccrs.PlateCarree(), vmax=100, vmin=0, add_colorbar=False) a2.coastlines() plt.colorbar(im2, orientation="horizontal", pad=0.15) #plt.show() DJF_minus_JJA = DJF_mask[var] - JJA_mask[var] ax3 = plt.subplot(133, projection=ccrs.EqualEarth()) im3 = DJF_minus_JJA.plot(ax=ax3, transform=ccrs.PlateCarree(), add_colorbar=False) plt.colorbar(im3, orientation="horizontal", pad=0.15) plt.show()
def plot(mask, d, nuts): proj = ccrs.EqualEarth(central_longitude=0) ax = plt.subplot(111, projection=proj) d.isel(time=1).temp.plot.pcolormesh(ax=ax, transform=ccrs.PlateCarree()) ax.coastlines() plt.show() plt.figure(figsize=(12, 8)) ax = plt.axes() mask.plot(ax=ax) nuts.plot(ax=ax, alpha=0.8, facecolor='none', lw=1) plt.show()
def test_default(): eqearth = ccrs.EqualEarth() other_args = {'ellps=WGS84', 'lon_0=0'} check_proj_params('eqearth', eqearth, other_args) assert_almost_equal(eqearth.x_limits, [-17243959.0622169, 17243959.0622169]) assert_almost_equal(eqearth.y_limits, [-8392927.59846646, 8392927.59846646]) # Expected aspect ratio from the paper. assert_almost_equal(np.diff(eqearth.x_limits) / np.diff(eqearth.y_limits), 2.05458, decimal=5)
def test_central_longitude(lon): eqearth = ccrs.EqualEarth(central_longitude=lon) other_args = {'ellps=WGS84', 'lon_0={}'.format(lon)} check_proj_params(eqearth, other_args) assert_almost_equal(eqearth.x_limits, [-17243959.0622169, 17243959.0622169], decimal=5) assert_almost_equal(eqearth.y_limits, [-8392927.59846646, 8392927.59846646]) # Expected aspect ratio from the paper. assert_almost_equal(np.diff(eqearth.x_limits) / np.diff(eqearth.y_limits), 2.05458, decimal=5)
def test_eccentric_globe(): globe = ccrs.Globe(semimajor_axis=1000, semiminor_axis=500, ellipse=None) eqearth = ccrs.EqualEarth(globe=globe) other_args = {'a=1000', 'b=500', 'lon_0=0'} check_proj_params('eqearth', eqearth, other_args) assert_almost_equal(eqearth.x_limits, [-2248.43664092550, 2248.43664092550]) assert_almost_equal(eqearth.y_limits, [-1094.35228122148, 1094.35228122148]) # Expected aspect ratio from the paper. assert_almost_equal(np.diff(eqearth.x_limits) / np.diff(eqearth.y_limits), 2.05458, decimal=5)
def test_multiple_projections_520(): # Test projections added in Proj 5.2.0. fig = plt.figure(figsize=(2, 2)) ax = fig.add_subplot(1, 1, 1, projection=ccrs.EqualEarth()) ax.set_global() ax.coastlines() ax.plot(-0.08, 51.53, 'o', transform=ccrs.PlateCarree()) ax.plot([-0.08, 132], [51.53, 43.17], color='red', transform=ccrs.PlateCarree()) ax.plot([-0.08, 132], [51.53, 43.17], color='blue', transform=ccrs.Geodetic())
def plot_OHC_anomaly(self): """""" ctrl_qd = xr.open_dataset(f'{path_samoc}/OHC/OHC_integrals_ctrl_qd.nc', decode_times=False) lpd_qd = xr.open_dataset(f'{path_samoc}/OHC/OHC_integrals_lpd_qd.nc' , decode_times=False) maxv = [] for j, depths in enumerate([(0,6000), (0,100), (0,700), (700,2000)]): key = f'OHC_vertical_{depths[0]}_{depths[1]}m' maxv.append(np.max([np.abs(ctrl_qd[key]).max(), np.abs(lpd_qd[key]).max()])/4) print(maxv) for y in range(250): f, ax = plt.subplots(4, 3 , figsize=(10,10), gridspec_kw={"width_ratios":[1,1, 0.05]}, subplot_kw=dict(projection=ccrs.EqualEarth(central_longitude=300))) for i, ds in enumerate([ctrl_qd, lpd_qd]): name = ['CTRL', 'LPD'][i] MASK = boolean_mask(['ocn_rect', 'ocn_low'][i], mask_nr=0) if i==0: X, Y = np.meshgrid(ds.t_lon, ds.t_lat) else: X, Y = ds.TLONG, ds.TLAT for j, depths in enumerate([(0,6000), (0,100), (0,700), (700,2000)]): key = f'OHC_vertical_{depths[0]}_{depths[1]}m' im = ax[j,i].pcolormesh(X, Y, ds[key][y,:,:].where(MASK), transform=ccrs.PlateCarree(), vmin=-maxv[j], vmax=maxv[j], cmap=cmocean.cm.balance) ax[j,i].add_feature(cartopy.feature.LAND, zorder=2, edgecolor='black', facecolor='w') if j==0: year = f'{ds.time.values[y]:3.0f}' ax[0,i].text(.5, 1.1, f'{name} (year {year})', transform=ax[0,i].transAxes, ha='center') ax[j,i].text(.5, 1.02, ['full depth (0-6000m)', 'surface (0-100m)', 'upper ocean (0-700m)', 'lower ocean (700-2000m)'][j], transform=ax[j,i].transAxes, ha='center') if i==1: cb = f.colorbar(im, ax=ax[j,2], orientation='vertical', label=r'OHC [J/m$^{2}$]')#, ticks=np.arange(-3e16,4e16,1e16)) cb.outline.set_visible(False) plt.savefig(f'{path_results}/OHC/OHC-video/OHC_vert_qd_ctrl_lpd_{y:03d}') return
def plot_pcolormesh_global(xx, yy, data, data_projection_code, global_code, cmin, cmax, subplots=[1, 1, 1]): plt.subplots = subplots # https://scitools.org.uk/cartopy/docs/latest/crs/projections.html if global_code == 0: ax = plt.axes(projection=ccrs.Robinson()) elif global_code == 1: ax = plt.axes(projection=ccrs.EqualEarth()) elif global_code == 2: ax = plt.axes(projection=ccrs.InterruptedGoodeHomolosine()) elif global_code == 3: ax = plt.axes(projection=ccrs.PlateCarree()) # lat/lon ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=False, linewidth=1, color='white', alpha=0.5, linestyle='--') projection = ccrs.epsg(data_projection_code) plt.pcolormesh(xx, yy, data, transform=projection, vmin=cmin, vmax=cmax, cmap='jet') plt.colorbar() ax.coastlines('110m', linewidth=0.8) ax.add_feature(cfeature.LAND)
capex_colors = n.carriers.color opex_alpha = 1 opex_colors = ( capex_colors.apply(lambda c: mpl.colors.to_rgba(c, opex_alpha)).apply( lambda c: mpl.colors.to_hex(c, True)).rename(lambda s: s + ' opex')) emission_color = color.loc[['co2_cost']] bus_colors = pd.concat([capex_colors, opex_colors, emission_color]) # %% bus_scale = 2e-10 branch_scale = 4e-7 fig, ax = plt.subplots(figsize=(4.5, 4.5), subplot_kw={'projection': ccrs.EqualEarth()}) n.plot( line_widths=branch_widths['Line'] * branch_scale, link_widths=branch_widths['Link'] * branch_scale, line_colors=branch_colors['Line'], link_colors=branch_colors['Link'], ax=ax, bus_alpha=None, geomap='10m', boundaries=regions.total_bounds[[0, 2, 1, 3]], bus_sizes=bus_sizes * bus_scale, bus_colors=bus_colors, ) regions.loc[[sink]].plot(ax=ax, transform=ccrs.PlateCarree(), aspect='equal') legend_colors = (n.carriers.set_index('nice_name').color.append(
def projection(self): if self.proj is None: return ccrs.PlateCarree() proj_dict = ast.literal_eval(self.proj) user_proj = proj_dict.pop("proj") if user_proj == 'PlateCarree': self.xylim_supported = True return ccrs.PlateCarree(**proj_dict) elif user_proj == 'AlbersEqualArea': return ccrs.AlbersEqualArea(**proj_dict) elif user_proj == 'AzimuthalEquidistant': return ccrs.AzimuthalEquidistant(**proj_dict) elif user_proj == 'EquidistantConic': return ccrs.EquidistantConic(**proj_dict) elif user_proj == 'LambertConformal': return ccrs.LambertConformal(**proj_dict) elif user_proj == 'LambertCylindrical': return ccrs.LambertCylindrical(**proj_dict) elif user_proj == 'Mercator': return ccrs.Mercator(**proj_dict) elif user_proj == 'Miller': return ccrs.Miller(**proj_dict) elif user_proj == 'Mollweide': return ccrs.Mollweide(**proj_dict) elif user_proj == 'Orthographic': return ccrs.Orthographic(**proj_dict) elif user_proj == 'Robinson': return ccrs.Robinson(**proj_dict) elif user_proj == 'Sinusoidal': return ccrs.Sinusoidal(**proj_dict) elif user_proj == 'Stereographic': return ccrs.Stereographic(**proj_dict) elif user_proj == 'TransverseMercator': return ccrs.TransverseMercator(**proj_dict) elif user_proj == 'UTM': return ccrs.UTM(**proj_dict) elif user_proj == 'InterruptedGoodeHomolosine': return ccrs.InterruptedGoodeHomolosine(**proj_dict) elif user_proj == 'RotatedPole': return ccrs.RotatedPole(**proj_dict) elif user_proj == 'OSGB': self.xylim_supported = False return ccrs.OSGB(**proj_dict) elif user_proj == 'EuroPP': self.xylim_supported = False return ccrs.EuroPP(**proj_dict) elif user_proj == 'Geostationary': return ccrs.Geostationary(**proj_dict) elif user_proj == 'NearsidePerspective': return ccrs.NearsidePerspective(**proj_dict) elif user_proj == 'EckertI': return ccrs.EckertI(**proj_dict) elif user_proj == 'EckertII': return ccrs.EckertII(**proj_dict) elif user_proj == 'EckertIII': return ccrs.EckertIII(**proj_dict) elif user_proj == 'EckertIV': return ccrs.EckertIV(**proj_dict) elif user_proj == 'EckertV': return ccrs.EckertV(**proj_dict) elif user_proj == 'EckertVI': return ccrs.EckertVI(**proj_dict) elif user_proj == 'EqualEarth': return ccrs.EqualEarth(**proj_dict) elif user_proj == 'Gnomonic': return ccrs.Gnomonic(**proj_dict) elif user_proj == 'LambertAzimuthalEqualArea': return ccrs.LambertAzimuthalEqualArea(**proj_dict) elif user_proj == 'NorthPolarStereo': return ccrs.NorthPolarStereo(**proj_dict) elif user_proj == 'OSNI': return ccrs.OSNI(**proj_dict) elif user_proj == 'SouthPolarStereo': return ccrs.SouthPolarStereo(**proj_dict)
# ------------- # ax = fig.add_subplot(gs[0, 2]) ax = fig.add_axes([0.8, 0.05 + 0.5, 0.03, 0.8 / 2]) # plt.colorbar(pcm, cax=ax, ticks=[40, 75, 100], label='Resolution (km)', extend='max') plt.colorbar(pcm, cax=ax, ticks=[40, 55, 70], label='Resolution (km)', extend='max') # cbar = grid.cbar_axes[0].colorbar(pcm, ticks=[75, 100, 125]) # cbar.ax.set_ylabel('Resolution (km)', rotation=270) # ax = fig.add_subplot(gs[1, :], projection=ccrs.EqualEarth()) import cartopy.feature as cfeature ax = fig.add_axes([0.02, 0.02, 0.96, 0.48], projection=ccrs.EqualEarth()) ax.set_global() region = maps.get_countries( '/home/liam/Downloads').loc['United States of America'].geometry maps.features.add_polygons(ax, region, outline=True, zorder=100, linewidth=1, edgecolor='k') ax.add_feature(cfeature.OCEAN, linewidth=0, color='#f0f0f0') ax.add_feature(cfeature.LAND, facecolor='none', linewidth=0, color='#bdbdbd') ax.add_feature(cfeature.LAKES, linewidth=0, color='#f0f0f0') ax.outline_patch.set_linewidth(0.5) ax.outline_patch.set_edgecolor('gray') for nf in range(6):
ds = xr.open_dataset(filename) grid = CubeSphere(180) fig = plt.figure(figsize=(8, 8)) gs = plt.GridSpec(3, 1, height_ratios=[10, 10, 1], left=0.05, right=0.95, top=0.98, bottom=0.07, wspace=0.01, hspace=0.1) ax = fig.add_subplot(gs[0, 0], projection=ccrs.EqualEarth()) ax.coastlines() ax.set_global() da_ctl = ds[species].isel(lev=layer).sel(ID='CTL').squeeze() cmap = 'cividis' norm = plt.Normalize(float(da_ctl.quantile(0.05)), float(da_ctl.quantile(0.95))) for face in tqdm(range(6)): pcolormesh2(grid.xe(face), grid.ye(face), da_ctl.isel(face=face), 180 if face != 2 else 20, norm, cmap=cmap)
payments = xr.open_dataset(snakemake.input.payments).sum(source_carrier) w = ntl.cost.snapshot_weightings(n) payments['one_port_operational_cost'] /= w payments['co2_cost'] /= w demand = ntl.power_demand(n, per_carrier=True).sel(carrier='Load', drop=True)\ .rename(bus="sink") prices = ((payments/demand).mean('snapshot').to_dataframe() .reindex(regions.index).fillna(0)) for col in prices: name = to_explanation[col] fig, ax = plt.subplots(subplot_kw={"projection": ccrs.EqualEarth()}, figsize=(5, 4)) ax.spines['geo'].set_visible(False) regions.plot(column=prices[col], legend=True, ax=ax, transform=ccrs.PlateCarree(), aspect='equal', legend_kwds={'label': f'Average LMP for \n {name} [€/MWh]'}) fig.canvas.draw() fig.tight_layout() fig.savefig(snakemake.output.folder + f'/{col}_average.png') fig, ax = plt.subplots(subplot_kw={"projection": ccrs.EqualEarth()}, figsize=(5, 4)) ax.spines['geo'].set_visible(False) lmp = n.buses_t.marginal_price.mean().reindex(regions.index).fillna(0) regions.plot(column=lmp, legend=True, ax=ax,
if 'snakemake' not in globals(): from _helpers import mock_snakemake snakemake = mock_snakemake('plot_network', nname='de50') plt.rc('axes', titlesize='medium') plt.rc('figure', dpi=300) n = pypsa.Network(snakemake.input.network) regions = gpd.read_file(snakemake.input.regions) bus_scale = 1.5e-5 branch_scale = 5e-4 fig, axes = plt.subplots(1, 2, subplot_kw={"projection": ccrs.EqualEarth()}, figsize=(8, 4)) # existent bus_sizes = n.generators.groupby(["bus", "carrier"]).p_nom_min.sum() plot = n.plot(bus_sizes=bus_sizes * bus_scale, line_widths=n.lines.s_nom_min * branch_scale, link_widths=n.links.p_nom_min * branch_scale, ax=axes[0], geomap='10m', title='Lower Capacity Bounds', boundaries=regions.total_bounds[[0, 2, 1, 3]]) regions.plot(ax=axes[0], transform=ccrs.PlateCarree(), aspect='equal', facecolor='white', edgecolor='blue',
def component_plot(n, linewidth_factor=5e3, gen_size_factor=5e4, sus_size_factor=1e4, carrier_colors=None, carrier_names=None, figsize=(10, 5), boundaries=None, **kwargs): """ Plot a pypsa.Network generation and storage capacity Parameters ---------- n : pypsa.Network Optimized network linewidth_factor : float, optional Scale factor of line widths. The default is 5e3. gen_size_factor : float, optional Scale factor of generator capacities. The default is 5e4. sus_size_factor : float, optional Scale factor of storage capacities. The default is 1e4. carrier_colors : pd.Series, optional Colors of the carriers. The default is None. carrier_names : pd.Series, optional Nice names of the carriers. The default is None. figsize : tuple, optional figsize of resulting image. The default is (10, 5). boundaries : tuple, optional Geographical bounds of the geomap. The default is [-10. , 30, 36, 70]. Returns ------- fig, ax Figure and axes of the corresponding plot. """ if carrier_colors is None: carrier_colors = n.carriers.color fallback = pd.Series(n.carriers.index.str.title(), n.carriers.index) carrier_names = n.carriers.nice_name.replace( '', np.nan).fillna(fallback) line_colors = {'cur': "purple", 'exp': to_hex(to_rgba("red", 0.5), True)} gen_sizes = n.generators.groupby(['bus', 'carrier']).p_nom_opt.sum() store_sizes = n.storage_units.groupby(['bus', 'carrier']).p_nom_opt.sum() # PLOT try: import cartopy.crs as ccrs projection = ccrs.EqualEarth() kwargs.setdefault('geomap', '50m') except ImportError: projection = None logger.warn('Could not import cartopy, drawing map disabled') fig, (ax, ax2) = plt.subplots(1, 2, figsize=figsize, subplot_kw={"projection": projection}) n.plot(bus_sizes=gen_sizes / gen_size_factor, bus_colors=carrier_colors, line_widths=n.lines.s_nom_min.div(linewidth_factor), link_widths=n.links.p_nom_min.div(linewidth_factor), line_colors=line_colors['cur'], link_colors=line_colors['cur'], boundaries=boundaries, title='Generation and \nTransmission Capacities', ax=ax, **kwargs) n.plot( bus_sizes=store_sizes / sus_size_factor, bus_colors=carrier_colors, line_widths=( n.lines.s_nom_opt - n.lines.s_nom_min) / linewidth_factor, link_widths=( n.links.p_nom_opt - n.links.p_nom_min) / linewidth_factor, line_colors=line_colors['exp'], link_colors=line_colors['exp'], boundaries=boundaries, title='Storages Capacities and \nTransmission Expansion', ax=ax2, **kwargs) ax.axis('off') # ax.artists[2].set_title('Carriers') # LEGEND add capcacities reference_caps = [10e3, 5e3, 1e3] for axis, scale in zip((ax, ax2), (gen_size_factor, sus_size_factor)): handles = make_legend_circles_for(reference_caps, scale=scale / projected_area_factor(axis)**2 / 3, facecolor="w", edgecolor='grey', alpha=.5) labels = ["{} GW".format(int(s / 1e3)) for s in reference_caps] handler_map = make_handler_map_to_scale_circles_as_in(axis) l2 = axis.legend(handles, labels, framealpha=0.7, loc="upper left", bbox_to_anchor=(0., 1), frameon=True, # edgecolor='w', title='Capacity', handler_map=handler_map) axis.add_artist(l2) reference_caps.pop(0) # LEGEND Transmission handles, labels = [], [] for s in (10, 5): handles.append(plt.Line2D([0], [0], color=line_colors['cur'], linewidth=s * 1e3 / linewidth_factor)) labels.append("/") for s in (10, 5): handles.append(plt.Line2D([0], [0], color=line_colors['exp'], linewidth=s * 1e3 / linewidth_factor)) labels.append("{} GW".format(s)) fig.artists.append(fig.legend(handles, labels, loc="lower left", bbox_to_anchor=(1., .0), frameon=False, ncol=2, columnspacing=0.5, title='Transmission Exist./Exp.')) # legend generation colors colors = carrier_colors[n.generators.carrier.unique()] if carrier_names is not None: colors = colors.rename(carrier_names) fig.artists.append(fig.legend(*handles_labels_for(colors), loc='upper left', bbox_to_anchor=(1, 1), frameon=False, title='Generation carrier')) # legend storage colors colors = carrier_colors[n.storage_units.carrier.unique()] if carrier_names is not None: colors = colors.rename(carrier_names) fig.artists.append(fig.legend(*handles_labels_for(colors), loc='upper left', bbox_to_anchor=(1, 0.55), frameon=False, title='Storage carrier')) fig.canvas.draw() fig.tight_layout() return fig, (ax, ax2)
from __future__ import print_function, division from __future__ import absolute_import import pypsa, os import numpy as np import cartopy.crs as ccrs import matplotlib.pyplot as plt network = pypsa.Network() folder_name = "ac-dc-data" network.import_from_csv_folder(folder_name) network.lopf(network.snapshots) fig, ax = plt.subplots(subplot_kw={'projection': ccrs.EqualEarth()}, figsize=(5, 5)) line_colors = network.lines.bus0.map(network.buses.carrier)\ .replace({'AC': 'indianred', 'DC': 'limegreen'}) network.plot( bus_colors='grey', ax=ax, margin=.5, line_widths={ 'Line': 2., 'Link': 0 }, line_colors=line_colors, geomap='10m', title='Mixed AC-DC (red - green) network', # flow='mean',
ll = laea.to_latlong() transform = pyproj.Transformer.from_proj(ll, laea, always_xy=True).transform xe_laea, ye_laea = transform(xe, ye) xy_ll = get_minor_xy(xe, ye) xy_laea = get_minor_xy(xe_laea, ye_laea) for i in range(n-1): for j in range(n-1): res = np.sqrt(shapely.geometry.Polygon(xy_laea[i, j, ...]).area/1e6) ax.add_geometries([shapely.geometry.Polygon(xy_ll[i, j, ...])], facecolor='none', linewidth=lw(res), crs=ccrs.PlateCarree()) import gcpy.grid fig = plt.Figure(figsize=(4.72441, 2.5), dpi=300) ax = fig.add_axes([0.02, 0, 0.96, 1], projection=ccrs.EqualEarth()) import cartopy.feature as cfeature ax.set_global() ax.add_feature(cfeature.OCEAN, linewidth=0, color='w') ax.add_feature(cfeature.LAND, facecolor='none', linewidth=0, color='#bdbdbd') ax.add_feature(cfeature.LAKES, linewidth=0, color='w') ax.outline_patch.set_linewidth(0.4) ax.outline_patch.set_edgecolor('gray') fname='C180e-US.png' grid, _ = gcpy.grid.make_grid_CS(24) #gcpy.grid.make_grid_SG(90, 10, 240.5, 37.2) for nf in [1]: #tqdm(range(6)): xe = grid['lon_b'][nf, ...] % 360
def _create_projection_axis(projection_type, user_lon_0, lat_lim, subplot_grid, less_output): """Set appropriate axis for projection type See plot_proj_to_latlon_grid for input parameter definitions. Returns ------- ax : matplotlib axis object defined with the correct projection show_grid_labels : logical True = show the grid labels, only currently supported for PlateCarree and Mercator projections """ # initialize (optional) subplot variables row = [] col = [] ind = [] if subplot_grid is not None: if type(subplot_grid) is dict: row = subplot_grid['nrows'] col = subplot_grid['ncols'] ind = subplot_grid['index'] elif type(subplot_grid) is list: row = subplot_grid[0] col = subplot_grid[1] ind = subplot_grid[2] else: raise TypeError('Unexpected subplot_grid type: ', type(subplot_grid)) if projection_type == 'Mercator': if subplot_grid is not None: ax = plt.subplot( row, col, ind, projection=ccrs.Mercator(central_longitude=user_lon_0)) else: ax = plt.axes(projection=ccrs.Mercator( central_longitude=user_lon_0)) show_grid_labels = True elif projection_type == 'AlbersEqualArea': if subplot_grid is not None: ax = plt.subplot( row, col, ind, projection=ccrs.AlbersEqualArea(central_longitude=user_lon_0)) else: ax = plt.axes(projection=ccrs.AlbersEqualArea( central_longitude=user_lon_0)) show_grid_labels = False elif projection_type == 'EqualEarth': if subplot_grid is not None: ax = plt.subplot( row, col, ind, projection=ccrs.EqualEarth(central_longitude=user_lon_0)) else: ax = plt.axes(projection=ccrs.EqualEarth( central_longitude=user_lon_0)) show_grid_labels = False elif projection_type == 'PlateCaree': if subplot_grid is not None: ax = plt.subplot( row, col, ind, projection=ccrs.PlateCarree(central_longitude=user_lon_0)) else: ax = plt.axes(projection=ccrs.PlateCarree( central_longitude=user_lon_0)) show_grid_labels = True elif projection_type == 'cyl': if subplot_grid is not None: ax = plt.subplot(row, col, ind, projection=ccrs.LambertCylindrical( central_longitude=user_lon_0)) else: ax = plt.axes(projection=ccrs.LambertCylindrical( central_longitude=user_lon_0)) show_grid_labels = False elif projection_type == 'robin': if subplot_grid is not None: ax = plt.subplot( row, col, ind, projection=ccrs.Robinson(central_longitude=user_lon_0)) else: ax = plt.axes(projection=ccrs.Robinson( central_longitude=user_lon_0)) show_grid_labels = False elif projection_type == 'ortho': if subplot_grid is not None: ax = plt.subplot( row, col, ind, projection=ccrs.Orthographic(central_longitude=user_lon_0)) else: ax = plt.axes(projection=ccrs.Orthographic( central_longitude=user_lon_0)) show_grid_labels = False elif projection_type == 'stereo': if lat_lim > 0: stereo_proj = ccrs.NorthPolarStereo() else: stereo_proj = ccrs.SouthPolarStereo() if subplot_grid is not None: ax = plt.subplot(row, col, ind, projection=stereo_proj) else: ax = plt.axes(projection=stereo_proj) show_grid_labels = False elif projection_type == 'InterruptedGoodeHomolosine': if subplot_grid is not None: ax = plt.subplot(row, col, ind, projection=ccrs.InterruptedGoodeHomolosine( central_longitude=user_lon_0)) else: ax = plt.axes(projection=ccrs.InterruptedGoodeHomolosine( central_longitude=user_lon_0)) show_grid_labels = False else: raise NotImplementedError( 'projection type must be either "Mercator", "PlateCaree", "AlbersEqualArea", "cyl", "robin", "ortho", "stereo", or "InterruptedGoodeHomolosine"' ) if not less_output: print('Projection type: ', projection_type) return (ax, show_grid_labels)
# ------------- # ax = fig.add_subplot(gs[0, 2]) ax = fig.add_axes([0.8, 0.05 + 0.5, 0.03, 0.8 / 2]) # plt.colorbar(pcm, cax=ax, ticks=[40, 75, 100], label='Resolution (km)', extend='max') plt.colorbar(pcm, cax=ax, ticks=[10, 25, 50, 75, 100, 125], label='Resolution (km)', extend='max') # cbar = grid.cbar_axes[0].colorbar(pcm, ticks=[75, 100, 125]) # cbar.ax.set_ylabel('Resolution (km)', rotation=270) # ax = fig.add_subplot(gs[1, :], projection=ccrs.EqualEarth()) import cartopy.feature as cfeature ax = fig.add_axes([0.02, 0.02, 0.96, 0.48], projection=ccrs.EqualEarth()) ax.set_global() region = maps.get_provinces_and_states( '/home/liam/Downloads').loc['California'].geometry maps.features.add_polygons(ax, region, outline=True, zorder=100, linewidth=1, edgecolor='k') ax.add_feature(cfeature.OCEAN, linewidth=0, color='#f0f0f0') ax.add_feature(cfeature.LAND, facecolor='none', linewidth=0, color='#bdbdbd') ax.add_feature(cfeature.LAKES, linewidth=0, color='#f0f0f0') ax.outline_patch.set_linewidth(0.5) ax.outline_patch.set_edgecolor('gray') for nf in range(6):
# take random countries num_nodes = 20 world = ng.maps["adaptive"] units = nngt._rng.choice(50, num_nodes, replace=False) codes = list(world.iloc[units].SU_A3) # make random network g = nngt.generation.erdos_renyi(nodes=num_nodes, avg_deg=3) # add the A3 code for each country (that's the crucial part that will link # the graph to the geospatial data) g.new_node_attribute("code", "string", codes) g.set_weights(nngt._rng.exponential(2, g.edge_nb())) # plot using draw_map and the A3 codes stored in "code" ng.draw_map(g, "code", ncolor="in-degree", esize="weight", threshold=0, ecolor="grey", proj=ccrs.EqualEarth(), max_nsize=20, show=False) if nngt.get_config("with_plot"): plt.tight_layout() plt.show()
def extract_ts(file, shp, var, type='area', lat=34, lon=34): d = xr.open_dataset(file) name = file.split('_')[0] # if name in ['TRMM']: # d = d.transpose('time','latitude', 'longitude') print(name) if type == 'area': nuts = gpd.read_file(shp) num = len(nuts) nuts_mask_poly = regionmask.Regions( name='nuts_mask', numbers=list(range(0, num)), names=list(nuts.ID), abbrevs=list(nuts.ID), outlines=list(nuts.geometry.values[i] for i in range(0, num))) print(nuts_mask_poly) if name not in ['sm2rain', 'GPM', 'TRMM', 'TRMMRT', 'Chirps']: mask = nuts_mask_poly.mask(d.isel(time=0).sel( latitude=slice(43, 35), longitude=slice(25, 45)), lat_name='latitude', lon_name='longitude') else: mask = nuts_mask_poly.mask(d.isel(time=0).sel( latitude=slice(35, 43), longitude=slice(25, 45)), lat_name='latitude', lon_name='longitude') lat = mask.latitude.values lon = mask.longitude.values proj = ccrs.EqualEarth(central_longitude=0) ax = plt.subplot(111, projection=proj) d.isel(time=0).tp.plot.pcolormesh(ax=ax, transform=ccrs.PlateCarree()) ax.coastlines() plt.show() ID_REGION = 1 # print(nuts.NUTS_ID[ID_REGION]) print(nuts.ID[ID_REGION]) sel_mask = mask.where(mask == ID_REGION).values id_lon = lon[np.where(~np.all(np.isnan(sel_mask), axis=0))] id_lat = lat[np.where(~np.all(np.isnan(sel_mask), axis=1))] try: out_sel = d.sel( latitude=slice(id_lat[0], id_lat[-1]), longitude=slice(id_lon[0], id_lon[-1])).compute().where(mask == ID_REGION) daily = out_sel.mean(dim=('latitude', 'longitude'), skipna=True) except: daily = d.mean(dim=('latitude', 'longitude'), skipna=True) daily['tp'] = 0 else: daily = d.sel(longitude=lon, latitude=lat, method='nearest') for key in daily.keys(): daily = daily.rename({key: name + '_' + key}) df = daily.to_dataframe() if name == 'Era5': df['Era5_tp'] = df['Era5_tp'] * 1e3 if name == 'PERSIANN': df = df.drop(['PERSIANN_crs'], axis=1) df.loc[(df.PERSIANN_tp < 0), 'PERSIANN_tp'] = 0 if name in ['sm2rain', 'TRMM', 'TRMMRT']: df.index = df.index.astype(int) df.index = pd.to_datetime(df.index.astype(str)) df.index = df.index.strftime('%m/%d/%Y') return df
def get_map_projection( proj_name, central_longitude=0.0, central_latitude=0.0, false_easting=0.0, false_northing=0.0, globe=None, standard_parallels=(20.0, 50.0), scale_factor=None, min_latitude=-80.0, max_latitude=84.0, true_scale_latitude=None, latitude_true_scale=None, ### BOTH secant_latitudes=None, pole_longitude=0.0, pole_latitude=90.0, central_rotated_longitude=0.0, sweep_axis='y', satellite_height=35785831, cutoff=-30, approx=None, southern_hemisphere=False, zone=15): #### numeric UTM zone proj_name = proj_name.lower() if (proj_name == 'albersequalarea'): proj = ccrs.AlbersEqualArea(central_longitude=central_longitude, central_latitude=central_latitude, false_easting=false_easting, false_northing=false_northing, globe=globe, standard_parallels=standard_parallels) elif (proj_name == 'azimuthalequidistant'): proj = ccrs.AzimuthalEquidistant(central_longitude=central_longitude, central_latitude=central_latitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'equidistantconic'): proj = ccrs.EquidistantConic(central_longitude=central_longitude, central_latitude=central_latitude, false_easting=false_easting, false_northing=false_northing, globe=globe, standard_parallels=standard_parallels) elif (proj_name == 'lambertconformal'): proj = ccrs.LambertConformal( central_longitude=-96.0, ########## central_latitude=39.0, ########## false_easting=false_easting, false_northing=false_northing, globe=globe, secant_latitudes=None, standard_parallels=None, ## default: (33,45) cutoff=cutoff) elif (proj_name == 'lambertcylindrical'): proj = ccrs.LambertCylindrical(central_longitude=central_longitude) elif (proj_name == 'mercator'): proj = ccrs.Mercator(central_longitude=central_longitude, min_latitude=min_latitude, max_latitude=max_latitude, latitude_true_scale=latitude_true_scale, false_easting=false_easting, false_northing=false_northing, globe=globe, scale_factor=None) ######### elif (proj_name == 'miller'): proj = ccrs.Miller(central_longitude=central_longitude, globe=globe) elif (proj_name == 'mollweide'): proj = ccrs.Mollweide(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'orthographic'): proj = ccrs.Orthographic(central_longitude=central_longitude, central_latitude=central_latitude, globe=globe) elif (proj_name == 'robinson'): proj = ccrs.Robinson(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'sinusoidal'): proj = ccrs.Sinusoidal(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'stereographic'): proj = ccrs.Stereographic(central_latitude=central_latitude, central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe, true_scale_latitude=true_scale_latitude, scale_factor=scale_factor) elif (proj_name == 'transversemercator'): proj = ccrs.TransverseMercator( central_longitude=central_longitude, central_latitude=central_latitude, false_easting=false_easting, false_northing=false_northing, globe=globe, scale_factor=1.0, ########## approx=approx) elif (proj_name == 'utm'): proj = ccrs.UTM(zone, southern_hemisphere=southern_hemisphere, globe=globe) elif (proj_name == 'interruptedgoodehomolosine'): proj = ccrs.InterruptedGoodeHomolosine( central_longitude=central_longitude, globe=globe) elif (proj_name == 'rotatedpole'): proj = ccrs.RotatedPole( pole_longitude=pole_longitude, pole_latitude=pole_latitude, globe=globe, central_rotated_longitude=central_rotated_longitude) elif (proj_name == 'osgb'): proj = ccrs.OSGB(approx=approx) elif (proj_name == 'europp'): proj = ccrs.EuroPP elif (proj_name == 'geostationary'): proj = ccrs.Geostationary(central_longitude=central_longitude, satellite_height=satellite_height, false_easting=false_easting, false_northing=false_northing, globe=globe, sweep_axis=sweep_axis) elif (proj_name == 'nearsideperspective'): proj = ccrs.NearsidePerspective(central_longitude=central_longitude, central_latitude=central_latitude, satellite_height=satellite_height, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'eckerti'): proj = ccrs.EckertI(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'eckertii'): proj = ccrs.EckertII(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'eckertiii'): proj = ccrs.EckertIII(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'eckertiv'): proj = ccrs.EckertIV(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'eckertv'): proj = ccrs.EckertV(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'eckertvi'): proj = ccrs.EckertVI(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'equalearth'): proj = ccrs.EqualEarth(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'gnomonic'): proj = ccrs.Gnomonic(central_latitude=central_latitude, central_longitude=central_longitude, globe=globe) elif (proj_name == 'lambertazimuthalequalarea'): proj = ccrs.LambertAzimuthalEqualArea( central_longitude=central_longitude, central_latitude=central_latitude, globe=globe, false_easting=false_easting, false_northing=false_northing) elif (proj_name == 'northpolarstereo'): proj = ccrs.NorthPolarStereo(central_longitude=central_longitude, true_scale_latitude=true_scale_latitude, globe=globe) elif (proj_name == 'osni'): proj = ccrs.OSNI(approx=approx) elif (proj_name == 'southpolarstereo'): proj = ccrs.SouthPolarStereo(central_longitude=central_longitude, true_scale_latitude=true_scale_latitude, globe=globe) else: # This is same as "Geographic coordinates" proj = ccrs.PlateCarree(central_longitude=central_longitude, globe=globe) return proj
fontsize = 14 cbstr = r'2m temperature anomaly [$^{\circ}$C]' projection = 'robinson' if projection == 'platecarree': p = ccrs.PlateCarree(central_longitude=0) threshold = 0 if projection == 'mollweide': p = ccrs.Mollweide(central_longitude=0) threshold = 1e6 if projection == 'robinson': p = ccrs.Robinson(central_longitude=0) threshold = 0 if projection == 'equalearth': p = ccrs.EqualEarth(central_longitude=0) threshold = 0 if projection == 'geostationary': p = ccrs.Geostationary(central_longitude=0) threshold = 0 if projection == 'goodehomolosine': p = ccrs.InterruptedGoodeHomolosine(central_longitude=0) threshold = 0 if projection == 'europp': p = ccrs.EuroPP() threshold = 0 if projection == 'northpolarstereo': p = ccrs.NorthPolarStereo() threshold = 0 if projection == 'southpolarstereo': p = ccrs.SouthPolarStereo()
#use_obs = 'CRUTEM' #use_obs = 'HadCRUT' use_minmax = False use_horizontal_colorbar = False use_mask = False use_gridliner = True cmap = 'coolwarm' fontsize = 14 top_pad = 0.9 projection = 'robinson' if projection == 'platecarree': p = ccrs.PlateCarree(central_longitude=0); threshold = 0 if projection == 'mollweide': p = ccrs.Mollweide(central_longitude=0); threshold = 1e6 if projection == 'robinson': p = ccrs.Robinson(central_longitude=0); threshold = 0 if projection == 'equalearth': p = ccrs.EqualEarth(central_longitude=0); threshold = 0 if projection == 'geostationary': p = ccrs.Geostationary(central_longitude=0); threshold = 0 if projection == 'goodehomolosine': p = ccrs.InterruptedGoodeHomolosine(central_longitude=0); threshold = 0 if projection == 'europp': p = ccrs.EuroPP(); threshold = 0 if projection == 'northpolarstereo': p = ccrs.NorthPolarStereo(); threshold = 0 if projection == 'southpolarstereo': p = ccrs.SouthPolarStereo(); threshold = 0 if projection == 'lambertconformal': p = ccrs.LambertConformal(central_longitude=0); threshold = 0 #---------------------------------------------------------------------------- # DARK BACKGROUND THEME #---------------------------------------------------------------------------- matplotlib.rcParams['text.usetex'] = False rcParams['font.family'] = ['DejaVu Sans'] rcParams['font.sans-serif'] = ['Avant Garde'] plt.rc('text',color='white')
def set_proj(projection='Robinson', proj_default=True): """ Set the projection for Cartopy. Parameters ---------- projection : string the map projection. Available projections: 'Robinson' (default), 'PlateCarree', 'AlbertsEqualArea', 'AzimuthalEquidistant','EquidistantConic','LambertConformal', 'LambertCylindrical','Mercator','Miller','Mollweide','Orthographic', 'Sinusoidal','Stereographic','TransverseMercator','UTM', 'InterruptedGoodeHomolosine','RotatedPole','OSGB','EuroPP', 'Geostationary','NearsidePerspective','EckertI','EckertII', 'EckertIII','EckertIV','EckertV','EckertVI','EqualEarth','Gnomonic', 'LambertAzimuthalEqualArea','NorthPolarStereo','OSNI','SouthPolarStereo' proj_default : bool If True, uses the standard projection attributes from Cartopy. Enter new attributes in a dictionary to change them. Lists of attributes can be found in the Cartopy documentation: https://scitools.org.uk/cartopy/docs/latest/crs/projections.html#eckertiv Returns ------- proj : the Cartopy projection object See Also -------- pyleoclim.utils.mapping.map_all : mapping function making use of the projection """ if proj_default is not True and type(proj_default) is not dict: raise TypeError( 'The default for the projections should either be provided' + ' as a dictionary or set to True') # Set the projection if projection == 'Robinson': if proj_default is True: proj = ccrs.Robinson() else: proj = ccrs.Robinson(**proj_default) elif projection == 'PlateCarree': if proj_default is True: proj = ccrs.PlateCarree() else: proj = ccrs.PlateCarree(**proj_default) elif projection == 'AlbersEqualArea': if proj_default is True: proj = ccrs.AlbersEqualArea() else: proj = ccrs.AlbersEqualArea(**proj_default) elif projection == 'AzimuthalEquidistant': if proj_default is True: proj = ccrs.AzimuthalEquidistant() else: proj = ccrs.AzimuthalEquidistant(**proj_default) elif projection == 'EquidistantConic': if proj_default is True: proj = ccrs.EquidistantConic() else: proj = ccrs.EquidistantConic(**proj_default) elif projection == 'LambertConformal': if proj_default is True: proj = ccrs.LambertConformal() else: proj = ccrs.LambertConformal(**proj_default) elif projection == 'LambertCylindrical': if proj_default is True: proj = ccrs.LambertCylindrical() else: proj = ccrs.LambertCylindrical(**proj_default) elif projection == 'Mercator': if proj_default is True: proj = ccrs.Mercator() else: proj = ccrs.Mercator(**proj_default) elif projection == 'Miller': if proj_default is True: proj = ccrs.Miller() else: proj = ccrs.Miller(**proj_default) elif projection == 'Mollweide': if proj_default is True: proj = ccrs.Mollweide() else: proj = ccrs.Mollweide(**proj_default) elif projection == 'Orthographic': if proj_default is True: proj = ccrs.Orthographic() else: proj = ccrs.Orthographic(**proj_default) elif projection == 'Sinusoidal': if proj_default is True: proj = ccrs.Sinusoidal() else: proj = ccrs.Sinusoidal(**proj_default) elif projection == 'Stereographic': if proj_default is True: proj = ccrs.Stereographic() else: proj = ccrs.Stereographic(**proj_default) elif projection == 'TransverseMercator': if proj_default is True: proj = ccrs.TransverseMercator() else: proj = ccrs.TransverseMercator(**proj_default) elif projection == 'TransverseMercator': if proj_default is True: proj = ccrs.TransverseMercator() else: proj = ccrs.TransverseMercator(**proj_default) elif projection == 'UTM': if proj_default is True: proj = ccrs.UTM() else: proj = ccrs.UTM(**proj_default) elif projection == 'UTM': if proj_default is True: proj = ccrs.UTM() else: proj = ccrs.UTM(**proj_default) elif projection == 'InterruptedGoodeHomolosine': if proj_default is True: proj = ccrs.InterruptedGoodeHomolosine() else: proj = ccrs.InterruptedGoodeHomolosine(**proj_default) elif projection == 'RotatedPole': if proj_default is True: proj = ccrs.RotatedPole() else: proj = ccrs.RotatedPole(**proj_default) elif projection == 'OSGB': if proj_default is True: proj = ccrs.OSGB() else: proj = ccrs.OSGB(**proj_default) elif projection == 'EuroPP': if proj_default is True: proj = ccrs.EuroPP() else: proj = ccrs.EuroPP(**proj_default) elif projection == 'Geostationary': if proj_default is True: proj = ccrs.Geostationary() else: proj = ccrs.Geostationary(**proj_default) elif projection == 'NearsidePerspective': if proj_default is True: proj = ccrs.NearsidePerspective() else: proj = ccrs.NearsidePerspective(**proj_default) elif projection == 'EckertI': if proj_default is True: proj = ccrs.EckertI() else: proj = ccrs.EckertI(**proj_default) elif projection == 'EckertII': if proj_default is True: proj = ccrs.EckertII() else: proj = ccrs.EckertII(**proj_default) elif projection == 'EckertIII': if proj_default is True: proj = ccrs.EckertIII() else: proj = ccrs.EckertIII(**proj_default) elif projection == 'EckertIV': if proj_default is True: proj = ccrs.EckertIV() else: proj = ccrs.EckertIV(**proj_default) elif projection == 'EckertV': if proj_default is True: proj = ccrs.EckertV() else: proj = ccrs.EckertV(**proj_default) elif projection == 'EckertVI': if proj_default is True: proj = ccrs.EckertVI() else: proj = ccrs.EckertVI(**proj_default) elif projection == 'EqualEarth': if proj_default is True: proj = ccrs.EqualEarth() else: proj = ccrs.EqualEarth(**proj_default) elif projection == 'Gnomonic': if proj_default is True: proj = ccrs.Gnomonic() else: proj = ccrs.Gnomonic(**proj_default) elif projection == 'LambertAzimuthalEqualArea': if proj_default is True: proj = ccrs.LambertAzimuthalEqualArea() else: proj = ccrs.LambertAzimuthalEqualArea(**proj_default) elif projection == 'NorthPolarStereo': if proj_default is True: proj = ccrs.NorthPolarStereo() else: proj = ccrs.NorthPolarStereo(**proj_default) elif projection == 'OSNI': if proj_default is True: proj = ccrs.OSNI() else: proj = ccrs.OSNI(**proj_default) elif projection == 'OSNI': if proj_default is True: proj = ccrs.SouthPolarStereo() else: proj = ccrs.SouthPolarStereo(**proj_default) else: raise ValueError('Invalid projection type') return proj
import cartopy.feature as cfeature import maps if __name__ == '__main__': import matplotlib.pyplot as plt import cartopy.crs as ccrs plt.figure() ax = plt.axes(projection=ccrs.EqualEarth()) ax.set_extent([-110, -85, 25, 50]) # maps.shaded_hills( # ax, # '/home/liam/Downloads/SR_LR/SR_LR.tif', # ) maps.tiger_roads( ax, '/home/liam/Downloads/tl_2016_us_primaryroads.shp', ) maps.outlines(ax, states=True) maps.format_page(ax) plt.show()
def components(n, region_data=None, line_data=None, index=None, plot_colorbar=False, figsize=(20, 6), cmap='RdBu_r', subplots=(1, 3), bounds=[-10., 45, 36, 72], line_widths={ 'Line': 1, 'Link': 1 }, line_colors={ 'Line': 'darkgreen', 'Link': 'darkgreen' }, plot_regions=None, regionsline_width=0.005, title_prefix='', ev_str='\lambda', starting_component=1, busscale=0.1, colorbar_kw={}, flow_quantile=0.): """ This plots the principal components of the network. """ if isinstance(region_data, str): region_data = getattr(n.pca, region_data) if isinstance(line_data, str): line_data = getattr(n.pca, line_data) if plot_regions is None: if 'regions' in n.__dir__(): regions = n.regions plot_regions = True else: plot_regions = False if index is None: index = region_data.abbr if region_data is not None else line_data.abbr crs = ccrs.EqualEarth() fig, axes = plt.subplots(*subplots, figsize=figsize, squeeze=0, subplot_kw={"projection": crs}) for i in range(axes.size): ax = axes.flatten()[i] region_comp = get_comp(region_data, i + starting_component) region_comp = pd.Series(region_comp, index=n.buses.index).fillna(0) if line_data is None: line_comp = None else: line_comp = get_comp(line_data, i + starting_component) line_comp = (line_comp.div(line_comp.abs().max()).where( lambda ds: ds.abs() > ds.abs().quantile(flow_quantile), 0)) if plot_regions: region_comp /= region_comp.abs().max() regions.loc[:, 'weight'] = region_comp regions.plot(cmap=cmap, column='weight', ax=ax, vmin=-1., vmax=1., linewidth=regionsline_width * figsize[0], edgecolor='k', transform=ccrs.PlateCarree()) region_comp[:] = 0 n.plot(ax=ax, bus_sizes=region_comp.abs() * busscale, flow=line_comp, line_widths=line_widths, line_colors=line_colors, bus_colors=np.sign(region_comp), bus_cmap=cmap, boundaries=bounds, geomap=True) val = region_data.val if region_data is not None else line_data.val ax.set_title(fr'{title_prefix}${ev_str}_{i+starting_component}' fr' = {round(val.loc[i+starting_component], 2)}$') ax.set_facecolor('white') fig.canvas.draw() fig.tight_layout(w_pad=7.) fig.colorbar(plt.cm.ScalarMappable(Normalize(-1, 1), cmap=cmap), ax=axes, **colorbar_kw) return fig, axes
def plot_orbit_var(lat, lon, var, vmin, vmax, projection, filestr, titlestr, varstr): x = lon[::10, ::10] y = lat[::10, ::10] z = var[::10, ::10] fig = plt.figure() if projection == 'platecarree': p = ccrs.PlateCarree(central_longitude=0) threshold = 0 if projection == 'mollweide': p = ccrs.Mollweide(central_longitude=0) threshold = 1e6 if projection == 'robinson': p = ccrs.Robinson(central_longitude=0) threshold = 0 if projection == 'equalearth': p = ccrs.EqualEarth(central_longitude=0) threshold = 0 if projection == 'geostationary': p = ccrs.Geostationary(central_longitude=0) threshold = 0 if projection == 'goodehomolosine': p = ccrs.InterruptedGoodeHomolosine(central_longitude=0) threshold = 0 if projection == 'europp': p = ccrs.EuroPP() threshold = 0 if projection == 'northpolarstereo': p = ccrs.NorthPolarStereo() threshold = 0 if projection == 'southpolarstereo': p = ccrs.SouthPolarStereo() threshold = 0 if projection == 'lambertconformal': p = ccrs.LambertConformal(central_longitude=0) threshold = 0 ax = plt.axes(projection=p) ax.stock_img() ax.coastlines(resolution='50m') ax.gridlines() colormap = 'gnuplot2' g = ccrs.Geodetic() trans = ax.projection.transform_points(g, x, y) x0 = trans[:, :, 0] x1 = trans[:, :, 1] if projection == 'platecarree': ax.set_extent([-180, 180, -90, 90], crs=p) gl = ax.gridlines(crs=p, draw_labels=True, linewidth=1, color='gray', alpha=0.5, linestyle='-') gl.xlabels_top = False gl.ylabels_right = False gl.xlines = True gl.ylines = True gl.xlocator = mticker.FixedLocator([-180, -120, -60, 0, 60, 120, 180]) gl.ylocator = mticker.FixedLocator([-90, -60, -30, 0, 30, 60, 90]) gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER for mask in (x0 >= threshold, x0 <= threshold): im = ax.pcolor(ma.masked_where(mask, x), ma.masked_where(mask, y), ma.masked_where(mask, z), vmin=vmin, vmax=vmax, transform=ax.projection, cmap=colormap) else: for mask in (x0 >= threshold, x0 <= threshold): im = ax.pcolor(ma.masked_where(mask, x0), ma.masked_where(mask, x1), ma.masked_where(mask, z), vmin=vmin, vmax=vmax, transform=ax.projection, cmap=colormap) im.set_clim(vmin, vmax) cb = plt.colorbar(im, orientation="horizontal", extend='both', label=varstr) plt.title(titlestr) plt.savefig(filestr) plt.close('all') return
import matplotlib.pyplot as plt import cartopy.crs as ccrs eq_earth = ccrs.EqualEarth() fig = plt.figure(figsize=(10, 5)) ax = plt.axes(projection=eq_earth) ax.set_global() ax.gridlines() ax.stock_img() ax.coastlines() plt.show()