动态更改地理地块中显示的geodataframe列

2024-09-28 19:25:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道是否有可能动态更改GeoPandas GeoDataFrame中显示在geoplot中的列。例如,如果我有一个GeoDataFrame,其中的不同列表示不同日期的全局数据,那么我怎么能有一个交互式滑块,允许我在地理地块中显示特定日期的数据?我看到matplotlib.widgets有一个滑块,但我不知道如何将其应用于GeoDataFrame和geoplot


Tags: 数据matplotlib动态widgets全局地理滑块geopandas
2条回答

我发现使用interact来设置交互式小部件,并结合一个基于小部件中选择的参数修改数据/绘图的函数是很方便的。为了演示,我实现了一个滑块小部件和一个下拉菜单小部件。根据您的用例,您可能只需要一个

# 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)))

ipywidgets.interact装饰器对于快速将函数转换为交互式小部件非常有用

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

相关问题 更多 >