Change layout depending on user selection in dcc component?

Hi all,

I would like to change the layout of the page depending on some type of user selection, perhaps a dropdown or radio selections. For instance, in the code below, I have five dropdowns, whose options are progressively filtered based on the value selected in the dropdown above it. Here, the filtering begins at the “pest_order” dropdown and ends at the “host_determination” dropdown. Would it be possible to both restructure the layout and the dropdown chain so that “host_determination” appears above “pest_order” and is first in the filtering hierarchy? Could I do this with a dash component, like a dropdown/radio buttons or would it be more feasible to just have a different page for each layout? Thanks.

aphid = pd.read_pickle("./output_files/aphid.pkl")

# define pull down options
pest_order = sorted([i for i in aphid['Pest order'].unique() if i == i])
pest_family = sorted([i for i in aphid['Pest family'].unique() if i == i])
pest_genus = sorted([i for i in aphid['Pest genus'].unique() if i == i])
pest_species = sorted([i for i in aphid['Pest species'].unique() if i == i])

host_determination = sorted([i for i in aphid['Host'].unique() if i == i])

# Define the page layout
app.layout = html.Div(
    [
        dbc.Row(
            [
                # side bar
                dbc.Col(
                    [
                        dbc.Row(
                            [
                                # header
                                html.H2(
                                children = 'Heading',
                                id = "heading",
                                # style = {'textAlign': 'center', 'color': '#FFFFFF', 'margin': '10px'}
                                ),
                                html.Br(),
                                # image
                                html.Img(
                                    src = "assets/image.png",
                                    width = 240,
                                    id = "logo",
                                ),
                            ], id = "dropdown_headings",
                        ),
                        dbc.Row(
                            [        
                                dbc.Col(
                                    [
                                        dbc.Row([
                                            html.Div(
                                                [
                                                    html.Br(),
                                                    html.Label(
                                                        children = "Pest order", 
                                                        className = "menu-title"
                                                    ),
                                                    # indicator dropdown
                                                    dcc.Dropdown(
                                                        pest_order,
                                                        id = "pest_order",
                                                        value = "",
                                                        className = 'dropdown',
                                                        clearable = True
                                                    ),
                                                    html.Br(),
                                                    html.Label(
                                                        children = "Pest family", 
                                                        className = "menu-title"
                                                    ),
                                                    # indicator dropdown
                                                    dcc.Dropdown(
                                                        pest_family,
                                                        id = "pest_family",
                                                        value = "",
                                                        className = 'dropdown',
                                                        clearable = True,
                                                        # multi = True
                                                    ),
                                                    html.Br(),
                                                    html.Label(
                                                        children = "Pest genus", 
                                                        className = "menu-title"
                                                    ),
                                                    # indicator dropdown
                                                    dcc.Dropdown(
                                                        pest_genus,
                                                        id = "pest_genus",
                                                        value = "Leucinodes, 1889551",
                                                        className = 'dropdown',
                                                        clearable = True
                                                    ),
                                                    html.Br(),
                                                    html.Label(
                                                        children = "Pest species", 
                                                        className = "menu-title"
                                                    ),
                                                    # indicator dropdown
                                                    dcc.Dropdown(
                                                        pest_species,
                                                        id = "pest_species",
                                                        value = "",
                                                        className = 'dropdown',
                                                        clearable = True,
                                                        # multi = True
                                                    ),
                                                ]
                                            ),
                                        ])
                                    ], id = "pest_dropdowns",
                                ),    
                                dbc.Col(
                                    [
                                        dbc.Row([
                                            html.Div(
                                                [
                                                    html.Br(),
                                                    html.Label(
                                                        children = "Host Determination",
                                                        className = "menu-title"
                                                    ),
                                                    # indicator dropdown
                                                    dcc.Dropdown(
                                                        host_determination,
                                                        id = "host_determination",
                                                        value = "",
                                                        className = 'dropdown',
                                                        clearable=True,
                                                        # multi = True
                                                    ),
                                                ]
                                            )
                                        ]),
                                        dbc.Row(
                                            [
                                                dbc.Col(
                                                    dbc.Row([
                                                        html.Div(
                                                            [
                                                                html.Br(),
                                                                html.Div(
                                                                children = "Year", 
                                                                className = "menu-title"
                                                                ),
                                                                # year slider
                                                                dcc.Slider(
                                                                min = aphid['Interception Date'].min().year,
                                                                max = aphid['Interception Date'].max().year,
                                                                step = 1,
                                                                value = 1997,
                                                                vertical=True,
                                                                marks = {1916: '1916', 
                                                                        1920: '1920',
                                                                        1930: '1930',
                                                                        1940: '1940', 
                                                                        1950: '1950',
                                                                        1960: '1960',
                                                                        1970: '1970',
                                                                        1980: '1980',
                                                                        1990: '1990',
                                                                        2000: '2000',
                                                                        2010: '2010',
                                                                        2021: '2021',
                                                                },
                                                                #tooltip property shows value on hover
                                                                tooltip={"placement": "bottom"},
                                                                id='year_slider',
                                                                ),
                                                            ]
                                                        ),
                                                    ])
                                                ),
                                                dbc.Col(
                                                    dbc.Row([
                                                        html.Div(
                                                            [
                                                                html.Br(),
                                                                html.Div(
                                                                children = "Month", 
                                                                className = "menu-title"
                                                                ),    
                                                                # month slider
                                                                dcc.Slider(
                                                                min = 1,
                                                                max = 12,
                                                                step = 1,
                                                                value= 7,
                                                                #tooltip property shows value on hover
                                                                tooltip={"placement": "bottom"},
                                                                id='month_slider',
                                                                vertical = True
                                                                ),
                                                            ]
                                                        )
                                                    ])
                                                )
                                            ],id = "time_sliders"
                                        )
                                    ], id = "host_dropdowns",
                                )
                            ], id = "dropdowns",
                        )
                    ], id='left-container',
                ),
                # main body
                dbc.Col(
                    [
                        html.Div(
                            # choropleth container
                            [
                                # choropleth
                                dcc.Graph(
                                    id='choro_plot1',
                                    className = 'choropleth',
                                    config = {"displayModeBar": False},
                                )
                            ], id = 'choro',
                        ), 
                        html.Div(
                            # bar plot container
                            [
                                # bar plot
                                dcc.Graph(
                                    id='bar_plot1',
                                    className = 'bar_plot',
                                    config = {"displayModeBar": False},
                                )
                            ], id = "bar",
                        )
                    ], id = 'right-container'
                )
            ], 
        )
    ]
)

@app.callback(
    Output('pest_family', 'options'),
    Input('pest_order', 'value')
)
def set_pfam_options(selected_pord):
    return [{'label': i, 'value': i} for i in aphid['Pest family'].loc[aphid['Pest order'] == selected_pord].unique() if i == i]

@app.callback(
    Output('pest_genus', 'options'),
    Input('pest_family', 'value')
)
def set_pgen_options(selected_pfam):
    return [{'label': i, 'value': i} for i in aphid['Pest genus'].loc[aphid['Pest family'] == selected_pfam].unique() if i == i]

@app.callback(
    Output('pest_species', 'options'),
    Input('pest_genus', 'value')
)
def set_pspc_options(selected_pgen):
    return [{'label': i, 'value': i} for i in aphid['Pest species'].loc[aphid['Pest genus'] == selected_pgen].unique() if i == i]

@app.callback(
    Output('host_determination', 'options'),
    Input('pest_species', 'value')
)
def set_host_det(selected_pspc):
    return [{'label': i, 'value': i} for i in aphid['Inspected Host cleaned'].loc[aphid['Pest species'] == selected_pspc].unique() if i == i]

@app.callback(
    Output('choro_plot1', 'figure'),
    Output('bar_plot1', 'figure'),
    Input('month_slider', 'value'),
    Input('year_slider', 'value'),
    Input('host_determination', 'value')
)
def update_figure(month, year, pspc, hspc):

    filtered_df = aphis.loc[(aphid'Inspected Host cleaned'].isin([hspc])) & 
                             (aphid['Pest species'].isin([pspc])) &
                             (aphid['Interception Date'].dt.year == year) & 
                             (aphid['Interception Date'].dt.month == month)]

The full code:

# import packages
from dash import Dash, dcc, html
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd
import numpy as np

external_stylesheets = [
    {
        "href": "https://fonts.googleapis.com/css2?"
                "family=Lato:wght@400;700&display=swap",
        "rel": "stylesheet",
    },
]

app = Dash(__name__, external_stylesheets = external_stylesheets)
app.title = "Invasive Species Dashboard"
server = app.server

# load data
aphis = pd.read_pickle("./output_files/aphis_sample.pkl"")

# define pull down options
pest_order = sorted([i for i in aphis['Pest order'].unique() if i == i])
pest_family = sorted([i for i in aphis['Pest family'].unique() if i == i])
pest_genus = sorted([i for i in aphis['Pest genus'].unique() if i == i])
pest_species = sorted([i for i in aphis['Pest species'].unique() if i == i])

host_determination = sorted([i for i in aphis['Inspected Host cleaned'].unique() if i == i])

# Define the page layout
app.layout = html.Div(
    [
        dbc.Row(
            [
                # side bar
                dbc.Col(
                    [
                        dbc.Row(
                            [
                                # header
                                html.H2(
                                children = 'APHIS: Invasive Species Records',
                                id = "heading",
                                # style = {'textAlign': 'center', 'color': '#FFFFFF', 'margin': '10px'}
                                ),
                                html.Br(),
                                # USDA image
                                html.Img(
                                    src = "assets/USDA.png",
                                    width = 240,
                                    id = "logo",
                                ),
                            ], id = "dropdown_headings",
                        ),
                        dbc.Row(
                            [        
                                dbc.Col(
                                    [
                                        dbc.Row([
                                            html.Div(
                                                [
                                                    html.Br(),
                                                    html.Label(
                                                        children = "Pest order", 
                                                        className = "menu-title"
                                                    ),
                                                    # indicator dropdown
                                                    dcc.Dropdown(
                                                        pest_order,
                                                        id = "pest_order",
                                                        value = "Lepidoptera, 797",
                                                        className = 'dropdown',
                                                        clearable = True
                                                    ),
                                                    html.Br(),
                                                    html.Label(
                                                        children = "Pest family", 
                                                        className = "menu-title"
                                                    ),
                                                    # indicator dropdown
                                                    dcc.Dropdown(
                                                        pest_family,
                                                        id = "pest_family",
                                                        value = "Crambidae, 8841",
                                                        className = 'dropdown',
                                                        clearable = True,
                                                        # multi = True
                                                    ),
                                                    html.Br(),
                                                    html.Label(
                                                        children = "Pest genus", 
                                                        className = "menu-title"
                                                    ),
                                                    # indicator dropdown
                                                    dcc.Dropdown(
                                                        pest_genus,
                                                        id = "pest_genus",
                                                        value = "Leucinodes, 1889551",
                                                        className = 'dropdown',
                                                        clearable = True
                                                    ),
                                                    html.Br(),
                                                    html.Label(
                                                        children = "Pest species", 
                                                        className = "menu-title"
                                                    ),
                                                    # indicator dropdown
                                                    dcc.Dropdown(
                                                        pest_species,
                                                        id = "pest_species",
                                                        value = "Leucinodes orbonalis, 1889552",
                                                        className = 'dropdown',
                                                        clearable = True,
                                                        # multi = True
                                                    ),
                                                ]
                                            ),
                                        ])
                                    ], id = "pest_dropdowns",
                                ),    
                                dbc.Col(
                                    [
                                        dbc.Row([
                                            html.Div(
                                                [
                                                    html.Br(),
                                                    html.Label(
                                                        children = "Host Determination",
                                                        className = "menu-title"
                                                    ),
                                                    # indicator dropdown
                                                    dcc.Dropdown(
                                                        host_determination,
                                                        id = "host_determination",
                                                        value = "Solanum melongena",
                                                        className = 'dropdown',
                                                        clearable=True,
                                                        # multi = True
                                                    ),
                                                ]
                                            )
                                        ]),
                                        dbc.Row(
                                            [
                                                dbc.Col(
                                                    dbc.Row([
                                                        html.Div(
                                                            [
                                                                html.Br(),
                                                                html.Div(
                                                                children = "Year", 
                                                                className = "menu-title"
                                                                ),
                                                                # year slider
                                                                dcc.Slider(
                                                                min = aphis['Interception Date'].min().year,
                                                                max = aphis['Interception Date'].max().year,
                                                                step = 1,
                                                                value = 1997,
                                                                vertical=True,
                                                                marks = {1916: '1916', 
                                                                        1920: '1920',
                                                                        1930: '1930',
                                                                        1940: '1940', 
                                                                        1950: '1950',
                                                                        1960: '1960',
                                                                        1970: '1970',
                                                                        1980: '1980',
                                                                        1990: '1990',
                                                                        2000: '2000',
                                                                        2010: '2010',
                                                                        2021: '2021',
                                                                },
                                                                #tooltip property shows value on hover
                                                                tooltip={"placement": "bottom"},
                                                                id='year_slider',
                                                                ),
                                                            ]
                                                        ),
                                                    ])
                                                ),
                                                dbc.Col(
                                                    dbc.Row([
                                                        html.Div(
                                                            [
                                                                html.Br(),
                                                                html.Div(
                                                                children = "Month", 
                                                                className = "menu-title"
                                                                ),    
                                                                # month slider
                                                                dcc.Slider(
                                                                min = 1,
                                                                max = 12,
                                                                step = 1,
                                                                value= 7,
                                                                #tooltip property shows value on hover
                                                                tooltip={"placement": "bottom"},
                                                                id='month_slider',
                                                                vertical = True
                                                                ),
                                                            ]
                                                        )
                                                    ])
                                                )
                                            ],id = "time_sliders"
                                        )
                                    ], id = "host_dropdowns",
                                )
                            ], id = "dropdowns",
                        )
                    ], id='left-container',
                ),
                # main body
                dbc.Col(
                    [
                        html.Div(
                            # choropleth container
                            [
                                # choropleth
                                dcc.Graph(
                                    id='choro_plot1',
                                    className = 'choropleth',
                                    config = {"displayModeBar": False},
                                )
                            ], id = 'choro',
                        ), 
                        html.Div(
                            # bar plot container
                            [
                                # bar plot
                                dcc.Graph(
                                    id='bar_plot1',
                                    className = 'bar_plot',
                                    config = {"displayModeBar": False},
                                )
                            ], id = "bar",
                        )
                    ], id = 'right-container'
                )
            ], 
        )
    ]
)

# define callbacks - inputs include pest and host taxa

@app.callback(
    Output('pest_family', 'options'),
    Input('pest_order', 'value')
)
def set_pfam_options(selected_pord):
    return [{'label': i, 'value': i} for i in aphis['Pest family'].loc[aphis['Pest order'] == selected_pord].unique() if i == i]

@app.callback(
    Output('pest_genus', 'options'),
    Input('pest_family', 'value')
)
def set_pgen_options(selected_pfam):
    return [{'label': i, 'value': i} for i in aphis['Pest genus'].loc[aphis['Pest family'] == selected_pfam].unique() if i == i]

@app.callback(
    Output('pest_species', 'options'),
    Input('pest_genus', 'value')
)
def set_pspc_options(selected_pgen):
    return [{'label': i, 'value': i} for i in aphis['Pest species'].loc[aphis['Pest genus'] == selected_pgen].unique() if i == i]

@app.callback(
    Output('host_determination', 'options'),
    Input('pest_species', 'value')
)
def set_host_det(selected_pspc):
    return [{'label': i, 'value': i} for i in aphis['Inspected Host cleaned'].loc[aphis['Pest species'] == selected_pspc].unique() if i == i]

@app.callback(
    Output('choro_plot1', 'figure'),
    Output('bar_plot1', 'figure'),
    Input('month_slider', 'value'),
    Input('year_slider', 'value'),
    Input('pest_species', 'value'),
    Input('host_determination', 'value')

)
def update_figure(month, year, pspc, hspc):

    filtered_df = aphis.loc[(aphis['Inspected Host cleaned'].isin([hspc])) & 
                             (aphis['Pest species'].isin([pspc])) &
                             (aphis['Interception Date'].dt.year == year) & 
                             (aphis['Interception Date'].dt.month == month)]
    
    # aggregate instances by pspc
    aggregate_df = filtered_df.groupby(['iso3']).sum()

    # define graph structures
    # fig1 = choropleth
    fig1 = go.Figure(
        data = [
            go.Choropleth(
                locations = aggregate_df.index,
                # z is the indicator value for each country in the selected year
                z = aggregate_df['Total Stages'],
            )
        ]    
    )       
    # update_layout sets graph size, font size, background color, etc. 
    fig1.update_layout(
        # paper_bgcolor is the color of the background behind the plots    
        paper_bgcolor = '#BAD0E3', 
        font_size = 14,
        # plot bg_color is the color of the background behind the text, legend, etc.
        plot_bgcolor='#E8EFF6',
        height = 900,
        title_text = "Number of Pests from Each Origin Site"
    )

    # update_traces sets plot element colors, hover text template
    fig1.update_traces(
        colorscale = 'sunsetdark',
        # hovertemplate = ('%{z:.2f}% <extra>%{text}</extra>'), text = percent,
        colorbar_title_text = "<b># of Pests</b>",
    )

    # fig2 = pie plot
    fig2 = px.pie(
        aggregate_df,
        # x-axis is value of indicator
        names = aggregate_df.index.get_level_values(0),
        # y-axis is the income group
        values = 'Total Stages',
        color = aggregate_df.index.get_level_values(0),
    )
    # update_layout sets graph size, font size, background color, etc.
    fig2.update_layout(
        paper_bgcolor = '#BAD0E3', 
        font_size = 14,
        plot_bgcolor='#E8EFF6',
        legend_title = "<b>Origin Site</b>",
        title_text = "Percentage of Pests from Each Origin Site",
        height = 900,
    )
    # update_traces sets plots to show all country points, creates custom
    # hovertext appearance, and sets jitter (vertical dispersion of points)
    fig2.update_traces(
        # hovertemplate = "%{x:.2f}%<extra>%{customdata[0]}</extra>",
    )
    return fig1, fig2


# Run the app on localhost:8050
if __name__ == '__main__':
    app.run_server(debug=True)

I think you can use value of each dropdown to return options for each dropdown. So you can choose host_determination to return pest_family, pest_species… or or vice versa. And I think for the you should change your code to make aggregate_df to aggregate_df = pd.pivot_table(filtered_df,('Total Stages'),index=['iso3'],aggfunc=np.sum). And because you are not setting your dropdown as multi choice so in you callback you can not use isin.

Please check code below:

# import packages
from dash import Dash, dcc, html
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd
import numpy as np


app = Dash(__name__, external_stylesheets=[dbc.themes.LUMEN])
app.title = "Invasive Species Dashboard"
server = app.server

# load data
aphis = pd.read_pickle("aphis_sample.pkl")

# define pull down options
pest_order = sorted([i for i in aphis['Pest order'].unique() if i == i])
pest_family = sorted([i for i in aphis['Pest family'].unique() if i == i])
pest_genus = sorted([i for i in aphis['Pest genus'].unique() if i == i])
pest_species = sorted([i for i in aphis['Pest species'].unique() if i == i])
host_determination = sorted([i for i in aphis['Inspected Host cleaned'].unique() if i == i])

# Define the page layout
app.layout = html.Div(
    [
        dbc.Row(
            [
                # side bar
                dbc.Col(
                    [
                        dbc.Row(
                            [
                                # header
                                html.H2(
                                children = 'APHIS: Invasive Species Records',
                                id = "heading",
                                # style = {'textAlign': 'center', 'color': '#FFFFFF', 'margin': '10px'}
                                ),
                                html.Br(),
                                # USDA image
                                html.Img(
                                    src = "assets/USDA.png",
                                    width = 240,
                                    id = "logo",
                                ),
                            ], id = "dropdown_headings",
                        ),
                        dbc.Row(
                            [        
                                dbc.Col(
                                    [
                                        dbc.Row([
                                            html.Div(
                                                [
                                                    html.Br(),
                                                    html.Label(
                                                        children = "Pest order", 
                                                        className = "menu-title"
                                                    ),
                                                    # indicator dropdown
                                                    dcc.Dropdown(
                                                        pest_order,
                                                        id = "pest_order",
                                                        value = "Lepidoptera, 797",
                                                        className = 'dropdown',
                                                        clearable = True
                                                    ),
                                                    html.Br(),
                                                    html.Label(
                                                        children = "Pest family", 
                                                        className = "menu-title"
                                                    ),
                                                    # indicator dropdown
                                                    dcc.Dropdown(
                                                        pest_family,
                                                        id = "pest_family",
                                                        value = [],
                                                        className = 'dropdown',
                                                        clearable = True,
                                                        # multi = True
                                                    ),
                                                    html.Br(),
                                                    html.Label(
                                                        children = "Pest genus", 
                                                        className = "menu-title"
                                                    ),
                                                    # indicator dropdown
                                                    dcc.Dropdown(
                                                        pest_genus,
                                                        id = "pest_genus",
                                                        value = [],
                                                        className = 'dropdown',
                                                        clearable = True
                                                    ),
                                                    html.Br(),
                                                    html.Label(
                                                        children = "Pest species", 
                                                        className = "menu-title"
                                                    ),
                                                    # indicator dropdown
                                                    dcc.Dropdown(
                                                        pest_species,
                                                        id = "pest_species",
                                                        value = [],
                                                        className = 'dropdown',
                                                        clearable = True,
                                                        # multi = True
                                                    ),
                                                ]
                                            ),
                                        ])
                                    ], id = "pest_dropdowns",
                                ),    
                                dbc.Col(
                                    [
                                        dbc.Row([
                                            html.Div(
                                                [
                                                    html.Br(),
                                                    html.Label(
                                                        children = "Host Determination",
                                                        className = "menu-title"
                                                    ),
                                                    # indicator dropdown
                                                    dcc.Dropdown(
                                                        host_determination,
                                                        id = "host_determination",
                                                        value = [],
                                                        className = 'dropdown',
                                                        clearable=True,
                                                        # multi = True
                                                    ),
                                                ]
                                            )
                                        ]),
                                        dbc.Row(
                                            [
                                                dbc.Col(
                                                    dbc.Row([
                                                        html.Div(
                                                            [
                                                                html.Br(),
                                                                html.Div(
                                                                children = "Year", 
                                                                className = "menu-title"
                                                                ),
                                                                # year slider
                                                                dcc.Slider(
                                                                min = aphis['Interception Date'].min().year,
                                                                max = aphis['Interception Date'].max().year,
                                                                step = 1,
                                                                value = 1997,
                                                                vertical=True,
                                                                marks = {1916: '1916', 
                                                                        1920: '1920',
                                                                        1930: '1930',
                                                                        1940: '1940', 
                                                                        1950: '1950',
                                                                        1960: '1960',
                                                                        1970: '1970',
                                                                        1980: '1980',
                                                                        1990: '1990',
                                                                        2000: '2000',
                                                                        2010: '2010',
                                                                        2021: '2021',
                                                                },
                                                                #tooltip property shows value on hover
                                                                tooltip={"placement": "bottom"},
                                                                id='year_slider',
                                                                ),
                                                            ]
                                                        ),
                                                    ])
                                                ),
                                                dbc.Col(
                                                    dbc.Row([
                                                        html.Div(
                                                            [
                                                                html.Br(),
                                                                html.Div(
                                                                children = "Month", 
                                                                className = "menu-title"
                                                                ),    
                                                                # month slider
                                                                dcc.Slider(
                                                                min = 1,
                                                                max = 12,
                                                                step = 1,
                                                                value= 7,
                                                                #tooltip property shows value on hover
                                                                tooltip={"placement": "bottom"},
                                                                id='month_slider',
                                                                vertical = True
                                                                ),
                                                            ]
                                                        )
                                                    ])
                                                )
                                            ],id = "time_sliders"
                                        )
                                    ], id = "host_dropdowns",
                                )
                            ], id = "dropdowns",
                        )
                    ], id='left-container',
                ),
                # main body
                dbc.Col(
                    [
                        html.Div(
                            # choropleth container
                            [
                                # choropleth
                                dcc.Graph(
                                    id='choro_plot1',
                                    className = 'choropleth',
                                    config = {"displayModeBar": False},
                                )
                            ], id = 'choro',
                        ), 
                        html.Div(
                            # bar plot container
                            [
                                # bar plot
                                dcc.Graph(
                                    id='bar_plot1',
                                    className = 'bar_plot',
                                    config = {"displayModeBar": False},
                                )
                            ], id = "bar",
                        )
                    ], id = 'right-container'
                )
            ], 
        )
    ]
)

# define callbacks - inputs include pest and host taxa


@app.callback(
    Output('pest_family', 'options'),
    [Input('pest_order', 'value'),
    Input('pest_genus', 'value'),
    Input('pest_species', 'value'),
    Input('host_determination', 'value')]
)
def set_pfam_options(selected_pord,selected_pgen,selected_pspc,selected_hspc):
    aphis_1 = aphis.copy()
    if selected_pord:
        aphis_1 = aphis_1[aphis_1['Pest order'] == selected_pord]
    if selected_pgen:
        aphis_1 = aphis_1[aphis_1['Pest genus'] == selected_pgen]
    if selected_pspc:
        aphis_1 = aphis_1[aphis_1['Pest species'] == selected_pspc]
    if selected_hspc:
        aphis_1 = aphis_1[aphis_1['Inspected Host cleaned'] == selected_hspc]        
    return [{'label': i, 'value': i} for i in aphis_1['Pest family'].unique()]

@app.callback(
    Output('pest_genus', 'options'),
    [Input('pest_order', 'value'),
    Input('pest_family', 'value'),
    Input('pest_species', 'value'),
    Input('host_determination', 'value')]
)
def set_pfam_options(selected_pord,selected_pfam,selected_pspc,selected_hspc):
    aphis_1 = aphis.copy()
    if selected_pord:
        aphis_1 = aphis_1[aphis_1['Pest order'] == selected_pord]
    if selected_pfam:
        aphis_1 = aphis_1[aphis_1['Pest family'] == selected_pfam]
    if selected_pspc:
        aphis_1 = aphis_1[aphis_1['Pest species'] == selected_pspc]
    if selected_hspc:
        aphis_1 = aphis_1[aphis_1['Inspected Host cleaned'] == selected_hspc]        
    return [{'label': i, 'value': i} for i in aphis_1['Pest genus'].unique()]

@app.callback(
    Output('pest_species', 'options'),
    [Input('pest_order', 'value'),
    Input('pest_family', 'value'),
    Input('pest_genus', 'value'),
    Input('host_determination', 'value')]
)
def set_pfam_options(selected_pord,selected_pfam,selected_pgen,selected_hspc):
    aphis_1 = aphis.copy()
    if selected_pord:
        aphis_1 = aphis_1[aphis_1['Pest order'] == selected_pord]
    if selected_pfam:
        aphis_1 = aphis_1[aphis_1['Pest family'] == selected_pfam]
    if selected_pgen:
        aphis_1 = aphis_1[aphis_1['Pest genus'] == selected_pgen]
    if selected_hspc:
        aphis_1 = aphis_1[aphis_1['Inspected Host cleaned'] == selected_hspc]        
    return [{'label': i, 'value': i} for i in aphis_1['Pest species'].unique()]

@app.callback(
    Output('host_determination', 'options'),
    [Input('pest_order', 'value'),
    Input('pest_family', 'value'),
    Input('pest_genus', 'value'),
    Input('pest_species', 'value')]
)
def set_pfam_options(selected_pord,selected_pfam,selected_pgen,selected_pspc):
    aphis_1 = aphis.copy()
    if selected_pord:
        aphis_1 = aphis_1[aphis_1['Pest order'] == selected_pord]
    if selected_pfam:
        aphis_1 = aphis_1[aphis_1['Pest family'] == selected_pfam]
    if selected_pgen:
        aphis_1 = aphis_1[aphis_1['Pest genus'] == selected_pgen]
    if selected_pspc:
        aphis_1 = aphis_1[aphis_1['Pest species'] == selected_pspc]       
    return [{'label': i, 'value': i} for i in aphis_1.sort_values('Inspected Host cleaned')['Inspected Host cleaned'].unique()]


@app.callback(
    Output('choro_plot1', 'figure'),
    Output('bar_plot1', 'figure'),
    Input('month_slider', 'value'),
    Input('year_slider', 'value'),
    Input('pest_species', 'value'),
    Input('host_determination', 'value')

)
def update_figure(month, year, pspc, hspc):
    filtered_df = aphis[(aphis['Inspected Host cleaned']==hspc) & 
                             (aphis['Pest species']==pspc) &
                             (aphis['Interception Date'].dt.year == year) & 
                             (aphis['Interception Date'].dt.month == month)]
    
    # aggregate instances by pspc
    aggregate_df = pd.pivot_table(filtered_df,('Total Stages'),index=['iso3'],aggfunc=np.sum)
    print(aggregate_df)
    # define graph structures
    # fig1 = choropleth
    fig1 = go.Figure(
        data = [
            go.Choropleth(
                locations = aggregate_df.index,
                # z is the indicator value for each country in the selected year
                z = aggregate_df['Total Stages'],
            )
        ]    
    )       
    # update_layout sets graph size, font size, background color, etc. 
    fig1.update_layout(
        # paper_bgcolor is the color of the background behind the plots    
        paper_bgcolor = '#BAD0E3', 
        font_size = 14,
        # plot bg_color is the color of the background behind the text, legend, etc.
        plot_bgcolor='#E8EFF6',
        height = 900,
        title_text = "Number of Pests from Each Origin Site"
    )

    # update_traces sets plot element colors, hover text template
    fig1.update_traces(
        colorscale = 'sunsetdark',
        # hovertemplate = ('%{z:.2f}% <extra>%{text}</extra>'), text = percent,
        colorbar_title_text = "<b># of Pests</b>",
    )

    # fig2 = pie plot
    fig2 = px.pie(
        aggregate_df,
        # x-axis is value of indicator
        names = aggregate_df.index.get_level_values(0),
        # y-axis is the income group
        values = 'Total Stages',
        color = aggregate_df.index.get_level_values(0),
    )
    # update_layout sets graph size, font size, background color, etc.
    fig2.update_layout(
        paper_bgcolor = '#BAD0E3', 
        font_size = 14,
        plot_bgcolor='#E8EFF6',
        legend_title = "<b>Origin Site</b>",
        title_text = "Percentage of Pests from Each Origin Site",
        height = 900,
    )
    # update_traces sets plots to show all country points, creates custom
    # hovertext appearance, and sets jitter (vertical dispersion of points)
    fig2.update_traces(
        # hovertemplate = "%{x:.2f}%<extra>%{customdata[0]}</extra>",
    )
    return fig1, fig2


# Run the app on localhost:8050
if __name__ == '__main__':
    app.run_server(debug=False, port=8058)

1 Like

Thanks for the suggestion @hoatran. This was not what I had in mind but it works (and is probably a better solution).