Dynamically change which geodataframe column is shown in a geoplot

Viewed 235

I am wondering if it is possible to dynamically change which column from a GeoPandas GeoDataFrame is shown in a geoplot. For example, if I have a GeoDataFrame with different columns representing Global data on different dates, how could I have an interactive slider which allows me to show data for a specific date in a geoplot? I see matplotlib.widgets has a slider, but I cannot figure out how to apply that to a GeoDataFrame and geoplot.

2 Answers

The ipywidgets.interact decorator is useful for quickly turning a function into an interactive widget

from ipywidgets import interact

# plot some GeoDataFrame, e.g. states

@interact(x=states.columns)
def on_trait_change(x):
    states.plot(x)

ineractive state plot

I found it convenient to use interact to set up interactive widgets in combination with a function modifying the data/plot based on the parameters selected in the widgets. For demonstration I implemented a slider widget and a drop down menu widget. Dependent on your use case, you might need only one.

# import relevant modules
import geopandas as gpd
import ipywidgets
import numpy as np

# load a sample data set
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))

# set seed for reproducability
np.random.seed(0)
# generate 3 artifical columns: random proportions of the gdp_md_est column (logarithmized)
for date in ['date1', 'date2', 'date3']:
    world[date] = np.log(world.gdp_md_est*np.random.rand(len(world)))

# function defining what should happen if the user selects a specific date and continent
def on_trait_change(date, continent):
    df=world[world['continent'] == continent] # sub set data
    df.plot(f'date{date}')  # to plot for example column'date2'

# generating the interactive plot with two widgets
interact(on_trait_change, date=ipywidgets.widgets.IntSlider(min=1, max=3, value=2), continent=list(set(world.continent)))
Related