【问题标题】:How create a slider for a custom chorpleth map using plotly in python?如何在 python 中使用 plotly 为自定义等值线图创建滑块?
【发布时间】:2019-06-21 15:02:41
【问题描述】:

我正在使用 plotly、geojso 和 matplotlib 创建一个等值线图。现在我想添加一个滑块。

我正在使用 python3,但我在互联网上找不到答案。所有这些都使用了 plotly 的默认等值线图。

def get_scatter_colors(sm, df):
    grey = 'rgba(128,128,128,1)'
    return ['rgba' + str(sm.to_rgba(m, bytes = True, alpha = 1)) if not np.isnan(m) else grey for m in df]


for age in columns[3:24]:
        age_data = df[age]
        age_data.name = 'province'
        # print(age_data.head())

        df_tmp = age_data.copy()
        df_tmp.index = df_tmp.index.map(match_dict)
        df_tmp = df_tmp[~df_tmp.index.duplicated(keep=False)]

        df_reindexed = df_tmp.reindex(index = provinces_names)

        colormap = 'Blues'
        cmin = df_reindexed.min()
        cmax = df_reindexed.max()

        sm = scalarmappable(colormap, cmin, cmax)
        scatter_colors = get_scatter_colors(sm, df_reindexed)
        colorscale = get_colorscale(sm, df_reindexed, cmin, cmax)
        hover_text = get_hover_text(df_reindexed)

        scatter_color_list.append(scatter_colors)

        tickformat = ""

        data = dict(type='scattermapbox',
                    lat=lats,
                    lon=lons,
                    mode='markers',
                    text=hover_text,
                    marker=dict(size=10,
                                color=scatter_colors,
                                showscale = True,
                                cmin = df_reindexed.min(),
                                cmax = df_reindexed.max(),
                                colorscale = colorscale,
                                colorbar = dict(tickformat = tickformat)
                               ),
                    showlegend=False,
                    hoverinfo='text'
                    )

        data_slider.append(data)

    layers=([dict(sourcetype = 'geojson',
                  source =sources[k],
                  below="",
                  type = 'line',    # the borders
                  line = dict(width = 1),
                  color = 'black',
                  ) for k in range(n_provinces)
              ] +

              # fill_list
            [dict(sourcetype = 'geojson',
                  source =sources[k],
                  below="water",
                  type = 'fill',
                  color = scatter_colors[k],
                  opacity=0.8,
                 ) for k in range(n_provinces)
             ]
            )

    steps = []
    for i in range(len(data_slider)):
        step = dict(method='restyle',
                    args=['visible', [False] * len(data_slider)],
                    label='Age {}' .format(i))
        step['args'][1][i] = True
        steps.append(step)

    sliders = [dict(active=0, steps=steps)]

    layout = dict(title="2016 POPULATION",
                  autosize=False,
                  width=700,
                  height=800,
                  hovermode='closest',
                  # hoverdistance = 30,

                  mapbox=dict(accesstoken=MAPBOX_APIKEY,
                              layers=layers,
                              bearing=0,
                              center=dict(
                                        lat=35.715298,
                                        lon=51.404343),
                              pitch=0,
                              zoom=4.9,
                              style = 'light'),
                  sliders=sliders,
                  )

当我用数据测试这段代码时,我想用幻灯片改变地图的颜色,但地图的颜色是由最新的幻灯片颜色固定的。

【问题讨论】:

    标签: python matplotlib plotly mapbox plotly-python


    【解决方案1】:

    像这样编辑步骤部分:

    visibility = []
    for i in range(len(data_slider)):
        list = [False] * len(data_slider)
        list[i] = True
        visibility.append(list)
    
    
    steps = []
    for i in range(len(data_slider)):
        step = dict(method='update',
                    args=[{'visible': visibility[i]},
                          {'mapbox.layers': layers[i]}],
                    label='Age {}' .format(i),)
        steps.append(step)
    

    并为图层添加功能:

    def get_data_layout(df):
    
        layers = []
        for i in range(len(data_slider)):
    
            scatter_colors = df[i]['marker']['color']
    
            layer=([dict(sourcetype = 'geojson',
                      source =sources[k],
                      below="",
                      type = 'line',
                      line = dict(width = 1),
                      color = 'black',
                      ) for k in range(n_provinces)
                  ] +
    
                [dict(sourcetype = 'geojson',
                      source =sources[k],
                      below="water",
                      type = 'fill',
                      color = scatter_colors[k],
                      opacity=0.8,
                     ) for k in range(n_provinces)]
                 )
    
        layers.append(layer)
    
    return layers
    

    并将布局更改为:

        layout = dict(title="IRAN 2016 POPULATION",
                  autosize=False,
                  width=700,
                  height=800,
                  hovermode='closest',
    
                  mapbox=dict(accesstoken=MAPBOX_APIKEY,
                              bearing=0,
                              center=dict(
                                        lat=35.715298,
                                        lon=51.404343),
                              pitch=0,
                              zoom=4.9,
                              style = 'dark'),
                  sliders=sliders,
                  )
    

    其他部分相同:))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-05
      • 2021-12-22
      • 2015-12-11
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      • 1970-01-01
      相关资源
      最近更新 更多