HeatMapWithTime Plugin in Folium

3.9k Views Asked by At

I was able to create a HeatMap but the points are not showing:

import folium
import folium.plugins as plugins
import numpy as np
import pandas as pd
import geopandas as gpd
from folium import Choropleth, Circle, Marker
from folium.plugins import HeatMap, MarkerCluster, HeatMapWithTime
ucdp_df = pd.read_csv('csv/ged201.csv') # from https://ucdp.uu.se/downloads/index.html#ged_global
ucdp = gpd.GeoDataFrame(ucdp_df, geometry=gpd.points_from_xy(ucdp_df.longitude, ucdp_df.latitude))
ucdp.crs = {'init': 'epsg:4326'}
m = folium.Map([35, 41], tiles='stamentoner', zoom_start=6)
hm = HeatMapWithTime(data=ucdp[['latitude', 'longitude']].values.tolist(),
                     index=ucdp['year'].values.tolist(), 
                     radius=10,
                     auto_play=True,
                     max_opacity=0.3)
hm.add_to(m)
m
1

There are 1 best solutions below

3
On

You need to provide the data in a correct format. This should work:

from collections import defaultdict, OrderedDict

data = defaultdict(list)
for r in ucdp_df.itertuples():
    data[r.year].append([r.latitude, r.longitude])
    
data = OrderedDict(sorted(data.items(), key=lambda t: t[0]))

Then use the data:

m = folium.Map([35, 41],
               tiles='stamentoner',
               zoom_start=6)


hm = HeatMapWithTime(data=list(data.values()),
                     index=list(data.keys()), 
                     radius=10,
                     auto_play=True,
                     max_opacity=0.3)
hm.add_to(m)
m

and you get:

enter image description here