How to modify points drawn on map using a dropdown menu?


Here’s how I create the map and add a dropdown menu with option1 and option2.

import pandas as pd
import plotly.express as px

us_cities = pd.read_csv(
    'https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv'
)


fig = px.scatter_mapbox(
    us_cities,
    lat='lat',
    lon='lon',
    hover_name='City',
    hover_data=['State', 'Population'],
    color_discrete_sequence=['fuchsia'],
    zoom=3,
)
fig.update_layout(mapbox_style='open-street-map')
fig.update_layout(margin={'r': 0, 't': 0, 'l': 0, 'b': 0})
fig.update_layout(
    updatemenus=[
        dict(
            buttons=list(
                [
                    {
                        'args': ['type', 'option1'],
                        'label': 'Option 1',
                        'method': 'restyle',
                    },
                    {
                        'args': ['type', 'option2'],
                        'label': 'Option 2',
                        'method': 'restyle',
                    },
                ]
            ),
            direction='down',
            x=0.075,
            xanchor='right',
            yanchor='bottom',
        ),
    ]
)
fig.show()

I want to have all states listed in the dropdown menu, with an option to plot all data points of all states when set to all or option1 or whatever the name is, or alternatively, to select a state and only the data points belonging to the state to be shown and the rest are deleted.

Hi @emadboctor, and welcome to the forum
In order to be able to do what you want you’ll need to use Dash

# Import Dash and Dash Bootstrap Components
import dash
import dash_daq as daq
from dash import Input, Output, dcc, html, dash_table, callback
import dash_bootstrap_components as dbc

# Start the App Here 

app = dash.Dash(__name__,title='CONFIRM - FÁTIMA 2022',suppress_callback_exceptions=True,update_title=None,
	meta_tags=[{"name": "viewport", "content": "width=device-width, initial-scale=1"}],
	)


app.css.config.serve_locally = False 
app.scripts.config.serve_locally = False 


server = app.server

# Get dataframe

us_cities = pd.read_csv(
    'https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv'
)

app.layout = html.Div(
	[
		html.Hr(style={'margin_bottom':'35px'}),
		dbc.Row(
			[
				dbc.Col(
					[
						html.H6("Pick State ",style={'margin-left':'20px'}),
						dbc.Col(
		                                     dcc.Dropdown(
		                                     id='dropdown_state',
		                                    options=[{'label': i, 'value': i} for i in us_cities['State'].unique()],
		                                    placeholder='Select',
		                                    value="Alabama",
		                                   className="dropdown",
		                                   multi=False
		                    ),
		                 ),
					],
					xs=12, sm=12, md=3, lg=3, xl=2,
				),

# Create a new row where you put your map 
dbc.Row(
       [
         dbc.Col(dcc.Graph(id='my_map'),)
      ],
)

# Create a callback 

@app.callback(
    Output(component_id="my_map", component_property="figure"),
    Input(component_id="dropdown_state", component_property="value"),
    #prevent_initial_call=True
)

# Define what happens when callback is triggered 
def update_card(value):
       us_cities = pd.read_csv( 'https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv')
       us_cities_filtered = us_cities[us_cities['State']== value]
       fig = px.scatter_mapbox(
    us_cities_filtered,
    lat='lat',
    lon='lon',
    hover_name='City',
    hover_data=['State', 'Population'],
    color_discrete_sequence=['fuchsia'],
    zoom=3,
)
fig.update_layout(mapbox_style='open-street-map')
fig.update_layout(margin={'r': 0, 't': 0, 'l': 0, 'b': 0})
fig.update_layout(
    updatemenus=[
        dict(
            buttons=list(
                [
                    {
                        'args': ['type', 'option1'],
                        'label': 'Option 1',
                        'method': 'restyle',
                    },
                    {
                        'args': ['type', 'option2'],
                        'label': 'Option 2',
                        'method': 'restyle',
                    },
                ]
            ),
            direction='down',
            x=0.075,
            xanchor='right',
            yanchor='bottom',
        ),
    ]
)

return fig

if __name__ == "__main__":
	app.run_server(host='0.0.0.0', debug=True)
       
      

Sorry for the indentation that is a bit screwed up, but I hope this helps.

2 Likes

thanks, that’s very helpful

1 Like

You’re most welcome!