How to make a choropleth map with a slider using Plotly?

前端 未结 1 749
情话喂你
情话喂你 2021-01-01 08:17

I\'m recreating the example choropleth and trying to add a slider that, when dragged, would change from year to year. Another user asked a similar question but they didn\'t

相关标签:
1条回答
  • 2021-01-01 09:10

    The code below is virtually a trimmed down version of the choropleth example for Python and the sliders code.

    Randomized data is created based on the first data and each slider entry shows a different part of the data list.

    import pandas as pd
    import plotly
    import numpy as np
    
    plotly.offline.init_notebook_mode()
    df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv')
    
    data = [dict(type='choropleth',
                 locations = df['code'].astype(str),
                 z=df['total exports'].astype(float),
                 locationmode='USA-states')]
    
    # let's create some additional, random data
    for i in range(5):
        data.append(data[0].copy())
        data[-1]['z'] = data[0]['z'] * np.random.rand(*data[0]['z'].shape)
    
    # let's create the steps for the slider
    steps = []
    for i in range(len(data)):
        step = dict(method='restyle',
                    args=['visible', [False] * len(data)],
                    label='Year {}'.format(i + 1980))
        step['args'][1][i] = True
        steps.append(step)
    
    sliders = [dict(active=0,
                    pad={"t": 1},
                    steps=steps)]    
    layout = dict(geo=dict(scope='usa',
                           projection={'type': 'albers usa'}),
                  sliders=sliders)
    
    fig = dict(data=data, 
               layout=layout)
    plotly.offline.iplot(fig)
    

    0 讨论(0)
提交回复
热议问题