|
| 1 | +import geopandas as gpd |
| 2 | +from geopandas.geodataframe import GeoDataFrame as gdf |
| 3 | +from typing import Optional |
| 4 | +import contextily as cx |
| 5 | +import matplotlib.pyplot as plt |
| 6 | +from dotenv import load_dotenv |
| 7 | +import os |
| 8 | + |
| 9 | +MAP_BOX_KEY = os.getenv('MAP_BOX_KEY') |
| 10 | + |
| 11 | +def plot_radius(df: gdf, target: gdf, rad: int=300, |
| 12 | + feature: Optional[str]=None, |
| 13 | + basemap: bool=False, |
| 14 | + ax=None, |
| 15 | + legend=False): |
| 16 | + |
| 17 | + targ_cent = target.geometry.centroid |
| 18 | + |
| 19 | + circle = targ_cent.buffer(rad) |
| 20 | + idx = df.sindex.query(circle, predicate="intersects") |
| 21 | + idx = idx[1,:] |
| 22 | + df_plot = df.iloc[idx].copy() |
| 23 | + |
| 24 | + if basemap: |
| 25 | + alpha=0.8 |
| 26 | + else: |
| 27 | + alpha=1 |
| 28 | + |
| 29 | + |
| 30 | + ax = target.plot(ax=ax, marker='x', color="blue", zorder=10) |
| 31 | + ax = df_plot.plot(ax=ax, figsize=(8,6), column=feature, legend=legend, |
| 32 | + legend_kwds={"label": feature}, alpha=alpha, zorder=5, |
| 33 | + vmin=0, vmax=10 |
| 34 | + ) |
| 35 | + |
| 36 | + ax.set_axis_off() |
| 37 | + |
| 38 | + if basemap: |
| 39 | + cx.add_basemap(ax, crs=df_plot.crs.to_string(), |
| 40 | + source="https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/{z}/{x}/{y}{r}?access_token={MAP_BOX_KEY}", |
| 41 | + zoom=18, zorder=1) |
| 42 | + |
| 43 | + return ax |
| 44 | + |
| 45 | +def compiled_plot(df: gdf, target: gdf, rad: int=250, |
| 46 | + feature: Optional[str]=None): |
| 47 | + |
| 48 | + # using tuple unpacking for multiple Axes |
| 49 | + fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16,7)) |
| 50 | + |
| 51 | + plot_radius(ax=ax1, df=df, target=target, feature=feature, legend=True) |
| 52 | + plot_radius(ax=ax2, df=df, target=target, feature=feature, basemap=True, rad=70, legend=False) |
| 53 | + print(target.centroid.to_crs("EPSG:4326")) |
0 commit comments