def test_3pt_poly(self): projection = ccrs.OSGB() polygon = sgeom.Polygon([(-1000, -1000), (-1000, 200000), (200000, -1000)]) multi_polygon = projection.project_geometry(polygon, ccrs.OSGB()) self.assertEqual(len(multi_polygon), 1) self.assertEqual(len(multi_polygon[0].exterior.coords), 4)
def plot_boroughs(): boroughs = models.Division.objects.filter(type='borough') ax = plt.axes([0, 0, 1, 0.95], projection=ccrs.OSGB()) ax.set_extent([497000, 572000, 146400, 208000], ccrs.OSGB()) # to get the effect of having just the states without a map "background" # turn off the outline and background patches ax.background_patch.set_visible(False) ax.outline_patch.set_visible(False) plt.title('London boroughs') for b in boroughs: # pick a default color for the land with a black outline, # this will change if the storm intersects with our track facecolor = [0.9375, 0.9375, 0.859375] edgecolor = 'black' polys = [Polygon(x[0]) for x in b.mpoly.coords] geom = MultiPolygon(polys) ax.add_geometries([geom], ccrs.OSGB(), facecolor=facecolor, edgecolor=edgecolor) plt.show()
def main(): imagery = OSM() fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection=imagery.crs) ax.set_extent([-0.14, -0.1, 51.495, 51.515], ccrs.PlateCarree()) # Construct concentric circles and a rectangle, # suitable for a London Underground logo. theta = np.linspace(0, 2 * np.pi, 100) circle_verts = np.vstack([np.sin(theta), np.cos(theta)]).T concentric_circle = Path.make_compound_path(Path(circle_verts[::-1]), Path(circle_verts * 0.6)) rectangle = Path([[-1.1, -0.2], [1, -0.2], [1, 0.3], [-1.1, 0.3]]) # Add the imagery to the map. ax.add_image(imagery, 14) # Plot the locations twice, first with the red concentric circles, # then with the blue rectangle. xs, ys = tube_locations().T ax.plot(xs, ys, transform=ccrs.OSGB(), marker=concentric_circle, color='red', markersize=9, linestyle='') ax.plot(xs, ys, transform=ccrs.OSGB(), marker=rectangle, color='blue', markersize=11, linestyle='') ax.set_title('London underground locations') plt.show()
def test_3pt_poly(self): projection = ccrs.OSGB(approx=True) polygon = sgeom.Polygon([(-1000, -1000), (-1000, 200000), (200000, -1000)]) multi_polygon = projection.project_geometry(polygon, ccrs.OSGB(approx=True)) assert len(multi_polygon) == 1 assert len(multi_polygon[0].exterior.coords) == 4
def test_gridliner(): ny, nx = 2, 4 plt.figure(figsize=(10, 10)) ax = plt.subplot(nx, ny, 1, projection=ccrs.PlateCarree()) ax.set_global() ax.coastlines(resolution="110m") ax.gridlines(linestyle=':') ax = plt.subplot(nx, ny, 2, projection=ccrs.OSGB(approx=False)) ax.set_global() ax.coastlines(resolution="110m") ax.gridlines(linestyle=':') ax = plt.subplot(nx, ny, 3, projection=ccrs.OSGB(approx=False)) ax.set_global() ax.coastlines(resolution="110m") ax.gridlines(ccrs.PlateCarree(), color='blue', linestyle='-') ax.gridlines(ccrs.OSGB(approx=False), linestyle=':') ax = plt.subplot(nx, ny, 4, projection=ccrs.PlateCarree()) ax.set_global() ax.coastlines(resolution="110m") ax.gridlines(ccrs.NorthPolarStereo(), alpha=0.5, linewidth=1.5, linestyle='-') ax = plt.subplot(nx, ny, 5, projection=ccrs.PlateCarree()) ax.set_global() ax.coastlines(resolution="110m") osgb = ccrs.OSGB(approx=False) ax.set_extent(tuple(osgb.x_limits) + tuple(osgb.y_limits), crs=osgb) ax.gridlines(osgb, linestyle=':') ax = plt.subplot(nx, ny, 6, projection=ccrs.NorthPolarStereo()) ax.set_global() ax.coastlines(resolution="110m") ax.gridlines(alpha=0.5, linewidth=1.5, linestyle='-') ax = plt.subplot(nx, ny, 7, projection=ccrs.NorthPolarStereo()) ax.set_global() ax.coastlines(resolution="110m") osgb = ccrs.OSGB(approx=False) ax.set_extent(tuple(osgb.x_limits) + tuple(osgb.y_limits), crs=osgb) ax.gridlines(osgb, linestyle=':') ax = plt.subplot(nx, ny, 8, projection=ccrs.Robinson(central_longitude=135)) ax.set_global() ax.coastlines(resolution="110m") ax.gridlines(ccrs.PlateCarree(), alpha=0.5, linewidth=1.5, linestyle='-') delta = 1.5e-2 plt.subplots_adjust(left=0 + delta, right=1 - delta, top=1 - delta, bottom=0 + delta)
def _nearest_dry_cell(self, rain, lat, lon): ospts = ccrs.OSGB().transform_points( rain.coord_system().as_cartopy_crs(), rain.coord('grid_longitude').points[np.where(rain.data == 0)[1]], rain.coord('grid_latitude').points[np.where( rain.data == 0)[0]])[:, :2] nbrs = NearestNeighbors(n_neighbors=1, algorithm='kd_tree').fit(ospts) x = ccrs.OSGB().transform_point( rain.coord('grid_longitude').points[lon], rain.coord('grid_latitude').points[lat], rain.coord_system().as_cartopy_crs()) return nbrs.kneighbors(np.array([x]))[0].flatten()[0] / 1000
def test_new_coords(self): u, v = self._uv_cubes_limited_extent() x = u.coord("grid_longitude").points y = u.coord("grid_latitude").points x2d, y2d = np.meshgrid(x, y) src_crs = ccrs.RotatedPole(pole_longitude=177.5, pole_latitude=37.5) tgt_crs = ccrs.OSGB() xyz_tran = tgt_crs.transform_points(src_crs, x2d, y2d) ut, vt = rotate_winds(u, v, iris.coord_systems.OSGB()) points = xyz_tran[..., 0].reshape(x2d.shape) expected_x = AuxCoord( points, standard_name="projection_x_coordinate", units="m", coord_system=iris.coord_systems.OSGB(), ) self.assertEqual(ut.coord("projection_x_coordinate"), expected_x) self.assertEqual(vt.coord("projection_x_coordinate"), expected_x) points = xyz_tran[..., 1].reshape(y2d.shape) expected_y = AuxCoord( points, standard_name="projection_y_coordinate", units="m", coord_system=iris.coord_systems.OSGB(), ) self.assertEqual(ut.coord("projection_y_coordinate"), expected_y) self.assertEqual(vt.coord("projection_y_coordinate"), expected_y)
def test_wfs(): ax = plt.axes(projection=ccrs.OSGB()) url = 'http://nsidc.org/cgi-bin/atlas_south?service=WFS' typename = 'land_excluding_antarctica' feature = cfeature.WFSFeature(url, typename, edgecolor='red') ax.add_feature(feature)
def test_default(self): proj = ccrs.OSGB() res = proj.transform_point(*self.point_a, src_crs=self.src_crs) np.testing.assert_array_almost_equal(res, (295971.28667707, 93064.27666368)) res = proj.transform_point(*self.point_b, src_crs=self.src_crs) np.testing.assert_array_almost_equal(res, (577274.98380140, 69740.49227181))
def test_default(self, approx): proj = ccrs.OSGB(approx=approx) res = proj.transform_point(*self.point_a, src_crs=self.src_crs) np.testing.assert_array_almost_equal(res, (295971.28668, 93064.27666), decimal=5) res = proj.transform_point(*self.point_b, src_crs=self.src_crs) np.testing.assert_array_almost_equal(res, (577274.98380, 69740.49227), decimal=5)
def test_domain_extents(): # Setting the extent to global or the domain limits. ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent((-180, 180, -90, 90)) assert_array_equal(ax.viewLim.get_points(), [[-180, -90], [180, 90]]) ax.set_extent((-180, 180, -90, 90), ccrs.PlateCarree()) assert_array_equal(ax.viewLim.get_points(), [[-180, -90], [180, 90]]) ax = plt.axes(projection=ccrs.PlateCarree(90)) ax.set_extent((-180, 180, -90, 90)) assert_array_equal(ax.viewLim.get_points(), [[-180, -90], [180, 90]]) ax.set_extent((-180, 180, -90, 90), ccrs.PlateCarree(90)) assert_array_equal(ax.viewLim.get_points(), [[-180, -90], [180, 90]]) ax = plt.axes(projection=ccrs.OSGB()) ax.set_extent((0, 7e5, 0, 13e5), ccrs.OSGB()) assert_array_equal(ax.viewLim.get_points(), [[0, 0], [7e5, 13e5]])
def spatial_density_all_time_all_crimes(): poly = get_camden_region() camden_mpoly = geodjango_to_shapely([get_camden_region()]) oo = osm.OsmRendererBase(poly, buffer=100) cbg = CadByGrid() a = cbg.all_time_aggregate() fig = plt.figure(figsize=(8, 8)) ax = fig.add_subplot(111, projection=ccrs.OSGB()) ax.set_extent([523000, 533000, 179000, 190000], ccrs.OSGB()) ax.background_patch.set_visible(False) oo.render(ax) a = a.sum(axis=1) cmap = mpl.cm.Reds norm = mpl.colors.Normalize() norm.autoscale(a) cax = mpl.colorbar.make_axes(ax, location='bottom', pad=0.02, fraction=0.05, shrink=0.9) cbar = mpl.colorbar.ColorbarBase(cax[0], cmap=cmap, norm=norm, orientation='horizontal') sm = mpl.cm.ScalarMappable(norm=norm, cmap=cmap) for j in range(cbg.m): val = a.values[j] fc = sm.to_rgba(val) if val else 'none' ax.add_geometries(geodjango_to_shapely([cbg.grid[j].mpoly]), ccrs.OSGB(), facecolor=fc, alpha=0.3) ax.add_geometries(camden_mpoly, ccrs.OSGB(), facecolor='none', edgecolor='black') plt.show()
def plot_spatial_density_all_time_by_crime(cad_spatial_grid): n = len(cad_spatial_grid) poly = get_camden_region() xmin, ymin, xmax, ymax = poly.buffer(100).extent oo = osm.OsmRendererBase(poly, buffer=100) fig = plt.figure(figsize=(15, 6)) axes = [ fig.add_subplot(1, n, i + 1, projection=ccrs.OSGB()) for i in range(n) ] fig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95, wspace=0.03, hspace=0.01) count = 0 for i, this_cbg in enumerate(cad_spatial_grid.itervalues()): ax = axes[i] oo.render(ax) ds = this_cbg.all_time_aggregate().values.flatten() ax.set_extent([xmin, xmax, ymin, ymax], ccrs.OSGB()) ax.background_patch.set_visible(False) cmap = mpl.cm.autumn norm = mpl.colors.Normalize(0, max(ds)) cax = mpl.colorbar.make_axes(ax, location='bottom', pad=0.02, fraction=0.05, shrink=0.9) cbar = mpl.colorbar.ColorbarBase(cax[0], cmap=cmap, norm=norm, orientation='horizontal') sm = mpl.cm.ScalarMappable(norm=norm, cmap=cmap) for j in range(len(this_cbg.grid)): val = ds[j] fc = sm.to_rgba(val) if val else 'none' ax.add_geometries(this_cbg.shapely_grid[j:j + 1], ccrs.OSGB(), facecolor=fc) # ax.add_geometries(geodjango_to_shapely(poly), ccrs.OSGB(), facecolor='none', edgecolor='black') plt.show()
def test_triplot_bbox_tight(): """Test triplot with a tight bbox (#1060).""" x = np.degrees([-0.101, -0.090, -0.069]) y = np.degrees([0.872, 0.883, 0.888]) triangles = np.asarray([[0, 1, 2]]) fig = plt.figure() ax = plt.axes(projection=ccrs.OSGB(approx=False)) ax.triplot(x, y, triangles, transform=ccrs.Geodetic()) fig.savefig(BytesIO(), bbox_inches='tight')
def test_unsupported_projection(self): source = ogc.WMSRasterSource(self.URI, self.layer) # Patch dict of known Proj->SRS mappings so that it does # not include any of the available SRSs from the WMS. with mock.patch.dict('cartopy.io.ogc_clients._CRS_TO_OGC_SRS', {ccrs.OSGB(): 'EPSG:27700'}, clear=True): msg = 'not available' with self.assertRaisesRegexp(ValueError, msg): source.validate_projection(ccrs.Miller())
def plot_maps(self, number_of_systems=None, _title="25,000 Systems", version=0, scale=500): """Plot map of passiv systems""" if number_of_systems is None: _data = self.data else: _data = self.data.sample(number_of_systems) _data.sort_values(by="kwp", axis=0, inplace=True) res_list = convert_bng(_data.longitude.values.tolist(), _data.latitude.values.tolist()) fig, ax = plt.subplots(figsize=(6, 12)) ax = plt.axes(projection=ccrs.OSGB()) ax.set_extent([1393.0196, 671196.3657, 13494.9764, 1230275.0454], crs=ccrs.OSGB()) ax.coastlines(resolution='50m') ax.gridlines() ax.set_title(_title, fontsize=18) marker_scale = _data.kwp.values sc = ax.scatter(res_list[0], res_list[1], c=marker_scale, s=10, marker="o", cmap="Spectral") clb = plt.colorbar(sc) clb.ax.set_title("kWp") fig_name = "../graphs/passiv_map_{}_{}.png".format( number_of_systems, version) fig.savefig(fig_name, bbbbox_inches="tight", dpi=600, transparent=True) plt.show() return fig
def test_new_coords_transposed(self): u, v = self._uv_cubes_limited_extent() # Transpose cubes so that cube is in xy order rather than the # typical yx order of meshgrid. u.transpose() v.transpose() x = u.coord("grid_longitude").points y = u.coord("grid_latitude").points x2d, y2d = np.meshgrid(x, y) src_crs = ccrs.RotatedPole(pole_longitude=177.5, pole_latitude=37.5) tgt_crs = ccrs.OSGB() xyz_tran = tgt_crs.transform_points(src_crs, x2d, y2d) ut, vt = rotate_winds(u, v, iris.coord_systems.OSGB()) points = xyz_tran[..., 0].reshape(x2d.shape) expected_x = AuxCoord( points, standard_name="projection_x_coordinate", units="m", coord_system=iris.coord_systems.OSGB(), ) self.assertEqual(ut.coord("projection_x_coordinate"), expected_x) self.assertEqual(vt.coord("projection_x_coordinate"), expected_x) points = xyz_tran[..., 1].reshape(y2d.shape) expected_y = AuxCoord( points, standard_name="projection_y_coordinate", units="m", coord_system=iris.coord_systems.OSGB(), ) self.assertEqual(ut.coord("projection_y_coordinate"), expected_y) self.assertEqual(vt.coord("projection_y_coordinate"), expected_y) # Check dim mapping for 2d coords is yx. expected_dims = u.coord_dims("grid_latitude") + u.coord_dims( "grid_longitude" ) self.assertEqual( ut.coord_dims("projection_x_coordinate"), expected_dims ) self.assertEqual( ut.coord_dims("projection_y_coordinate"), expected_dims ) self.assertEqual( vt.coord_dims("projection_x_coordinate"), expected_dims ) self.assertEqual( vt.coord_dims("projection_y_coordinate"), expected_dims )
def test_multiple_projections(): projections = [ ccrs.PlateCarree(), ccrs.Robinson(), ccrs.RotatedPole(pole_latitude=45, pole_longitude=180), ccrs.OSGB(), ccrs.TransverseMercator(), ccrs.Mercator(globe=ccrs.Globe(semimajor_axis=math.degrees(1)), min_latitude=-85., max_latitude=85.), ccrs.LambertCylindrical(), ccrs.Miller(), ccrs.Gnomonic(), ccrs.Stereographic(), ccrs.NorthPolarStereo(), ccrs.SouthPolarStereo(), ccrs.Orthographic(), ccrs.Mollweide(), ccrs.InterruptedGoodeHomolosine(), ] if ccrs.PROJ4_VERSION < (5, 0, 0): # Produce the same sized image for old proj, to avoid having to replace # the image. If this figure is regenerated for both old and new proj, # then drop this condition. rows = 5 else: rows = np.ceil(len(projections) / 5) fig = plt.figure(figsize=(10, 2 * rows)) for i, prj in enumerate(projections, 1): ax = fig.add_subplot(rows, 5, i, projection=prj) ax.set_global() ax.coastlines() plt.plot(-0.08, 51.53, 'o', transform=ccrs.PlateCarree()) plt.plot([-0.08, 132], [51.53, 43.17], color='red', transform=ccrs.PlateCarree()) plt.plot([-0.08, 132], [51.53, 43.17], color='blue', transform=ccrs.Geodetic())
def test_multiple_projections(): projections = [ ccrs.PlateCarree(), ccrs.Robinson(), ccrs.RotatedPole(pole_latitude=45, pole_longitude=180), ccrs.OSGB(approx=True), ccrs.TransverseMercator(approx=True), ccrs.Mercator(globe=ccrs.Globe(semimajor_axis=math.degrees(1)), min_latitude=-85., max_latitude=85.), ccrs.LambertCylindrical(), ccrs.Miller(), ccrs.Gnomonic(), ccrs.Stereographic(), ccrs.NorthPolarStereo(), ccrs.SouthPolarStereo(), ccrs.Orthographic(), ccrs.Mollweide(), ccrs.InterruptedGoodeHomolosine(emphasis='land'), ccrs.EckertI(), ccrs.EckertII(), ccrs.EckertIII(), ccrs.EckertIV(), ccrs.EckertV(), ccrs.EckertVI(), ] rows = np.ceil(len(projections) / 5).astype(int) fig = plt.figure(figsize=(10, 2 * rows)) for i, prj in enumerate(projections, 1): ax = fig.add_subplot(rows, 5, i, projection=prj) ax.set_global() ax.coastlines(resolution="110m") plt.plot(-0.08, 51.53, 'o', transform=ccrs.PlateCarree()) plt.plot([-0.08, 132], [51.53, 43.17], color='red', transform=ccrs.PlateCarree()) plt.plot([-0.08, 132], [51.53, 43.17], color='blue', transform=ccrs.Geodetic())
def plot_shapes(path): plt.figure(figsize=(6, 6), dpi=150) proj = ccrs.OSGB() ax = plt.axes(projection=proj) ax.outline_patch.set_visible(False) geoms = [] for record in shpreader.Reader(path).records(): geoms.append(record.geometry) ax.add_geometries(geoms, crs=proj, edgecolor='white', facecolor='#efefef') output_filename = os.path.join( os.getcwd(), 'map.png' ) plt.savefig(output_filename)
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 map_plotter(x, y): # setting up the axes to plot into ax = plt.axes(projection=ccrs.OSGB()) ax.set_extent([307000.0, 336000.0, 657000.0, 684000.0], crs=ccrs.OSGB()) # looping through the dictionary data for plotting for b in range(len(x)): plt.plot(x[b], y[b], color='black', linewidth=0.8, transform=ccrs.OSGB()) # loading the SAVI basemap fname = 'edin_SAVI_277.tif' # satellite image for basemap img_extent = (307059.5282843578606844, 335615.2470486343372613, 656490.9100024187937379, 683219.2234168014256284) img = plt.imread(fname) ax.imshow(img, origin='upper', extent=img_extent, transform=ccrs.OSGB()) ax.set_xticks([308000, 335000], crs=ccrs.OSGB()) ax.set_yticks([658000, 681000], crs=ccrs.OSGB()) # manual labels as cartopy doesn't support OSGB grid labels yet ax.text(307000, 669000, 'Northing', va='bottom', ha='center', rotation='vertical', rotation_mode='anchor', transform=ccrs.OSGB()) ax.text(321500, 655500, 'Easting', va='bottom', ha='center', rotation='horizontal', rotation_mode='anchor', transform=ccrs.OSGB()) return (map_plotter)
def quiver_plot(wind_slice, direction_slice, step): """ Calculate U and V and plot quivers. """ U = (wind_slice.data) * np.cos(np.deg2rad(direction_slice.data)) V = (wind_slice.data) * np.sin(np.deg2rad(direction_slice.data)) X = wind_slice.coord('projection_x_coordinate').points Y = wind_slice.coord('projection_y_coordinate').points arrows = plt.quiver(X[::step], Y[::step], U[::step, ::step], V[::step, ::step], units='xy', headwidth=2, transform=ccrs.OSGB(), zorder=1.0) return arrows
def test_osgb(self): osgb = ccrs.OSGB() ll = ccrs.Geodetic() # results obtained by streetmap.co.uk. lat, lon = np.array([50.462023, -3.478831], dtype=np.double) east, north = np.array([295131, 63511], dtype=np.double) # note the handling of precision here... assert_arr_almost_eq(np.array(osgb.transform_point(lon, lat, ll)), np.array([east, north]), 1) assert_arr_almost_eq(ll.transform_point(east, north, osgb), [lon, lat], 2) r_lon, r_lat = ll.transform_point(east, north, osgb) r_inverted = np.array(osgb.transform_point(r_lon, r_lat, ll)) assert_arr_almost_eq(r_inverted, [east, north], 3) r_east, r_north = osgb.transform_point(lon, lat, ll) r_inverted = np.array(ll.transform_point(r_east, r_north, osgb)) assert_arr_almost_eq(r_inverted, [lon, lat])
def _transform_pv_systems(pv_systems: xr.Dataset) -> xr.Dataset: """Transform the system locations into the same coordinate system used by UKV""" system_latitudes, system_longitudes = ( pv_systems["latitude"].values, pv_systems["longitude"].values, ) wgs84 = ccrs.Geodetic() ukv_crs = ccrs.OSGB(approx=False) locs = ukv_crs.transform_points( src_crs=wgs84, x=np.asanyarray(system_longitudes), y=np.asanyarray(system_latitudes), )[:, :-1] new_coords = { "easting": (["system_id"], locs[:, 0].astype("int32")), "northing": (["system_id"], locs[:, 1].astype("int32")), } return pv_systems.assign_coords(new_coords)
def test_multiple_projections(): projections = [ ccrs.PlateCarree(), ccrs.Robinson(), ccrs.RotatedPole(pole_latitude=45, pole_longitude=180), ccrs.OSGB(), ccrs.TransverseMercator(), ccrs.Mercator(globe=ccrs.Globe(semimajor_axis=math.degrees(1)), min_latitude=-85., max_latitude=85.), ccrs.LambertCylindrical(), ccrs.Miller(), ccrs.Gnomonic(), ccrs.Stereographic(), ccrs.NorthPolarStereo(), ccrs.SouthPolarStereo(), ccrs.Orthographic(), ccrs.Mollweide(), ccrs.InterruptedGoodeHomolosine(), ] fig = plt.figure(figsize=(10, 10)) for i, prj in enumerate(projections, 1): ax = fig.add_subplot(5, 5, i, projection=prj) ax.set_global() ax.coastlines() plt.plot(-0.08, 51.53, 'o', transform=ccrs.PlateCarree()) plt.plot([-0.08, 132], [51.53, 43.17], color='red', transform=ccrs.PlateCarree()) plt.plot([-0.08, 132], [51.53, 43.17], color='blue', transform=ccrs.Geodetic())
def test_osgb(self): self._check_osgb(ccrs.OSGB())
def test_nan(self): proj = ccrs.OSGB(approx=True) res = proj.transform_point(0.0, float('nan'), src_crs=self.src_crs) assert np.all(np.isnan(res)) res = proj.transform_point(float('nan'), 0.0, src_crs=self.src_crs) assert np.all(np.isnan(res))
def map_plot(user_location, user_node, high_point, high_node, dataset, shortest_path_gpd, flood_poly=False): """This function plots a map of the user_location, highest point and shortest path gpd df over an OS Explorer and elevation raster basemap. """ print("\nPlotting your shortest route to higher ground...") # background and the map extent background = rasterio.open('data/background/raster-50k_2724246.tif') back_array = background.read(1) palette = np.array( [value for key, value in background.colormap(1).items()]) background_image = palette[back_array] bg_extent = [ background.bounds.left, background.bounds.right, background.bounds.bottom, background.bounds.top ] el_extent = [ dataset.bounds.left, dataset.bounds.right, dataset.bounds.bottom, dataset.bounds.top ] display_extent = [((user_location.x + high_point.x) / 2) - 5000, ((user_location.x + high_point.x) / 2) + 5000, ((user_location.y + high_point.y) / 2) - 5000, ((user_location.y + high_point.y) / 2) + 5000] # Task 5: Map Plotting # defining the walking path between the user and the nearest NIT node # and defining the walking path between highest point and its nearest NIT node waking_route_user_node_lons = [user_location.x, user_node.x] waking_route_user_node_lats = [user_location.y, user_node.y] waking_route_highest_point_lons = [high_point.x, high_node.x] waking_route_highest_point_lats = [high_point.y, high_node.y] # Set up figure and extent fig = plt.figure(figsize=(3, 3), dpi=300) ax = fig.add_subplot(1, 1, 1, projection=ccrs.OSGB()) ax.set_extent(display_extent, crs=ccrs.OSGB()) # imshow for the background ax.imshow(background_image, origin="upper", extent=bg_extent, zorder=0) # imshow for the elevation raster plt.imshow(dataset.read(1), extent=el_extent, cmap='gist_earth', origin='upper', zorder=0, alpha=0.65, resample='True', vmax=numpy.amax(dataset.read(1)), vmin=numpy.amin(dataset.read(1))) if flood_poly: for i in flood_poly.geoms: plt.plot(*i.exterior.xy, color="darkgray", linewidth=0.5, alpha=0.7) # plotting the shortest path shortest_path_gpd.plot(ax=ax, edgecolor="orangered", linewidth=0.5, zorder=2, label='ITN shortest path') # scattering the user point the highest elevation point ax.scatter(user_location.x, user_location.y, s=1.5, c='r', label='Your location', marker="*") ax.scatter(high_point.x, high_point.y, s=1.5, c='k', label='Highest_point', marker='*') # user_location.xy()[1] arrow x, y, arrow_length = 0.9, 0.95, 0.18 ax.annotate('N', xy=(x, y), xytext=(x, y - arrow_length), arrowprops=dict(facecolor='black', width=2, headwidth=8), ha='center', va='center', fontsize=9, xycoords=ax.transAxes) # adding scale bar scalebar = AnchoredSizeBar(ax.transData, 1000, '1 km', 'lower center', pad=0.1, color='black', frameon=False, size_vertical=1) ax.add_artist(scalebar) # 6) plotting the color bar cbar = plt.colorbar(fraction=0.03, pad=0.03) cbar.set_label(r"Elevation", size=8) cbar.ax.tick_params(labelsize=5) # 7) plotting the walking paths ax.plot(waking_route_user_node_lons, waking_route_user_node_lats, c='k', label='walking route', linewidth=0.5, linestyle='dashed') link_patch = mlines.Line2D([], [], color='orangered', label='ITN Shortest Path', linewidth=0.5) walk_patch = mlines.Line2D([], [], color='k', label='Walking route', linewidth=0.5, linestyle='dashed') user_star = mlines.Line2D([], [], color='r', marker="*", linestyle='None', markersize=2, label='Your location') high_point = mlines.Line2D([], [], color='k', marker='*', linestyle='None', markersize=2, label='Highest point') # Dynamic legend - can handle absence of flood_poly if flood_poly: flood_patch = mlines.Line2D([], [], color='darkgray', label='Flood line', linewidth=0.5) plt.legend(fontsize=3, loc=2, handles=[ user_star, high_point, walk_patch, link_patch, flood_patch ], title="Legend") else: plt.legend(fontsize=3, loc=2, handles=[user_star, high_point, walk_patch, link_patch], title="Legend") ax.plot(waking_route_highest_point_lons, waking_route_highest_point_lats, c='k', label='walking route', linewidth=0.5, linestyle='dashed') plt.show()
def test_grid_labels(): plt.figure(figsize=(8, 10)) crs_pc = ccrs.PlateCarree() crs_merc = ccrs.Mercator() crs_osgb = ccrs.OSGB() ax = plt.subplot(3, 2, 1, projection=crs_pc) ax.coastlines() ax.gridlines(draw_labels=True) # Check that adding labels to Mercator gridlines gives an error. # (Currently can only label PlateCarree gridlines.) ax = plt.subplot(3, 2, 2, projection=ccrs.PlateCarree(central_longitude=180)) ax.coastlines() with pytest.raises(TypeError): ax.gridlines(crs=crs_merc, draw_labels=True) ax.set_title('Known bug') gl = ax.gridlines(crs=crs_pc, draw_labels=True) gl.xlabels_top = False gl.ylabels_left = False gl.xlines = False ax = plt.subplot(3, 2, 3, projection=crs_merc) ax.coastlines() ax.gridlines(draw_labels=True) # Check that labelling the gridlines on an OSGB plot gives an error. # (Currently can only draw these on PlateCarree or Mercator plots.) ax = plt.subplot(3, 2, 4, projection=crs_osgb) ax.coastlines() with pytest.raises(TypeError): ax.gridlines(draw_labels=True) ax = plt.subplot(3, 2, 4, projection=crs_pc) ax.coastlines() gl = ax.gridlines(crs=crs_pc, linewidth=2, color='gray', alpha=0.5, linestyle='--') gl.xlabels_bottom = True gl.ylabels_right = True gl.xlines = False gl.xlocator = mticker.FixedLocator([-180, -45, 45, 180]) gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabel_style = {'size': 15, 'color': 'gray'} gl.xlabel_style = {'color': 'red'} gl.xpadding = 10 gl.ypadding = 15 # trigger a draw at this point and check the appropriate artists are # populated on the gridliner instance FigureCanvasAgg(plt.gcf()).draw() assert len(gl.xlabel_artists) == 4 assert len(gl.ylabel_artists) == 5 assert len(gl.ylabel_artists) == 5 assert len(gl.xline_artists) == 0 ax = plt.subplot(3, 2, 5, projection=crs_pc) ax.set_extent([-20, 10.0, 45.0, 70.0]) ax.coastlines() ax.gridlines(draw_labels=True) ax = plt.subplot(3, 2, 6, projection=crs_merc) ax.set_extent([-20, 10.0, 45.0, 70.0], crs=crs_pc) ax.coastlines() ax.gridlines(draw_labels=True) # Increase margins between plots to stop them bumping into one another. plt.subplots_adjust(wspace=0.25, hspace=0.25)