Javier Parada
Javier Parada

Reputation: 41

HeatMapWithTime Plugin in Folium

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

Upvotes: 3

Views: 4240

Answers (1)

sentence
sentence

Reputation: 8933

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

Upvotes: 6

Related Questions