Adding drop down menu to Choropleth map to select each state and generate new graph type

后端 未结 1 1200
北恋
北恋 2021-01-15 02:45

I\'ve created a Choropleth map and I want to know if it\'s possible to add a drop down with each state. When you select the drop down the graph changes to a line graph of th

相关标签:
1条回答
  • 2021-01-15 03:32

    You can get the desired functionality with Plotly online but all the data needs to be loaded when the first graph is rendered. Perhaps have a look at Plotly's Dash which enabled dynamic loading of data.

    In order to get the dropmenu which shows traces you could do the following:

    • First create map, then add a scatter plot for each country but only show the map by setting the visible attribute.
    • Create a drop down menu which shows the scatter plot for the selected country (by passing an array of Booleans to visible)
    • Add a menu entry to show the map again

    import pandas as pd
    import plotly
    
    plotly.offline.init_notebook_mode()
    df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv')
    
    # create the initial map
    data = [dict(type='choropleth',
                 locations = df['code'].astype(str),
                 z=df['total exports'].astype(float),
                 locationmode='USA-states', 
                 visible=True)]
    
    layout = dict(geo=dict(scope='usa',
                           projection={'type': 'albers usa'}))
    
    # create the empty dropdown menu
    updatemenus = list([dict(buttons=list()), 
                        dict(direction='down',
                             showactive=True)])
    
    total_codes = len(df.code.unique()) + 1
    
    for s, state in enumerate(df.code.unique()):
        # add a trace for each state
        data.append(dict(type='scatter',
                         x=[i for i in range(1980, 2016)],
                         y=[i + random.random() * 100 for i in range(1980, 2016)],
                         visible=False))
    
        # add each state to the dropdown    
        visible_traces = [False] * total_codes
        visible_traces[s + 1] = True
        updatemenus[0]['buttons'].append(dict(args=[{'visible': visible_traces}],
                                              label=state,
                                              method='update'))
    
    # add a dropdown entry to reset the map    
    updatemenus[0]['buttons'].append(dict(args=[{'visible': [True] + [False] *  (total_codes - 1)}],
                                          label='Map',
                                          method='update'))
    layout['updatemenus'] = updatemenus
    
    fig = dict(data=data, 
               layout=layout)
    plotly.offline.iplot(fig)
    
    0 讨论(0)
提交回复
热议问题