Skip to content

Instantly share code, notes, and snippets.

@adriantre
Created June 5, 2018 22:27
Show Gist options
  • Save adriantre/600deac0ccac517086a1d21d5a9b1aa4 to your computer and use it in GitHub Desktop.
Save adriantre/600deac0ccac517086a1d21d5a9b1aa4 to your computer and use it in GitHub Desktop.
def map_points(df, lat_col='latitude', lon_col='longitude', zoom_start=11, \
plot_points=False, pt_radius=15, \
draw_heatmap=False, heat_map_weights_col=None, \
heat_map_weights_normalize=True, heat_map_radius=15):
"""Creates a map given a dataframe of points. Can also produce a heatmap overlay
Arg:
df: dataframe containing points to maps
lat_col: Column containing latitude (string)
lon_col: Column containing longitude (string)
zoom_start: Integer representing the initial zoom of the map
plot_points: Add points to map (boolean)
pt_radius: Size of each point
draw_heatmap: Add heatmap to map (boolean)
heat_map_weights_col: Column containing heatmap weights
heat_map_weights_normalize: Normalize heatmap weights (boolean)
heat_map_radius: Size of heatmap point
Returns:
folium map object
"""
## center map in the middle of points center in
middle_lat = df[lat_col].median()
middle_lon = df[lon_col].median()
curr_map = folium.Map(location=[middle_lat, middle_lon],
zoom_start=zoom_start)
# add points to map
if plot_points:
for _, row in df.iterrows():
folium.CircleMarker([row[lat_col], row[lon_col]],
radius=pt_radius,
popup=row['name'],
fill_color="#3db7e4", # divvy color
).add_to(curr_map)
# add heatmap
if draw_heatmap:
# convert to (n, 2) or (n, 3) matrix format
if heat_map_weights_col is None:
stations = zip(df[lat_col], df[lon_col])
else:
# if we have to normalize
if heat_map_weights_normalize:
df[heat_map_weights_col] = \
df[heat_map_weights_col] / df[heat_map_weights_col].sum()
stations = zip(df[lat_col], df[lon_col], df[heat_map_weights_col])
curr_map.add_child(plugins.HeatMap(stations, radius=heat_map_radius))
return curr_map
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment