Skip to content

Instantly share code, notes, and snippets.

@jens-andersson-2-wcar
Last active November 15, 2023 14:04
Show Gist options
  • Save jens-andersson-2-wcar/7cecb40db1fbc051f2822262be42d11b to your computer and use it in GitHub Desktop.
Save jens-andersson-2-wcar/7cecb40db1fbc051f2822262be42d11b to your computer and use it in GitHub Desktop.
Jupyter notebook snippet for plotting H3 hexagons on Folium maps
!conda install -y folium geojson
import folium
from geojson import Feature, Point, FeatureCollection
import json
def hexagons_dataframe_to_geojson(df_hex, file_output = None, column_name = "value"):
"""
Produce the GeoJSON for a dataframe, constructing the geometry from the "hex_id" column
and with a property matching the one in column_name
"""
list_features = []
for i,row in df_hex.iterrows():
try:
geometry_for_row = { "type" : "Polygon", "coordinates": [h3.h3_to_geo_boundary(h=row["hex_id"],geo_json=True)]}
feature = Feature(geometry = geometry_for_row , id=row["hex_id"], properties = {column_name : row[column_name]})
list_features.append(feature)
except:
print("An exception occurred for hex " + row["hex_id"])
feat_collection = FeatureCollection(list_features)
geojson_result = json.dumps(feat_collection)
return geojson_result
def get_color(custom_cm, val, vmin, vmax):
return matplotlib.colors.to_hex(custom_cm((val-vmin)/(vmax-vmin)))
def choropleth_map(df_aggreg, column_name = "value", border_color = 'black', fill_opacity = 0.7, color_map_name = "Blues", initial_map = None):
"""
Creates choropleth maps given the aggregated data. initial_map can be an existing map to draw on top of.
"""
#colormap
min_value = df_aggreg[column_name].min()
max_value = df_aggreg[column_name].max()
mean_value = df_aggreg[column_name].mean()
print(f"Colour column min value {min_value}, max value {max_value}, mean value {mean_value}")
print(f"Hexagon cell count: {df_aggreg['hex_id'].nunique()}")
# the name of the layer just needs to be unique, put something silly there for now:
name_layer = "Choropleth " + str(df_aggreg)
if initial_map is None:
initial_map = folium.Map(location= [47, 4], zoom_start=5.5, tiles="cartodbpositron")
#create geojson data from dataframe
geojson_data = hexagons_dataframe_to_geojson(df_hex = df_aggreg, column_name = column_name)
# color_map_name 'Blues' for now, many more at https://matplotlib.org/stable/tutorials/colors/colormaps.html to choose from!
custom_cm = matplotlib.cm.get_cmap(color_map_name)
folium.GeoJson(
geojson_data,
style_function=lambda feature: {
'fillColor': get_color(custom_cm, feature['properties'][column_name], vmin=min_value, vmax=max_value),
'color': border_color,
'weight': 1,
'fillOpacity': fill_opacity
},
name = name_layer
).add_to(initial_map)
return initial_map
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment