city_retrofit/utilities.py

40 lines
1.9 KiB
Python
Raw Permalink Normal View History

import pandas as pd
import matplotlib.pyplot as plt
from shapely.geometry import Polygon
import geopandas as gpd
import contextily as cx
### --- PLOTTING FUNCTIONS --- ###
def plot_it(buildings_list, column=None, legend=False, basemap=True, multipolygon=False, alpha=1, labeled=False, edgecolor='black', title=None, figx=5, figy=5):
dataset = geodataframe_of(buildings_list, multipolygon) if not isinstance(buildings_list, gpd.GeoDataFrame) else buildings_list
dataset = dataset.to_crs('EPSG:32198')
# Set the color cycle to a set of distinct colors
num_colors = max(10, len(dataset.geometry.unique()))
plt.rcParams['axes.prop_cycle'] = plt.cycler(color=plt.cm.tab20.colors[:num_colors])
ax = dataset.plot(column=column, legend=legend, alpha=alpha, figsize=(figx, figy), edgecolor=edgecolor)
if basemap:
cx.add_basemap(ax, crs=dataset.crs.to_string(), source=cx.providers.OpenStreetMap.Mapnik)
if column and labeled:
for x, y, label in zip(dataset.geometry.centroid.x, dataset.geometry.centroid.y, dataset[column]):
ax.annotate(label, xy=(x, y), xytext=(0, 0), textcoords="offset points", ha='center', fontsize=6)
ax.set_axis_off()
ax.set_title(title or column)
return
def geometry_generator(bldgs, multipolygon=False):
return [Polygon(bldgs.iloc[i]["geom"]["coordinates"][0][0] if multipolygon else bldgs.iloc[i]["geom"]["coordinates"][0]) for i in range(len(bldgs))]
def geodataframe_of(buildings_list, multipolygon=False, crs='EPSG:32198'):
if 'geom' in buildings_list.columns:
print("there is 'geom' in columns")
geometry = geometry_generator(buildings_list, multipolygon)
elif 'geometry' in buildings_list.columns:
print('there is "geometry" in columns')
geometry = buildings_list.geometry
else:
print('no geometry detected')
return gpd.GeoDataFrame()
return gpd.GeoDataFrame(buildings_list, geometry=geometry, crs='epsg:4326').to_crs(crs)