def plot_point_metric(dem, da_metric, variable_name, variable_units, cmap_in, ctype): fig = plt.figure(figsize=(20, 12)) ax1 = plt.axes(projection=ccrs.AlbersEqualArea()) ax1.imshow( np.flipud(dem.values), extent=[np.min(dem.x), np.max(dem.x), np.min(dem.y), np.max(dem.y)], aspect=ax1.get_aspect()) # Add metric values at points p1 = ax1.scatter(da_metric.Lon, da_metric.Lat, transform=ccrs.AlbersEqualArea(), s=100, c=da_metric, zorder=100, cmap=cmap_in) # yc, xc -- lists or numpy arrays # Add a colorbar c1 = fig.colorbar(p1) c1.ax.set_ylabel(variable_name + ' ' + ctype + ' (' + variable_units + ')') plt.title(variable_name) return fig
def test_central_longitude(self, lon): aea = ccrs.AlbersEqualArea() aea_offset = ccrs.AlbersEqualArea(central_longitude=lon) other_args = {'ellps=WGS84', 'lon_0={}'.format(lon), 'lat_0=0.0', 'x_0=0.0', 'y_0=0.0', 'lat_1=20.0', 'lat_2=50.0'} check_proj_params('aea', aea_offset, other_args) assert_array_almost_equal(aea_offset.boundary, aea.boundary, decimal=0)
def test_standard_parallels(self): aea = ccrs.AlbersEqualArea(standard_parallels=(13, 37)) expected = ('+ellps=WGS84 +proj=aea +lon_0=0.0 +lat_0=0.0 ' '+x_0=0.0 +y_0=0.0 +lat_1=13 +lat_2=37 +no_defs') assert_equal(aea.proj4_init, expected) aea = ccrs.AlbersEqualArea(standard_parallels=(13, )) expected = ('+ellps=WGS84 +proj=aea +lon_0=0.0 +lat_0=0.0 ' '+x_0=0.0 +y_0=0.0 +lat_1=13 +no_defs') assert_equal(aea.proj4_init, expected) aea = ccrs.AlbersEqualArea(standard_parallels=13) expected = ('+ellps=WGS84 +proj=aea +lon_0=0.0 +lat_0=0.0 ' '+x_0=0.0 +y_0=0.0 +lat_1=13 +no_defs') assert_equal(aea.proj4_init, expected)
def test_standard_parallels(self): aea = ccrs.AlbersEqualArea(standard_parallels=(13, 37)) other_args = {'ellps=WGS84', 'lon_0=0.0', 'lat_0=0.0', 'x_0=0.0', 'y_0=0.0', 'lat_1=13', 'lat_2=37'} check_proj_params('aea', aea, other_args) aea = ccrs.AlbersEqualArea(standard_parallels=(13, )) other_args = {'ellps=WGS84', 'lon_0=0.0', 'lat_0=0.0', 'x_0=0.0', 'y_0=0.0', 'lat_1=13'} check_proj_params('aea', aea, other_args) aea = ccrs.AlbersEqualArea(standard_parallels=13) other_args = {'ellps=WGS84', 'lon_0=0.0', 'lat_0=0.0', 'x_0=0.0', 'y_0=0.0', 'lat_1=13'} check_proj_params('aea', aea, other_args)
def global_map( shapefiles=[ "Data/Shapefiles/UpperIndus_HP_shapefile/UpperIndus_HP.shp" ]): """ Returns global map with study area(s) superimposed. """ # Shapefiles plt.figure() ax = plt.subplot(projection=ccrs.PlateCarree(central_longitude=70)) ax.coastlines("50m", linewidth=0.5) for s in shapefiles: path = s basin_shape = shapereader.Reader(path) for rec in basin_shape.records(): ax.add_geometries( [rec.geometry], ccrs.AlbersEqualArea(central_longitude=125, central_latitude=-15, standard_parallels=(7, -32)), edgecolor="red", facecolor="red", alpha=0.1, ) plt.show()
def test_sphere_transform(self): # USGS Professional Paper 1395, pg 291 globe = ccrs.Globe(semimajor_axis=1.0, semiminor_axis=1.0, ellipse=None) lat_1 = 29 + 30 / 60 lat_2 = 45 + 30 / 60 aea = ccrs.AlbersEqualArea(central_latitude=23.0, central_longitude=-96.0, standard_parallels=(lat_1, lat_2), globe=globe) geodetic = aea.as_geodetic() other_args = {'a=1.0', 'b=1.0', 'lon_0=-96.0', 'lat_0=23.0', 'x_0=0.0', 'y_0=0.0', 'lat_1=29.5', 'lat_2=45.5'} check_proj_params('aea', aea, other_args) assert_almost_equal(np.array(aea.x_limits), [-2.6525072042232, 2.6525072042232], decimal=3) assert_almost_equal(np.array(aea.y_limits), [-1.09628087472359, 2.39834724057551], decimal=10) result = aea.transform_point(-75.0, 35.0, geodetic) assert_almost_equal(result, [0.2952720, 0.2416774])
def get_projection_object(type="Lambert"): # Cartopy has a "globe" object to define more projection standards, we create this first globe = ccrs.Globe(ellipse=None, semimajor_axis=6370000, semiminor_axis=6370000, nadgrids="@null") # Now we can create the projection object cen_lat = float(50.0) cen_lon = float(-107.0) std_pll = [50.0] cutoff = -30.0 if type == "Lambert": projObj = ccrs.LambertConformal(central_latitude=cen_lat, central_longitude=cen_lon, standard_parallels=std_pll, globe=globe, cutoff=cutoff) elif type == "EqualArea": projObj = ccrs.AlbersEqualArea(central_latitude=cen_lat, central_longitude=cen_lon, standard_parallels=std_pll, globe=globe) else: print("get_projection_object(): Invalid type " + type + " sent to function") return None return projObj
def test_eastings(self): aea_offset = ccrs.AlbersEqualArea(false_easting=1234, false_northing=-4321) expected = ('+ellps=WGS84 +proj=aea +lon_0=0.0 +lat_0=0.0 ' '+x_0=1234 +y_0=-4321 +lat_1=20.0 +lat_2=50.0 +no_defs') assert_equal(aea_offset.proj4_init, expected)
def test_ellipsoid_transform(self): # USGS Professional Paper 1395, pp 292 -- 293 globe = ccrs.Globe(semimajor_axis=6378206.4, flattening=1 - np.sqrt(1 - 0.00676866), ellipse=None) lat_1 = 29 + 30 / 60 lat_2 = 45 + 30 / 60 aea = ccrs.AlbersEqualArea(central_latitude=23.0, central_longitude=-96.0, standard_parallels=(lat_1, lat_2), globe=globe) geodetic = aea.as_geodetic() other_args = {'a=6378206.4', 'f=0.003390076308689371', 'lon_0=-96.0', 'lat_0=23.0', 'x_0=0.0', 'y_0=0.0', 'lat_1=29.5', 'lat_2=45.5'} check_proj_params('aea', aea, other_args) assert_almost_equal(np.array(aea.x_limits), [-16900972.674607, 16900972.674607], decimal=-3) assert_almost_equal(np.array(aea.y_limits), [-6971893.11311231, 15298166.8919989], decimal=1) result = aea.transform_point(-75.0, 35.0, geodetic) assert_almost_equal(result, [1885472.7, 1535925.0], decimal=1)
def projection(self): # return ccrs.PlateCarree() # return ccrs.EckertI() # return ccrs.EquidistantConic() # return ccrs.LambertConformal(central_longitude=0)#,central_latitude=0) # return ccrs.LambertConformal(central_longitude=0)#,central_latitude=0) return ccrs.AlbersEqualArea()
def test_eastings(self): aea_offset = ccrs.AlbersEqualArea(false_easting=1234, false_northing=-4321) other_args = {'ellps=WGS84', 'lon_0=0.0', 'lat_0=0.0', 'x_0=1234', 'y_0=-4321', 'lat_1=20.0', 'lat_2=50.0'} check_proj_params('aea', aea_offset, other_args)
def base_map(projection='local', center_lat=0, center_lon=0, extent=None, **kwargs): """ Function to plot a basic map which can be used to add data later. :param projection: Cartopy projection string :param center_lat: Latitude to center map :param center_lon: Longitude to center map :param extent: List of coordinates for map boundaries """ plt.figure() if projection == 'global': ax = plt.axes(projection=ccrs.Mollweide(central_longitude=center_lon)) elif projection == 'local': ax = plt.axes(projection=ccrs.AlbersEqualArea( central_latitude=center_lat, central_longitude=center_lon)) if extent: ax.set_extent(extent) elif projection == 'AzimuthalEquidistant': ax = plt.axes(projection=ccrs.AzimuthalEquidistant( central_longitude=center_lon, central_latitude=center_lat)) else: print('Projection not supported') ax.coastlines() ax.add_feature(cfeature.LAND) ax.add_feature(cfeature.BORDERS, linestyle='-') return ax
def test_sphere_transform(self): # USGS Professional Paper 1395, pg 291 globe = ccrs.Globe(semimajor_axis=1.0, semiminor_axis=1.0, ellipse=None) lat_1 = 29 + 30 / 60 lat_2 = 45 + 30 / 60 aea = ccrs.AlbersEqualArea(central_latitude=23.0, central_longitude=-96.0, standard_parallels=(lat_1, lat_2), globe=globe) geodetic = aea.as_geodetic() expected = ('+a=1.0 +b=1.0 +proj=aea +lon_0=-96.0 +lat_0=23.0 ' '+x_0=0.0 +y_0=0.0 +lat_1=29.5 +lat_2=45.5 +no_defs') assert_equal(aea.proj4_init, expected) assert_almost_equal(np.array(aea.x_limits), [-2.6525072042232, 2.6525072042232], decimal=3) assert_almost_equal(np.array(aea.y_limits), [-1.09628087472359, 2.39834724057551], decimal=10) result = aea.transform_point(-75.0, 35.0, geodetic) assert_almost_equal(result, [0.2952720, 0.2416774])
def as_cartopy_crs(self): globe = self._ellipsoid_to_globe(self.ellipsoid, ccrs.Globe()) return ccrs.AlbersEqualArea( central_longitude=self.longitude_of_central_meridian, central_latitude=self.latitude_of_projection_origin, false_easting=self.false_easting, false_northing=self.false_northing, standard_parallels=self.standard_parallels, globe=globe)
def __init__(self, figsize=(10, 6)): self.projection = c_crs.AlbersEqualArea(np.mean(LONG_RANGE), np.mean(LAT_RANGE)) plt.figure(figsize=figsize) self.ax = plt.axes(projection=self.projection) self.ax.set_extent(LONG_RANGE + LAT_RANGE) self.ax.add_feature(cartopy.feature.OCEAN) self.ax.add_feature(cartopy.feature.LAND, edgecolor='black') self.ax.add_feature(cartopy.feature.LAKES, edgecolor='black')
def find_tile(f, lat, lon, radius=3, trim=4): """ Return dataframe with information about gridpoints in resource f that are neighboring (lat, lon). At first, there will be (radius*2) ^ 2 entries/neighbors. The dataframe will be sorted by the distance (in meters) from (lat, lon); the first row -- nearest neighbor. Finally, the function will return N=trim first/nearest rows. """ # Appropriate for lat/lon pairs crs_from = ccrs.PlateCarree() # This projection uses USA_Contiguous_Albers_Equal_Area_Conic_USGS_version: # typical projection for historical USGS maps of the lower 48 # Reference: https://spatialreference.org/ref/sr-org/usa_contiguous_/ # albers_equal_area_conic_usgs_version-2/ crs_to = ccrs.AlbersEqualArea(central_longitude=-96.0, central_latitude=23.0, false_easting=0.0, false_northing=0.0, standard_parallels=(29.5, 45.5), globe=None) point_idx = indicesForCoord(f, lat, lon) point_xy = coordXform(crs_from, crs_to, np.array([lon]), np.array([lat]))[0] # # TODO: Edge cases (around boundaries) need to be handled differently neighbors_to_check = [] for x_idx in range(point_idx[0] - radius, point_idx[0] + radius + 1): for y_idx in range(point_idx[1] - radius, point_idx[1] + radius + 1): neighbors_to_check.append([x_idx, y_idx]) # Get lat/lon pairs for all neighbors (faster than one-at-a-time) neighbors_latlon = [list(p) for p in f["coordinates"][neighbors_to_check]] # Convert all neighbors' lat/lon pairs to x/y neighbors_xy = coordXform(crs_from, crs_to, np.array(neighbors_latlon).reshape(-1, 2)[:, 1], np.array(neighbors_latlon).reshape(-1, 2)[:, 0]) res = pd.DataFrame(columns=[ "x_idx", "y_idx", "lat", "lon", "x_centered", "y_centered", "d" ]) for idx, latlon, xy in zip(neighbors_to_check, neighbors_latlon, neighbors_xy): # Distance in meters calculated after applying projections dx = xy[0] - point_xy[0] dy = xy[1] - point_xy[1] d = np.sqrt(dx**2 + dy**2) res.loc[len(res)] = [idx[0], idx[1], latlon[0], latlon[1], dx, dy, d] res["x_idx"] = pd.to_numeric(res["x_idx"], downcast='integer') res["y_idx"] = pd.to_numeric(res["y_idx"], downcast='integer') return res.sort_values("d")[:trim].reset_index(drop=True)
def test_albers(self): """See if we can plot albers""" m = plot.MapPlot(sector='custom', north=43, east=-80, west=-96, south=38, projection=ccrs.AlbersEqualArea(), continentalcolor='white') m.postprocess(filename='/tmp/test_plot_albers.png') m.close()
def get_boundary_polygon(polygons): """Tries to create a tight boundary around given polygons Parameters: polygons (list of shapely.geometry.polygon.Polygon): input polygons for generating the boundary buffer (int): buffer in meter to be considered around the alphashape Returns: boundary (shapely.geometry.polygon.Polygon): boundary around given polygons """ gpd_polygons = gpd.GeoSeries(polygons, crs='epsg:4326') gpd_proj = gpd_polygons.to_crs(ccrs.AlbersEqualArea().proj4_init) proj_polygons = list(gpd_proj.geometry) proj_points = np.zeros((0, 2)) for proj_polygon in proj_polygons: proj_points = np.vstack((proj_points, np.array(proj_polygon.exterior))) alpha_shape_proj = alphashape.alphashape(proj_points) alpha_polygons = gpd.GeoSeries(alpha_shape_proj, crs=ccrs.AlbersEqualArea().proj4_init) alpha_shape = alpha_polygons.to_crs(crs='epsg:4326')[0] return alpha_shape
def make_aea(attrs_dict, globe): """Handle Albers Equal Area.""" attr_mapping = [('central_longitude', 'longitude_of_central_meridian'), ('standard_parallels', 'standard_parallel')] kwargs = CFProjection.build_projection_kwargs(attrs_dict, attr_mapping) if 'standard_parallels' in kwargs: try: len(kwargs['standard_parallels']) except TypeError: kwargs['standard_parallels'] = [kwargs['standard_parallels']] return ccrs.AlbersEqualArea(globe=globe, **kwargs)
def get_eu_map(figsize=(10, 6)): projection = c_crs.AlbersEqualArea(np.mean(LONG_RANGE), np.mean(LAT_RANGE)) plt.figure(figsize=figsize) ax = plt.axes(projection=projection) ax.set_extent(LONG_RANGE + LAT_RANGE) ax.add_feature(cartopy.feature.OCEAN) ax.add_feature(cartopy.feature.LAND, edgecolor='black') ax.add_feature(cartopy.feature.LAKES, edgecolor='black') return ax, projection
def test_draw_scale(): fig = plt.figure(figsize=(4, 4)) proj = ccrs.AlbersEqualArea(central_latitude=30, central_longitude=-82.5, standard_parallels=(30.0)) ax = fig.add_axes( [0, 0, 1, 1], projection=proj, ) ax.coastlines() ax.set_extent([-90, -75, 25, 35]) draw_scale(ax, pos='ll', units='m')
def test_default(self): aea = ccrs.AlbersEqualArea() expected = ('+ellps=WGS84 +proj=aea +lon_0=0.0 +lat_0=0.0 ' '+x_0=0.0 +y_0=0.0 +lat_1=20.0 +lat_2=50.0 +no_defs') assert_equal(aea.proj4_init, expected) assert_almost_equal(np.array(aea.x_limits), [-17702759.799178038, 17702759.799178038], decimal=0) assert_almost_equal(np.array(aea.y_limits), [-4782937.05107294, 15922623.93176938], decimal=4)
def test_projection_creation(self): res = self.aea_cs.as_cartopy_projection() globe = ccrs.Globe(semimajor_axis=self.semi_major_axis, semiminor_axis=self.semi_minor_axis, ellipse=None) expected = ccrs.AlbersEqualArea(self.latitude_of_projection_origin, self.longitude_of_central_meridian, self.false_easting, self.false_northing, self.standard_parallels, globe=globe) self.assertEqual(res, expected)
def test_default(self): aea = ccrs.AlbersEqualArea() other_args = {'ellps=WGS84', 'lon_0=0.0', 'lat_0=0.0', 'x_0=0.0', 'y_0=0.0', 'lat_1=20.0', 'lat_2=50.0'} check_proj_params('aea', aea, other_args) assert_almost_equal(np.array(aea.x_limits), [-17702759.799178038, 17702759.799178038], decimal=0) assert_almost_equal(np.array(aea.y_limits), [-4782937.05107294, 15922623.93176938], decimal=4)
def plot_site(bbox, figsize=(10, 10), tracks=None, coast_resolution="50m"): """ """ if tracks is None: tracks = swot_tracks central_lon = (bbox[0] + bbox[1]) * 0.5 central_lat = (bbox[2] + bbox[3]) * 0.5 polygon = Polygon( [ (bbox[0], bbox[2]), (bbox[1], bbox[2]), (bbox[1], bbox[3]), (bbox[0], bbox[3]), (bbox[0], bbox[2]), ] ) # poly_gdf = gpd.GeoDataFrame([1], geometry=[polygon], crs=world.crs) gdf = tracks["swath"] gdf_clipped = gpd.clip(gdf, polygon) # crs = ccrs.Orthographic(central_lon, central_lat) crs = ccrs.AlbersEqualArea(central_lon, central_lat) crs_proj4 = crs.proj4_init fig, ax = plt.subplots( 1, 1, subplot_kw={"projection": crs}, figsize=figsize, ) ax.set_extent(bbox) # _gdf = gdf.cx[bbox[0]:bbox[1], bbox[2]:bbox[3]] _gdf = gdf_clipped gdf_crs = _gdf.to_crs(crs_proj4) ax.add_geometries( gdf_crs["geometry"], crs=crs, facecolor="grey", edgecolor="black", alpha=0.5, ) ax.gridlines(draw_labels=True) ax.coastlines(resolution=coast_resolution) return fig, ax
def test_eccentric_globe(self): globe = ccrs.Globe(semimajor_axis=1000, semiminor_axis=500, ellipse=None) aea = ccrs.AlbersEqualArea(globe=globe) expected = ('+a=1000 +b=500 +proj=aea +lon_0=0.0 +lat_0=0.0 ' '+x_0=0.0 +y_0=0.0 +lat_1=20.0 +lat_2=50.0 +no_defs') assert_equal(aea.proj4_init, expected) assert_almost_equal(np.array(aea.x_limits), [-2323.47073363411, 2323.47073363411], decimal=-2) assert_almost_equal(np.array(aea.y_limits), [-572.556243423972, 2402.36176984391], decimal=10)
def test_eccentric_globe(self): globe = ccrs.Globe(semimajor_axis=1000, semiminor_axis=500, ellipse=None) aea = ccrs.AlbersEqualArea(globe=globe) other_args = {'a=1000', 'b=500', 'lon_0=0.0', 'lat_0=0.0', 'x_0=0.0', 'y_0=0.0', 'lat_1=20.0', 'lat_2=50.0'} check_proj_params('aea', aea, other_args) assert_almost_equal(np.array(aea.x_limits), [-2323.47073363411, 2323.47073363411], decimal=-2) assert_almost_equal(np.array(aea.y_limits), [-572.556243423972, 2402.36176984391], decimal=10)
def visualize_map(ticks): """Visualize the crag locations on a world map Args: ticks (DataFrame): Preprocessed ticklist data Returns: Figure: The produced matplotlib figure """ import cartopy.crs as ccrs import cartopy.feature as cfeature # plot the world map map_crs = ccrs.AlbersEqualArea() fig, ax = plt.subplots(1, 1, figsize=(10, 3), subplot_kw={'projection': map_crs}) ax.add_feature(cfeature.LAND, facecolor='C0') ax.add_feature(cfeature.BORDERS, edgecolor='white', alpha=0.4) ax.spines['geo'].set_visible(False) ax.gridlines() # plot ascents as a scatterplot where more ascents at the same crag # produces a bigger blob db = ticks.pivot_table(index=['lat', 'lon'], values='route', aggfunc='count').reset_index() sns.scatterplot(data=db, x='lon', y='lat', alpha=0.5, color='C1', size='route', sizes=(20, 200), ax=ax, legend=False, transform=ccrs.PlateCarree()) # set the viewlimits of the map to match the figure aspect ratio top = 0.9 left = 0.03 right = 0.97 bottom = 0.15 size = fig.get_size_inches() width = (right - left)*size[0] height = (top - bottom)*size[1] old_width = ax.viewLim.width new_width = ax.viewLim.height*width/height width_change = new_width - old_width ax.viewLim.x0 = ax.viewLim.x0 - width_change/2. ax.viewLim.x1 = ax.viewLim.x1 + width_change/2. plt.subplots_adjust(top=top, left=left, right=right, bottom=bottom) return fig
def show_proj(latitudes, longitudes, angle, extent, proj, label=''): import numpy as np import matplotlib.pyplot as plt import matplotlib.collections as mplcollections from matplotlib.patches import Circle import cartopy.crs as ccrs from math import degrees as to_deg # Ustawianie kolorów colors = np.linspace(0, 1, num=5) if extent == None: extent = [0, 0, 0, 0] # Ustawianie rzutowania if proj == 'orto': bmap = ccrs.Orthographic( central_longitude=((extent[0] + extent[1]) / 2), central_latitude=((extent[2] + extent[3]) / 2)) if proj == 'albers': bmap = ccrs.AlbersEqualArea(central_longitude=0) if proj == 'sinus': bmap = ccrs.Sinusoidal(central_longitude=((extent[0] + extent[1]) / 2)) if proj == 'merc': bmap = ccrs.Mercator(central_longitude=((extent[0] + extent[1]) / 2)) if proj == 'plate': bmap = ccrs.PlateCarree(central_longitude=((extent[0] + extent[1]) / 2)) ax = plt.axes(projection=bmap) ax.set_global() ax.coastlines() ax.gridlines() if not extent == [0, 0, 0, 0]: ax.set_extent(extent) # Ładowanie kół opisujących maksymalną widoczność patches = [] for i in range(len(latitudes)): patches.append( Circle((latitudes[i], longitudes[i]), radius=to_deg(angle[i]))) collection = mplcollections.PatchCollection(patches, transform=ccrs.PlateCarree()) # Rysowanie collection.set_array(colors) ax.add_collection(collection) ax.set_title(label) plt.savefig('CircleTest.png', dpi=100) plt.show() return ()
def test_pcolormesh(self): """See if we can do pcolormesh OKish""" m = plot.MapPlot(sector='custom', north=43, east=-80, west=-96, south=38, projection=ccrs.AlbersEqualArea(), continentalcolor='white') lons = np.arange(-100, -80, 0.25) lats = np.arange(40, 50, 0.25) vals = np.random.rand(lats.shape[0], lons.shape[0]) lons, lats = np.meshgrid(lons, lats) m.pcolormesh(lons, lats, vals, np.arange(0, 1, 0.1)) m.postprocess(filename='/tmp/test_plot_pcolormesh.png') m.close()