如何在python中使用plotly为自定义的chorpleth贴图创建滑块?

时间:2019-06-21 15:02:41

标签: python matplotlib plotly mapbox plotly-python

我正在使用plotly,geojso和matplotlib创建一个Choropleth贴图。现在我想添加一个滑块。

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

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

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

1 个答案:

答案 0 :(得分:0)

像这样编辑步骤部分:

def change():
    global f      # f is global 
    del f         # deleted
    f = 500       # recreated as GLOBAL variable
    g = 5000      # this is LOCAL ==>> can't access outside the scope

change()
print(f)  # f was deleted, then recreated in the global scope
print(g)  # raises NameError: name 'g' is not defined

并为图层添加功能:

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

其他部分相同:))