如何在 python 中使用 plotly 为自定义分区统计图创建滑块?

How create a slider for a custom chorpleth map using plotly in python?

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

我正在使用 python3,但我无法在 internet.all 中找到答案,其中 internet.all 使用了 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,
                  )

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

像这样编辑步骤部分:

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

其他部分相同:))