def test_imshow_rgb(): # tests that the alpha of a RGB array passed to imshow is set to 0 # instead of masked z = np.ones((100, 100, 3)) * 0.5 plt_crs = ccrs.LambertAzimuthalEqualArea() latlon_crs = ccrs.PlateCarree() ax = plt.axes(projection=plt_crs) ax.set_extent([-30, -20, 60, 70], crs=latlon_crs) img = ax.imshow(z, extent=[-26, -24, 64, 66], transform=latlon_crs) assert sum(img.get_array().data[:, 0, 3]) == 0
def as_cartopy_crs(self): globe = self._ellipsoid_to_globe(self.ellipsoid, ccrs.Globe()) return ccrs.LambertAzimuthalEqualArea( central_longitude=self.longitude_of_projection_origin, central_latitude=self.latitude_of_projection_origin, false_easting=self.false_easting, false_northing=self.false_northing, globe=globe, )
def as_cartopy_crs(self): if self.ellipsoid is not None: globe = self.ellipsoid.as_cartopy_globe() else: globe = ccrs.Globe() return ccrs.LambertAzimuthalEqualArea( central_longitude=self.longitude_of_projection_origin, central_latitude=self.latitude_of_projection_origin, false_easting=self.false_easting, false_northing=self.false_northing, globe=globe)
def test_default(self): crs = ccrs.LambertAzimuthalEqualArea() other_args = {'ellps=WGS84', 'lon_0=0.0', 'lat_0=0.0', 'x_0=0.0', 'y_0=0.0'} check_proj4_params(crs, other_args) assert_almost_equal(np.array(crs.x_limits), [-12755636.1863, 12755636.1863], decimal=4) assert_almost_equal(np.array(crs.y_limits), [-12727770.598700099, 12727770.598700099], decimal=4)
def test_projection_creation(self): res = self.laea_cs.as_cartopy_projection() globe = ccrs.Globe(semimajor_axis=self.semi_major_axis, semiminor_axis=self.semi_minor_axis, ellipse=None) expected = ccrs.LambertAzimuthalEqualArea( self.latitude_of_projection_origin, self.longitude_of_projection_origin, self.false_easting, self.false_northing, globe=globe) self.assertEqual(res, expected)
def test_eccentric_globe(self): globe = ccrs.Globe(semimajor_axis=1000, semiminor_axis=500, ellipse=None) crs = ccrs.LambertAzimuthalEqualArea(globe=globe) other_args = {'a=1000', 'b=500', 'lon_0=0.0', 'lat_0=0.0', 'x_0=0.0', 'y_0=0.0'} check_proj4_params(crs, other_args) assert_almost_equal(np.array(crs.x_limits), [-1999.9, 1999.9], decimal=1) assert_almost_equal(np.array(crs.y_limits), [-1380.17298647, 1380.17298647], decimal=4)
def test_default(self): crs = ccrs.LambertAzimuthalEqualArea() expected = ('+ellps=WGS84 +proj=laea +lon_0=0.0 ' '+lat_0=0.0 +x_0=0.0 +y_0=0.0 +no_defs') assert crs.proj4_init == expected assert_almost_equal(np.array(crs.x_limits), [-12755636.1863, 12755636.1863], decimal=4) assert_almost_equal(np.array(crs.y_limits), [-12727770.598700099, 12727770.598700099], decimal=4)
def test_imshow_rgba(): # tests that the alpha of a RGBA array passed to imshow is set to 0 # instead of masked z = np.ones((100, 100)) * 0.5 cmap = cm.get_cmap() norm = colors.Normalize(vmin=0, vmax=1) z1 = cmap(norm(z)) plt_crs = ccrs.LambertAzimuthalEqualArea() latlon_crs = ccrs.PlateCarree() ax = plt.axes(projection=plt_crs) ax.set_extent([-30, -20, 60, 70], crs=latlon_crs) img = ax.imshow(z1, extent=[-26, -24, 64, 66], transform=latlon_crs) assert sum(img.get_array().data[:, 0, 3]) == 0
def test_eccentric_globe(self): globe = ccrs.Globe(semimajor_axis=1000, semiminor_axis=500, ellipse=None) crs = ccrs.LambertAzimuthalEqualArea(globe=globe) expected = ('+a=1000 +b=500 +proj=laea +lon_0=0.0 +lat_0=0.0 ' '+x_0=0.0 +y_0=0.0 +no_defs') assert crs.proj4_init == expected assert_almost_equal(np.array(crs.x_limits), [-1999.9, 1999.9], decimal=1) assert_almost_equal(np.array(crs.y_limits), [-1380.17298647, 1380.17298647], decimal=4)
def __init__(self, lon0, lat0, Size, path_pdsfile=defaut_pdsfile): self.path_pdsfiles = path_pdsfile self.lat0 = lat0 self.lon0 = lon0 self.ppdlola = 512 self.ppdwac = 128 self.globe = ccrs.Globe(semimajor_axis=self.rsphere, semiminor_axis=self.rsphere) self.laea = ccrs.LambertAzimuthalEqualArea(central_longitude=self.lon0, central_latitude=self.lat0, globe=self.globe) assert (self.lon0 > 0.0) and (self.lon0 < 360.0), 'Longitude has to span 0-360 !!!' self.change_window(Size)
def make_ccrs(info): """ Gets cartopy coordinate reference system and image extent for SEVIR events Paramters --------- info pandas.Series object Any row from the SEVIR CATALOG, or metadata returned from SEVIRGenerator Returns ------- ccrs - catropy.crs object containing coordinate ref system img_extent - image_extent used for imshow """ # parse the info.proj string # e.g. +proj=laea +lat_0=38 +lon_0=-98 +units=m +a=6370997.0 +ellps=sphere pjd = {} proj_list = info.proj.split() for p in proj_list: grps = p.strip().split('=') key=grps[0].strip('+') val=str(grps[1]) if len(grps)==2 else '' if _check_num(val): val=float(val) pjd.update({key:val}) # Create appropriate cartopy object based on proj_dict a=pjd.get('a',None) b=pjd.get('b',None) ellps=pjd.get('ellps','WGS84') datum=pjd.get('datum',None) globe=Globe(datum=datum,ellipse=ellps,semimajor_axis=a,semiminor_axis=b) if ('proj' in pjd) and (pjd['proj']=='laea'): ccrs = crs.LambertAzimuthalEqualArea(central_longitude=pjd.get('lon_0',0.0), central_latitude=pjd.get('lat_0',0.0), globe=globe) else: raise NotImplementedError('Projection %s not implemented, please add it' % info.proj) # use ccrs to compute image extent x1,y1=ccrs.transform_point(info.llcrnrlon,info.llcrnrlat,crs.Geodetic()) x2,y2=ccrs.transform_point(info.urcrnrlon,info.urcrnrlat,crs.Geodetic()) img_extent=(x1,x2,y1,y2) return ccrs,img_extent
def plticepos(Xib, Yib, Xis, Yis, path): fig = plt.figure(figsize=(12, 12), frameon=True) ax = plt.axes(projection=ccrs.LambertAzimuthalEqualArea( central_longitude=25.0, central_latitude=77.0)) # ax.set_extent([15,33,74,81]) ax.set_extent([16, 28, 74, 78]) # Define gridline locations and draw the lines using cartopy's built-in gridliner: # *must* call draw in order to get the axis boundary used to add ticks: fig.canvas.draw() xticks = [0, 4, 12, 16, 20, 24, 28, 32, 36] yticks = [72, 74, 76, 78, 80, 82] ax.gridlines(xlocs=xticks, ylocs=yticks) # Label the end-points of the gridlines using the custom tick makers: ax.xaxis.set_major_formatter(LONGITUDE_FORMATTER) ax.yaxis.set_major_formatter(LATITUDE_FORMATTER) lambert_xticks(ax, xticks) lambert_yticks(ax, yticks) # Plotting buoy obs and buoy simulated locations plt.plot(Xib, Yib, color='red', transform=ccrs.PlateCarree(), label='buoy drift') plt.plot(Xis, Yis, '--', color='yellow', transform=ccrs.PlateCarree(), label='simulated ice drift') # gebco wms background service = 'https://www.gebco.net/data_and_products/gebco_web_services/web_map_service/mapserv?' ax.add_wms(service, layers=['GEBCO_LATEST'], wms_kwargs={ 'width': 900 * 2, 'height': 600 * 2 }) feature = cpf.GSHHSFeature(scale='i', levels=[1], facecolor='#e6e1e1', alpha=1) ax.add_feature(feature) plt.legend(prop={"size": 16}, framealpha=1) plt.savefig(path + '/ice_drift.jpg', dpi=400) plt.close(fig)
def plot_xarray_data_array(dataset: xr.Dataset, da: xr.DataArray, file: IO[Any]) -> None: """Create an image plot for a data array""" central_latitude = ( dataset.lambert_azimuthal_equal_area.latitude_of_projection_origin[0]) central_longitude = ( dataset.lambert_azimuthal_equal_area.longitude_of_projection_origin[0]) mogreps_crs = ccrs.LambertAzimuthalEqualArea( central_latitude=central_latitude, central_longitude=central_longitude) plt.figure() ax = plt.axes(projection=ccrs.OSGB(approx=True)) ax.coastlines(resolution="10m") da.plot(ax=ax, add_colorbar=False, transform=mogreps_crs, cmap="viridis") ax.gridlines(draw_labels=True) plt.savefig(file, format="png")
def make_projection(proj_params): """ turn a set of proj4 parameters into a cartopy laea projection introduced in read_resample.ipynb Parameters ---------- proj_params: dict dictionary with parameters lat_0, lon_0 datum and ellps Returns ------- cartopy projection object """ import cartopy.crs as ccrs globe_w = ccrs.Globe(datum=proj_params["datum"],ellipse=proj_params['ellps']) projection_w=ccrs.LambertAzimuthalEqualArea(central_latitude=float(proj_params['lat_0']), central_longitude= float(proj_params['lon_0']),globe=globe_w) return projection_w
) regions = { "atlantic": { "faces": [0, 1, 2, 6, 10, 11, 12], "extent": [-110, 25, -70, 70], "dticks": [10, 10], "projection": ccrs.Mollweide(), }, "south-atlantic": { "faces": [1, 11, 0, 12], "extent": [-50, 20, -60, 5], "dticks": [10, 10], "projection": ccrs.LambertAzimuthalEqualArea(central_longitude=-15.0, central_latitude=-30), }, "global": { "faces": [i for i in range(13) if i != 6], "extent": "global", "dticks": [10, 10], "projection": ccrs.EckertIII(), }, "global_pacific": { "faces": [i for i in range(13) if i != 6], "extent": "global", "dticks": [10, 10], "projection": ccrs.EckertIII(central_longitude=-180), }, "marquises-0": { "faces": [5, 7, 8, 11],
#### clim_min = 1998 clim_max = 2017 year_interest = 2020 #### FLAG TO ASSIGN OUTPUT FIGURE FORMAT FIG_FMT = 'PNG' # or 'PDF' or 'TIF' plt.rcParams['font.weight'] = 'bold' plt.rcParams['font.family'] = 'Arial' plt.rcParams['axes.labelsize'] = 16 plt.rcParams['axes.labelweight'] = 'bold' plt.rcParams['xtick.labelsize'] = 14 plt.rcParams['ytick.labelsize'] = 14 fig_crs = ccrs.LambertAzimuthalEqualArea(central_latitude=90, central_longitude=-80) data_crs = ccrs.Stereographic(true_scale_latitude=60, central_longitude=-80, central_latitude=90, globe=ccrs.Globe(semimajor_axis=6371200, semiminor_axis=6371200)) figsize = (11, 10) dpi = 100 extent = [-6e6, 6e6, -6e6, 6e6] cbar_ticks = [-100, -80, -60, -40, -20, 0, 20, 40, 60, 80, 100] # copied the RGB values from Arc18_Snow_Fig2.png cmap = mpl.colors.LinearSegmentedColormap.from_list( name='fig3', colors=[(x[0] / 255, x[1] / 255, x[2] / 255) for x in [(188, 15,
def plot_pointfield_statistic(ds, map_type, stat_name, sig_alpha=0.05, plotfun=None, **kwargs): """Generic plotting function for field statistic manuscript figures """ assert map_type in ['north_hemisphere', 'global'] assert plotfun in ['contourf', 'pcolormesh'] proj = { 'north_hemisphere': ccrs.LambertAzimuthalEqualArea(central_longitude=-160, central_latitude=90), 'global': ccrs.Robinson(central_longitude=-160) } subplot_kwargs = { 'north_hemisphere': { 'adjust': { 'bottom': 0.1 }, 'add_axes': [0.17, 0.1, 0.7, 0.01], 'colorbar': { 'orientation': 'horizontal' } }, 'global': { 'adjust': { 'bottom': 0.1 }, 'add_axes': [0.17, 0.1, 0.7, 0.01], 'colorbar': { 'orientation': 'horizontal' } } } pc_dim = ds['PC'].values season = ds['season'].values alpha = [0, sig_alpha, 1] theta = np.linspace(0, 2 * np.pi, 100) center, radius = [0.5, 0.5], 0.5 verts = np.vstack([np.sin(theta), np.cos(theta)]).T circle = mplpath.Path(verts * radius + center) plot_meta = [{ 'season': 'JJA-1', 'PC': 'PC1', 'title': 'a) PC1: JJA' }, { 'season': 'SON-1', 'PC': 'PC1', 'title': 'b) PC1: SON' }, { 'season': 'DJF', 'PC': 'PC1', 'title': 'c) PC1: DJF' }, { 'season': 'MAM', 'PC': 'PC1', 'title': 'd) PC1: MAM' }, { 'season': 'JJA-1', 'PC': 'PC2', 'title': 'e) PC2: JJA' }, { 'season': 'SON-1', 'PC': 'PC2', 'title': 'f) PC2: SON' }, { 'season': 'DJF', 'PC': 'PC2', 'title': 'g) PC2: DJF' }, { 'season': 'MAM', 'PC': 'PC2', 'title': 'h) PC2: MAM' }] fig = plt.figure(figsize=(7.48031, 4.52756)) for i in range(len(pc_dim) * len(season)): i_season = plot_meta[i]['season'] i_pc = plot_meta[i]['PC'] i_title = plot_meta[i]['title'] ax = fig.add_subplot(len(pc_dim), len(season), i + 1, projection=proj[map_type]) ax.gridlines(color='#696969', linewidth=0.5) ds_crop = ds.sel(season=i_season, PC=i_pc) if map_type == 'north_hemisphere': ax.coastlines(color='#696969', linewidth=1) ax.set_boundary(circle, transform=ax.transAxes) ds_crop = ds_crop.sel(lat=slice(90, 0)) else: ax.set_extent([100, 300, -90, 90]) ax.add_feature(cartopy.feature.LAND, edgecolor='#696969', facecolor='#696969', zorder=0) stat_crop = ds_crop[stat_name] p_crop = ds_crop['pvalue'] p_cyc, lon_cyc = cartopy.util.add_cyclic_point( p_crop.values, coord=p_crop['lon'].values, axis=-1) stat_cyc, lon_cyc = cartopy.util.add_cyclic_point( stat_crop.values, coord=stat_crop['lon'].values, axis=-1) # For whatever reason, this screws with our NAN masks, so to correct: stat_cyc = np.ma.masked_where(np.isnan(stat_cyc), stat_cyc) ctf1 = None if plotfun == 'pcolormesh': ctf1 = ax.pcolormesh(lon_cyc, stat_crop.lat.values, stat_cyc, cmap=plt.cm.RdBu, transform=ccrs.PlateCarree(), **kwargs) elif plotfun == 'contourf': ctf1 = ax.contourf(lon_cyc, stat_crop.lat.values, stat_cyc, cmap=plt.cm.RdBu, transform=ccrs.PlateCarree(), **kwargs) ctf2 = ax.contourf(lon_cyc, p_crop.lat.values, p_cyc, alpha, colors='none', hatches=['....', None], transform=ccrs.PlateCarree()) ax.set_title(i_title, loc='left') ax.outline_patch.set_edgecolor('none') fig.tight_layout() fig.subplots_adjust(**subplot_kwargs[map_type]['adjust']) cax = fig.add_axes(subplot_kwargs[map_type]['add_axes']) cb = plt.colorbar(ctf1, cax=cax, **subplot_kwargs[map_type]['colorbar']) cb.set_label(stat_name) return fig
'central_longitude': -45.0, 'false_easting': 0.0, 'false_northing': 0.0, 'true_scale_latitude': 70 }, 'bounds': [-3850000.000, 3750000., -5350000., 5850000.000]} src_globe = ccrs.Globe(datum=None, semimajor_axis=6378273., semiminor_axis=6356889.449) src_crs = ccrs.Stereographic(**src_proj['ccrs'], globe=src_globe) #Define output projection and parameters dst_proj = {'pixel_width': 50135.05, 'pixel_height': 50135.05, 'ccrs': {'central_latitude': 90., 'central_longitude': 0., 'false_easting': 0.0, 'false_northing': 0.0}, 'bounds': [-8999241.475, 8999241.475, -8999241.475, 8999241.475]} dst_globe = ccrs.Globe(datum=None, semimajor_axis=6371228, semiminor_axis=6371228) dst_crs = ccrs.LambertAzimuthalEqualArea(**dst_proj['ccrs'], globe=dst_globe) # Get mask mask = read_seaice_mask() # Plot mask ax = plt.subplot(projection=src_crs) ax.set_extent([0., 359., 20., 90.], ccrs.PlateCarree()) ax.imshow(mask, extent=src_proj['bounds'], origin='upper') ax.coastlines() plt.show()
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
t = tf.t.isel(timestep=0).drop('timestep') u = uf.u.isel(timestep=0).drop('timestep') v = vf.v.isel(timestep=0).drop('timestep') u500 = u500f.u.isel(timestep=0).drop('timestep') v500 = v500f.v.isel(timestep=0).drop('timestep') time = vf.timestep # Convert Pa to hPa p = p / 100 # Convert K to F t = (t - 273.15) * 9 / 5 + 32 ############################################################################### # Create plot: fig = plt.figure(figsize=(8, 7)) proj = ccrs.LambertAzimuthalEqualArea(central_longitude=-100, central_latitude=40) # Set axis projection ax = plt.axes([0, 0.2, 0.8, 0.7], projection=proj) # Create inset axes for color bars cax1 = inset_axes(ax, width='5%', height='100%', loc='lower right', bbox_to_anchor=(0.125, 0, 1, 1), bbox_transform=ax.transAxes, borderpad=0) cax2 = inset_axes(ax, width='100%', height='7%',
# radius = 6_371_228 # # vancouver longitude, latitude indegrees # van_lon, van_lat = [-123.1207, 49.2827] # # use a simple sphere as the datum # globe = ccrs.Globe(ellipse=None, semimajor_axis=radius, semiminor_axis=radius) # # set up # projection = ccrs.LambertAzimuthalEqualArea(central_latitude=90, central_longitude=-90, globe=globe) print(f"pro4 program params: {projection.proj4_params}") # %% [markdown] # **Use matplotlib to draw the map and add a coastline** # %% fig, ax = plt.subplots(1, 1, figsize=(10, 10), subplot_kw={"projection": projection}) ax.gridlines(linewidth=2) ax.add_feature(cartopy.feature.GSHHSFeature(scale="coarse", levels=[1, 2, 3])) # %% [markdown]
# In[4]: json_file = a301.data_dir / Path('corners.json') with open(json_file, 'r') as f: map_dict = json.load(f) pprint.pprint(map_dict) # # use the stored data to make a new map # In[5]: globe_w = ccrs.Globe(datum=map_dict['proj4_params']['datum'], ellipse=map_dict['proj4_params']['ellps']) projection_w = ccrs.LambertAzimuthalEqualArea( central_latitude=map_dict['proj4_params']['lat_0'], central_longitude=map_dict['proj4_params']['lon_0'], globe=globe_w) # In[6]: fig, ax = plt.subplots(1, 1, figsize=(10, 10), subplot_kw={'projection': projection_w}) ax.set_extent(map_dict['extent'], projection_w) xy_vals = projection_w.transform_points(cartopy.crs.Geodetic(), lons, lats) xcoords = xy_vals[:, :, 0] ycoords = xy_vals[:, :, 1] ax.plot(xcoords, ycoords, alpha=0.05) ax.gridlines(linewidth=2) ax.add_feature(cartopy.feature.GSHHSFeature(scale='coarse', levels=[1, 2, 3]))
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
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)
def test_extrema(self, latitude): crs = ccrs.LambertAzimuthalEqualArea(central_latitude=latitude) expected = ('+ellps=WGS84 +proj=laea +lon_0=0.0 +lat_0={} ' '+x_0=0.0 +y_0=0.0 +no_defs'.format(latitude)) assert crs.proj4_init == expected
def plot_colocation(f, index): """ Plot colocation scene with given index from file. Args: f(netCDF4.Dataset): NetCDF file handle containing the colocations. index(int): The scene_id value identifying the scene to plot. """ norm = LogNorm(1e-2, 5e1) cmap = "magma" indices = f["scene_id"][:] == index p_opera = f["opera"]["precipitation_5"][indices, :] p_gprof = f["gprof"]["surface_precipitation"][indices, :] lons = f["lon"][indices, :] lats = f["lat"][indices, :] proj_opera = ccrs.LambertAzimuthalEqualArea(central_longitude=10, central_latitude=55, false_easting=1950000, false_northing=-2100000) proj_pc = ccrs.PlateCarree() ll = np.array([-10.434, 31.746]) ur = np.array([57.81, 67.62]) ll_t = proj_opera.transform_point(ll[0], ll[1], proj_pc) ur_t = proj_opera.transform_point(ur[0], ur[1], proj_pc) ################################################################################ # OPERA ################################################################################ plt.figure(figsize=(12, 4), dpi=200) gs = GridSpec(1, 4, width_ratios=[1.0, 1.0, 1.0, 0.05]) ax = plt.subplot(gs[0], projection=proj_opera) ax.set_extent([ll_t[0], ur_t[0], ll_t[1], ur_t[1]], crs=proj_opera) ax.stock_img() ax.coastlines(resolution="10m", linewidth=0.2) ax.set_title("(a) Opera ground radar", loc="left") ax.pcolormesh(lons, lats, p_opera, norm=norm, cmap=cmap, transform=proj_pc) # # Boundary # mask_opera = np.logical_and(p_gprof >= 0, np.isfinite(p_opera)).astype(np.float) mask_opera[0, :] = 0.0 mask_opera[-1, :] = 0.0 ax.contour(lons, lats, mask_opera, levels=[0.0, 1.0], colors="k", linewidths=0.8, transform=proj_pc) ################################################################################ # GPROF ################################################################################ ax = plt.subplot(gs[1], projection=proj_opera) ax.set_extent([ll_t[0], ur_t[0], ll_t[1], ur_t[1]], crs=proj_opera) ax.stock_img() ax.coastlines(resolution="10m", linewidth=0.5) ax.set_title("(b) GPROF GMI", loc="left") img = ax.pcolormesh(lons, lats, p_gprof, norm=norm, cmap=cmap, transform=proj_pc) # # Boundary # i = np.where(p_gprof >= 0)[1][0] ax.plot(lons[:, i], lats[:, i], c="k", transform=proj_pc, lw=0.8) i = np.where(p_gprof >= 0)[1][-1] ax.plot(lons[:, i], lats[:, i], c="k", transform=proj_pc, lw=0.8) ax_gprof = ax ################################################################################ # Combined ################################################################################ ax = plt.subplot(gs[2], projection=proj_opera) ax.set_extent([ll_t[0], ur_t[0], ll_t[1], ur_t[1]], crs=proj_opera) ax.stock_img() ax.coastlines(resolution="10m", linewidth=0.5) ax.set_title("(c) GPM Combined", loc="left") g = f["combined"] indices = g["scene_id"][:] == index if np.any(indices): p_cmb = g["surface_precipitation"][indices, :] p_cmb_s = convolve(p_cmb, gprof_weights, "same") p_cmb_s[p_cmb_s < 1e-2] = np.nan lons = g["lon"][indices, :] lats = g["lat"][indices, :] ax.pcolormesh(lons, lats, p_cmb_s, norm=norm, cmap=cmap, transform=proj_pc) # # Boundary # i = np.where(p_cmb >= 0)[1][0] ax.plot(lons[:, i], lats[:, i], c="k", transform=proj_pc, lw=0.8) ax_gprof.plot(lons[:, i], lats[:, i], c="k", transform=proj_pc, lw=0.8, ls="--") i = np.where(p_cmb >= 0)[1][-1] ax.plot(lons[:, i], lats[:, i], c="k", transform=proj_pc, lw=0.8) ax_gprof.plot(lons[:, i], lats[:, i], c="k", transform=proj_pc, lw=0.8, ls="--") ################################################################################ # Colorbar ################################################################################ ax = plt.subplot(gs[3]) plt.colorbar(img, cax=ax, label=r"Rainfall rate $[mm\ h^{-1}]$") plt.tight_layout()
def plot_2(data1, data2, lat, lon, name): fig_crs = ccrs.LambertAzimuthalEqualArea(central_latitude=90, central_longitude=-80) data_crs = ccrs.PlateCarree() figsize = (15, 6.85) extent = [-6e6, 5e6, -5e6, 5e6] cbar_ticks = [-50, -40, -30, -20, -10, 0, 10, 20, 30, 40, 50] # copied the RGB values from Arc18_Snow_Fig2.png cmap = mpl.colors.LinearSegmentedColormap.from_list( name='fig2', colors=[ (x[0] / 255, x[1] / 255, x[2] / 255) for x in [(255, 47, 34), (255, 113, 57), ( 239, 162, 0), (255, 211, 66), (255, 255, 156), ( 255, 255, 255), (255, 255, 255), (255, 255, 255), (198, 255, 222), (140, 211, 255), (57, 195, 255), (0, 150, 189), (0, 95, 206)] ], N=256) cut_data1 = data1[158:1024 - 158 + 1, 158:1024 - 158 + 1] cut_data2 = data2[158:1024 - 158 + 1, 158:1024 - 158 + 1] cut_lat = lat[158:1024 - 158 + 1, 158:1024 - 158 + 1] cut_lon = lon[158:1024 - 158 + 1, 158:1024 - 158 + 1] #initialize canvas fig, (ax_a, ax_b) = plt.subplots(figsize=figsize, nrows=1, ncols=2, subplot_kw={'projection': fig_crs}) # setting margins plt.subplots_adjust(top=0.999, bottom=0.001, left=0.001, right=0.999, wspace=0, hspace=0) mesh_a = ax_a.pcolormesh(cut_lon, cut_lat, cut_data1, transform=data_crs, cmap=cmap, vmin=-50, vmax=50) mesh_b = ax_b.pcolormesh(cut_lon, cut_lat, cut_data2, transform=data_crs, cmap=cmap, vmin=-50, vmax=50) ax_a.coastlines() ax_b.coastlines() ax_a.add_feature(cfeature.BORDERS, linestyle=':') ax_b.add_feature(cfeature.BORDERS, linestyle=':') gla = ax_a.gridlines(color='gray') gla.xlocator = mticker.FixedLocator([-180, -90, 0, 90, 180]) gla.ylocator = mticker.FixedLocator([60]) glb = ax_b.gridlines(color='gray') glb.xlocator = mticker.FixedLocator([-180, -90, 0, 90, 180]) glb.ylocator = mticker.FixedLocator([60]) # adding colorbars caxa = inset_axes(ax_a, width='5%', height='55%', loc=3, bbox_to_anchor=(0.015, 0.015, 1, 1), bbox_transform=ax_a.transAxes) cb_a = plt.colorbar(mesh_a, cax=caxa, ticks=cbar_ticks, orientation='vertical') ax_a.text(0.015, 0.61, 'days', fontsize=18, transform=ax_a.transAxes) cb_a.ax.tick_params(labelsize=14) caxb = inset_axes(ax_b, width='5%', height='55%', loc=3, bbox_to_anchor=(0.015, 0.015, 1, 1), bbox_transform=ax_b.transAxes) cb_b = plt.colorbar(mesh_b, cax=caxb, ticks=cbar_ticks, orientation='vertical') ax_b.text(0.015, 0.61, 'days', fontsize=18, transform=ax_b.transAxes) cb_b.ax.tick_params(labelsize=14) # axis text indicators ax_a.text(0.02, 0.94, 'a.', fontsize=30, transform=ax_a.transAxes) ax_b.text(0.02, 0.94, 'b.', fontsize=30, transform=ax_b.transAxes) # setting figure extents ax_a.set_extent(extent, crs=fig_crs) ax_a.outline_patch.set_linewidth(1) ax_b.set_extent(extent, crs=fig_crs) ax_b.outline_patch.set_linewidth(1) plt.savefig(name) plt.close()
res[nf, ...], transform=ccrs.PlateCarree(), norm=norm, cmap=cmap) # xy = get_major_xy(xe[nf,...], ye[nf,...]) # ax.plot(xy[...,0], xy[...,1], transform=ccrs.PlateCarree(), color='k') # draw_major_grid_boxes(ax, xe[nf,...], ye[nf,...], transform=ccrs.PlateCarree(), linewidth=1) return pcm # norm = matplotlib.colors.LogNorm(vmin=80, vmax=500) #norm = matplotlib.colors.Normalize(vmin=75, vmax=125) norm = matplotlib.colors.Normalize(vmin=40, vmax=100) cmap = 'RdYlGn_r' projection = ccrs.LambertAzimuthalEqualArea(central_latitude=39, central_longitude=-96) mask_box = [-170, -10, -5, 85] plot_bbox = [-125, -67, 2, 70] fig = plt.figure(figsize=(4.72441, 2.5 * 2 - 0.5)) axes_class = (cartopy.mpl.geoaxes.GeoAxes, dict(map_projection=projection)) # grid = AxesGrid(fig, 111, axes_class=axes_class, # nrows_ncols=(1, 2), # axes_pad=0.05, # cbar_mode='single', # cbar_location='right', # cbar_pad=0.2, # cbar_size='10%', # label_mode=''
import matplotlib.pyplot as plt import cartopy.crs as ccrs plt.figure(figsize=(3.00656806014, 3)) ax = plt.axes(projection=ccrs.LambertAzimuthalEqualArea()) ax.coastlines(resolution='110m') ax.gridlines()
def plot_field_map(model, feature, radius, **kwargs): """ This function plots the synthetic values generated by a given spherical harmonic model within the domain of geomagnetism. It computes the design matrix G, based on the length of the input model, m, and uses it in the forward problem: d = G.m The user has several options for plotting different field features in different plotting views. This function serves well as a first investigation of a given model, but it is not flexible for more advanced visualisation goals. The user is encouraged to visit https://scitools.org.uk/cartopy for learning how to use cartopy for plotting, which is relatively simply. The complexity of the below function is due to the different options given, but a cartopy map projection can actually be carried out in a few lines of code. Args: model (ndarray): model coefficients used for computing d = G.m, where m is the model feature (str): geomagnetic field feature to be plotted, options: 'B_r', 'B_t', 'B_p', 'F', 'D', 'I' or 'H' radius (float): the radius at which the synthetic field values should be generated **kwargs (optional): value_limits (float list): upper and lower value limits e.g. [-1e3, 1e3] mesh_size (float): mesh size for the synthetic grid, below .5 computations are heavy lat_limits (float list): limits on latitude, order does not matter e.g. [90, -90] lon_limits (float list): limits on longitude, order does not matter e.g. [-180, 180] main_projection (object): Cartopy projection object e.g. ccrs.Mollweide() for full list of projections see: https://scitools.org.uk/cartopy plot_poles (boolean): Whether to plot poles or not, default is True polar_limit (float): Bounding latitude for the polar plots default is 60N and 60S contour_labels (float list): list of contour line labels plotted if feature=='D' e.g. [-30, -15, -5, 0, 5, 15, 30] microtesla (boolean): Set to false for plotting in nanoTesla savefig (boolean): save figure True/False colormap (str): Choose from matplotlibs color map options e.g. 'PuOr_r' or 'RdBu' title_string (str): set a customized title string colorbar_string (str): set a customized colorbar string figure_size (float tuple): figure size, (width, height) in inches. title_pos (float): position of the title text, e.g. 1.1 label_pos (int): spacing in points between the colobar label and the x-axis. Returns: None Notes: - Contour lines are only plotted on declination plots - Contour lines are omitted in polar plots. Calling the function with plot_poles=False and projection_type=ccrs.LambertAzimuthalEqualArea(), will produce a polar plot with contours. Examples: # Example1 model = np.loadtxt('coefficients_L2.txt') plot_feature = 'B_r' radius_core = 3480. plot_field_map(model, plot_feature, radius_core) # Example2: plot_feature = 'D' radius_surface = 6371.2 plot_field_map(model, plot_feature, radius_surface, value_limits=[-40, 40], no_poles=True, colormap='RdBu') @author: Eigil Y. H. Lippert, Student DTU Space, <*****@*****.**> """ # set default values value_limits = [-1e3, 1e3] mesh_size = 1 lat_limits = [90, -90] lon_limits = [-180, 180] main_projection = ccrs.Mollweide() plot_poles = True polar_limit = 60 contour_labels = [-30, -15, -5, 0, 5, 15, 30] microtesla = True savefig = False colormap = 'PuOr_r' title_string = None colorbar_string = None figure_size = (12, 12) title_pos = 1. label_pos = 5. # update defaults based on used input for key, value in kwargs.items(): if key == 'value_limits': value_limits = value elif key == 'mesh_size': mesh_size = value elif key == 'lat_limits': lat_limits = value elif key == 'lon_limits': lon_limits = value elif key == 'main_projection': main_projection = value elif key == 'plot_poles': plot_poles = value elif key == 'polar_limit': polar_limit = value elif key == 'contour_labels': contour_labels = value elif key == 'microtesla': microtesla = value elif key == 'savefig': savefig = value elif key == 'colormap': colormap = value elif key == 'title_string': title_string = value elif key == 'colorbar_string': colorbar_string = value elif key == 'figure_size': figure_size = value elif key == 'title_pos': title_pos = value elif key == 'label_pos': label_pos = value # set constants degree = int(-1 + np.sqrt(1 + len(model))) r_surface = 6371.2 rad = np.pi / 180 lat_bound = [np.max(lat_limits), np.min(lat_limits)] lon_bound = [np.min(lon_limits), np.max(lon_limits)] # make range of lat/lon lat = 90 - np.arange(lat_bound[0], lat_bound[1] - mesh_size, -mesh_size) # lat/theta array between 90 and 90 lon = np.arange(lon_bound[0], lon_bound[1] + mesh_size, mesh_size) # remove pole points lat = np.delete(lat, np.where(lat == 0)) lat = np.delete(lat, np.where(lat == 180.)) # compute(lat, lon) - grid lon_grid, lat_grid = np.meshgrid(lon, lat) rows, cols = np.shape(lon_grid) # reshape for design_SHA to work lon_grid = lon_grid.reshape(-1, ) lat_grid = lat_grid.reshape(-1, ) [Gr, Gt, Gp] = design_SHA(radius / r_surface, lat_grid * rad, lon_grid * rad, degree) G = np.vstack((Gr, Gt, Gp)) # compute synthetic field B_synth = G.dot(model) # seperate into components step = int(len(B_synth) / 3) Br_synth = B_synth[0:step] Bt_synth = B_synth[step:step * 2] Bp_synth = B_synth[step * 2::] # reshape back for pcolormesh to work lon_grid = lon_grid.reshape(rows, cols) lat_grid = (90 - lat_grid).reshape(rows, cols) # reshape field components into size of grid as well Br_synth = Br_synth.reshape(rows, cols) Bt_synth = Bt_synth.reshape(rows, cols) Bp_synth = Bp_synth.reshape(rows, cols) # chosen feature: for feature_name in [feature]: if feature_name == 'B_r': feature_name = feature_name + '-component' # compute Br component feat = Br_synth unit = 'B_r, [nT]' if microtesla: feat = feat * 1e-3 unit = 'B_r, [\mu T]' elif feature_name == 'B_t': feature_name = feature_name + '-component' # compute Bt component feat = Bt_synth unit = 'B_t, [nT]' if microtesla: feat = feat * 1e-3 unit = 'B_t, [\mu T]' elif feature_name == 'B_p': feature_name = feature_name + '-component' # compute Bp component feat = Bp_synth unit = 'B_p, [nT]' if microtesla: feat = feat * 1e-3 unit = 'B_p, [\mu T]' elif feature_name == 'F': feature_name = feature_name + ', field intensity' # compute F, intensity feat = np.sqrt(Br_synth ** 2 + Bt_synth ** 2 + Bp_synth ** 2) unit = 'F, [nT]' if microtesla: feat = feat * 1e-3 unit = 'F, [\mu T]' elif feature_name == 'D': feature_name = feature_name + ', declination' X_synth = -Bt_synth Y_synth = Bp_synth # compute D, declination feat = np.arctan2(Y_synth, X_synth) * 180 / np.pi unit = 'D, [degree]' elif feature_name == 'I': feature_name = feature_name + ', inclination' X_synth = -Bt_synth Y_synth = Bp_synth Z_synth = -Br_synth H_synth = np.sqrt(X_synth ** 2 + Y_synth ** 2) # compute I, inclination feat = np.arctan2(Z_synth, H_synth) * 180 / np.pi unit = 'I, [degree]' elif feature_name == 'H': feature_name = feature_name + ', horisontal component' X_synth = -Bt_synth Y_synth = Bp_synth # compute H, horisontal component feat = np.sqrt(X_synth ** 2 + Y_synth ** 2) unit = 'H, [nT]' if microtesla: feat = feat * 1e-3 unit = 'H, [\mu T]' else: print('Feature not known please choose B_r, B_t, B_p, F, D, I or H') # creates a list of projections for a combined main projection polar projection figure projections = [main_projection, ccrs.LambertAzimuthalEqualArea(central_longitude=0., central_latitude=90.), ccrs.LambertAzimuthalEqualArea(central_longitude=0., central_latitude=-90.)] # if no poles, only use one figure position if not plot_poles: subplot_position = [(0, 0)] else: subplot_position = [(0, 0), (2, 0), (2, 2)] colspan = 4 f = plt.figure(figsize=figure_size) gs = GridSpec(4, 4, figure=f) for i, pos in enumerate(subplot_position): # change colspan for polar plots if i > 0: colspan = 2 if not plot_poles: ax = plt.subplot(projection=projections[0]) else: ax = plt.subplot(gs.new_subplotspec(pos, colspan=colspan, rowspan=2), projection=projections[i]) # select polar values of interest for pcolormesh. if (i == 1) or (i == 2): lat_bound = [(90, 60), (-90, -60)] if i == 1: lat_bound = [90, polar_limit] polar_mask = lat_grid >= lat_bound[1] elif i == 2: lat_bound = [-90, -polar_limit] polar_mask = lat_grid <= lat_bound[1] # the masked array is 1-d so reshape with same number of columns as before: lat_grid_polar = np.reshape(lat_grid[polar_mask], (-1, lat_grid.shape[1])) b_r_polar = np.reshape(feat[polar_mask], (-1, lon_grid.shape[1])) lon_grid_polar = lon_grid[0:lat_grid_polar.shape[0], :] h1 = ax.pcolormesh(lon_grid_polar, lat_grid_polar, b_r_polar, cmap=colormap, transform=ccrs.PlateCarree(), vmin=value_limits[0], vmax=value_limits[1]) ax.set_extent([-180, 180, lat_bound[0], lat_bound[1]], ccrs.PlateCarree()) # make circular boundary on projection theta = np.linspace(0, 2 * np.pi, 100) center, radius = [0.5, 0.5], 0.5 verts = np.vstack([np.sin(theta), np.cos(theta)]).T circle = mpath.Path(verts * radius + center) ax.set_boundary(circle, transform=ax.transAxes) else: # If declination draw contour lines if unit == 'D, [degree]': feat_flatten = feat.flatten() lon_grid_flatten = lon_grid.flatten() lat_grid_flatten = lat_grid.flatten() h1 = ax.scatter(x=lon_grid_flatten, y=lat_grid_flatten, s=20, c=feat_flatten, edgecolors='none', transform=ccrs.PlateCarree(), cmap=colormap, vmin=value_limits[0], vmax=value_limits[1]) c1 = ax.contour(lon, 90 - lat, feat, contour_labels, colors='black', linewidths=2.5, linestyles='solid', alpha=0.6, transform=ccrs.PlateCarree()) cl = plt.clabel(c1, fontsize=10, colors='k', inline=1, inline_spacing=8, fmt='%i', rightside_up=True, use_clabeltext=True) else: h1 = ax.pcolormesh(lon_grid, lat_grid, feat, cmap=colormap, transform=ccrs.PlateCarree(), vmin=value_limits[0], vmax=value_limits[1]) ax.coastlines(linewidth=1.1) ax.gridlines() # we need to set axes_class=plt.Axes, else it attempts to create a GeoAxes as colorbar if i == 0: divider = make_axes_locatable(ax) ax_cb = divider.new_vertical(size="5%", pad=0.1, axes_class=plt.Axes, pack_start=True) f.add_axes(ax_cb) # colorbar and properties cbar = plt.colorbar(h1, cax=ax_cb, orientation="horizontal") if colorbar_string is None: colorbar_string = r'${}$'.format(unit) cbar.set_label(colorbar_string, rotation=0, labelpad=label_pos, fontsize='xx-large') cbar.ax.tick_params(labelsize=15) if title_string is None: title_string = 'Field map of {}'.format(feature_name) ax.set_title(title_string, weight='bold', fontsize='xx-large', y=title_pos) if savefig: plt.savefig('Field_map_of_the_{}_component'.format(feature_name) + '.png') plt.show() return