【问题标题】:Dynamically change which geodataframe column is shown in a geoplot动态更改地理图中显示的地理数据框列
【发布时间】:2020-08-26 07:00:39
【问题描述】:

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

【问题讨论】:

    标签: python pandas slider interactive geopandas


    【解决方案1】:

    我发现使用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)))
    

    【讨论】:

      【解决方案2】:

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

      from ipywidgets import interact
      
      # plot some GeoDataFrame, e.g. states
      
      @interact(x=states.columns)
      def on_trait_change(x):
          states.plot(x)
      

      【讨论】:

      • 这种工作,但是在添加新集合之前数据不会被删除,所以当我使用交互小部件时,我有几个重叠的点图。知道如何改变数据,而不是仅仅在以前的数据之上绘制?
      • 您可以在问题中包含您的代码吗?如果我们不知道您在做什么,很难诊断您的具体问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-20
      • 1970-01-01
      • 2022-12-29
      • 2017-10-07
      • 1970-01-01
      • 2013-06-03
      • 2012-08-18
      相关资源
      最近更新 更多