Search code examples
pythonheatmapfoliumipywidgetsipyvuetify

Getting ipywidgets to update a folium heatmap?


Beginner python user, having some success with heatmaps using Folium. I am experimenting with using the Global Terrorism Database as a source for some visualizations but I really wanted to use ipywidgets to select a specific terrorist group from a list to update my heatmap. I've already constructed a heatmap for ISIS, created an ipyvuetify button containing the groups I want to compare, but am having trouble figuring out the function and widgets.link syntax. I'd really appreciate some help because there don't seem to be any good guides (for my skill level) on how to do what I'm trying to do here.

import ipyvuetify as v
import ipywidgets as widgets
import folium
from folium import plugins
from folium.plugins import HeatMap as hm

map = folium.Map(location = [25,15], tiles = "cartodbdark_matter", zoom_start = 2)
selected = gtd.loc[gtd['Group'] == 'Islamic State of Iraq and the Levant (ISIL)'] 
coords = selected[['Latitude','Longitude']]
hm(coords).add_to(map)

terrorists = [
    'Taliban', 
    'Shining Path (SL)', 
    'Islamic State of Iraq and the Levant (ISIL)', 
    'Farabundo Marti National Liberation Front (FMLN)', 
    'Al-Shabaab', 
    'Irish Republican Army (IRA)', 
    'Revolutionary Armed Forces of Colombia (FARC)', 
    'New Peoples Army (NPA)', 
    'Kurdistan Workers Party (PKK)', 
    'Boko Haram']

# This is where things go off the rails for me, not exactly sure how to arrange this function
def update(x):
    if widget_terrorist_selector.selected is not None:
        xmin, xmax = widget_terrorist_selector.selected
widget_terrorist_selector.observe(update,'widget_terrorist_selector')

# The selector here works but I can't figure out how to link it to my map so that it pushes a new set of heatmap coordinates
widget_terrorist_selector = v.Select(label='Choose Option', items=terrorists, v_model=terrorists[0])
widget_terrorist_selector

# This bit keeps throwing a "TypeError: Each object must be HasTraits, not <class 'pandas.core.frame.DataFrame'>"
widgets.link((widget_terrorist_selector,'v_model'),(selected, 'Group'))

Thanks in advance!


Solution

  • widgets.link is used for keeping two ipywidgets in sync. I'm not sure that's what you're trying to achieve here, it can probably be achieved with plain old observe.

    I think in your update function you need to make the necessary change to your map, something like

    def update(x):
        new_choice = widget_terrorist_selector.selected
        selected = gtd.loc[gtd['Group'] == new_choice] 
        coords = selected[['Latitude','Longitude']]
        hm(coords).add_to(map)