Help with checklist callback

Hello

I would appreciate guidance for the code below.
My goal is to update the linear graph once users select Animal and Country.

Preview of the dataset:

Code:

app.layout = html.Div([
    
    html.H1("Methane Emissions from the Enteric Fermentation", style={"color":"white","backgroundColor":"green","text-align": "center"}),
    html.H2("Irish AgriBusiness and Top Countries Producers", style={"color":"white","backgroundColor":"green","text-align": "center"}),
    
    html.Br(),
    
    dcc.Checklist(
        id="animal_checklist",
        options=[{"label":x,"value":x} for x in all_animals],
        value="Cattle, dairy",
        labelStyle={"display":"inline=block"}
    ), 
    html.Br(),
    
    dcc.Checklist(
        id="country_checklist",
        options=[{"label":x,"value":x} for x in all_countries],
        value="Ireland",
        labelStyle={"display":"inline=block"}),
    
    dcc.Graph(id="line-chart",figure={}),    
])            
         
@app.callback(
    Output("line-chart","figure"),
    Input("animal_checklist","value"),
    Input("country_checklist","value"))
    
def update_line_chart(animal_slct,country_slct):
    eff = ef[(ef.Animal==animal_slct)&(ef.Country==country_slct)]
    fig = px.line(eff,x="Year",y="Enteric CH4 Emissions (kt)",color="Animal")
    fig.update_traces(mode="markers+lines",hovertemplate=None)
    fig.update_layout(hovermode="x unified")
    return fig

thanks a mill
Ligia

Hi,

Welcome to the community!

I believe the only point where you need some changes is in how to apply the filters to the dataframe, given that animal_slct and country_slct are lists of values.

You can replace your filtering line by:

eff = ef[(ef.Animal.isin(animal_slct)) & (ef.Country.isin(country_slct))]

Does it help?

Hello

Thank you so much for the help.
It’s working now.

Have a great day.

Ligia

1 Like