I am receiving error message "nutrients_checklist" is not defined (pandas.core.computation.ops.UndefinedVariableError)

EDIT: Before anyone answers this question, I should note that I have (mostly) found an answer.

The pandas dataframe .loc argument enables me to produce a chart tailored to the user’s inputs, comparing their nutritional values to benchmarks relevant to that demographic. I am not using conventional terns here, though, in the code below. Results is the name of the dataframe. Here is the quick and dirty function.

It works but it needs more work.

(I was receiving the error message above because ‘nutrients_checklist’ is not a column name, and I thought I needed to put an item ID in that location).


@app.callback(
    Output('display_barchart', 'figure'),
    Input('gender_radio', 'value'),
    Input('ages_radio', 'value'),
    Input('units_radio', 'value'))

def display_graph(selected_gender, selected_ages, selected_units):

    
    results = pd.read_csv('chart_data011622.csv')
    Genders = results.Genders.unique()
    AgeGroups = results.AgeGroups.unique()
    Nutrients = results.Nutrients.unique()
    Units = results.Units.unique()
    Amounts = results.Amounts.unique()
    Benchmarks = results.Benchmarks.unique()

    data = results.loc[(results['Genders'] == selected_gender) & (results['AgeGroups'] == selected_ages) & (results['Units'] == selected_units)]

    import plotly.graph_objects as go

    fig = go.Figure()
    fig.add_trace(go.Bar(x=data.Nutrients, y=data.Amounts,
                name='Recipe',
                marker_color='rgb(55, 83, 109)'
                ))
    fig.add_trace(go.Bar(x=data.Nutrients, y=data.Benchmarks,
                name='Benchmarks',
                marker_color='rgb(26, 118, 255)'
                ))
    fig.update_layout(
        title='Recipe Nutritional Profile vs. Benchmarks',
        xaxis_tickfont_size=14,
        yaxis=dict(
        # title='?????',
        titlefont_size=16,
        tickfont_size=14,
    ),
    legend=dict(
        x=0,
        y=1.0,
        bgcolor='rgba(255, 255, 255, 0)',
        bordercolor='rgba(255, 255, 255, 0)'
    ),
    barmode='group',
    bargap=0.15, # gap between bars of adjacent location coordinates.
    bargroupgap=0.1 # gap between bars of the same location coordinate.
)
    return fig

if __name__ == '__main__':
    app.run_server(debug=True)

**ORIGINAL QUESTION:**

Hello,

I am really struggling with the endgame here. Now, I just need to produce the interactive charts, tailoring the presentation of the final results to the user's parameters. I have gone ahead and pasted the code below. It only seems like a lot because the dcc.Checklist in question has about 40 nutrients to choose from. 

But it isn't that much code to review.

Thank you for your consideration.

Here is the code:


import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd

external_stylesheets = [‘https://codepen.io/chriddyp/pen/bWLwgP.css’]

app = dash.Dash(name, external_stylesheets=external_stylesheets)

app.layout = html.Div([

dcc.RadioItems(
id=‘genderadio’,
options=[
{‘label’: ‘Males’, ‘value’: ‘Males’},
{‘label’: ‘Females’, ‘value’: ‘Females’},
],
value=‘Males’
),

html.Hr(),

dcc.RadioItems(
id=‘agesradio’,
options=[

    {'label': '< 14', 'value': '< 14'},
    {'label': '14-18', 'value': '14-18'},
    {'label':  '19-30', 'value':  '19-30'},
    {'label': '31-50', 'value': '31-50'},
    {'label': '51+', 'value': '51+'},
    ], value='19-30'
    ),

html.Hr(),

dcc.RadioItems(
id=‘unitsradio’,
options=[

    {'label': 'Micrograms', 'value': 'Micrograms'},
    {'label': 'Milligrams', 'value': 'Milligrams'},
    {'label': 'Grams', 'value':  'Grams'},
    {'label': 'Percentage', 'value': 'Percentage'},
    ], value='Grams'
    ),

html.Hr(),

dcc.Checklist(
id=“nutrients_checklist”,
options=[
{‘label’: ‘Added Sugar’, ‘value’: ‘Added Sugar’},
{‘label’: ‘Beta Carotene’, ‘value’: ‘Beta Carotene’},
{‘label’: ‘Biotin’, ‘value’: ‘Biotin’},
{‘label’: ‘Caffeine’, ‘value’: ‘Caffeine’},
{‘label’: ‘Calcium’, ‘value’: ‘Calcium’},
{‘label’: ‘Calories’, ‘value’: ‘Calories’},
{‘label’: ‘Carbohydrates’, ‘value’: ‘Carbohydrates’},
{‘label’: ‘Chlorine’, ‘value’: ‘Chlorine’},
{‘label’: ‘Cholesterol’, ‘value’: ‘Cholesterol’},
{‘label’: ‘Choline’, ‘value’: ‘Choline’},
{‘label’: ‘Cobalamin (Vitamin B12)’, ‘value’: ‘Cobalamin (Vitamin B12)’},
{‘label’: ‘Copper’, ‘value’: ‘Copper’},
{‘label’: ‘Fat, total’, ‘value’: ‘Total Fat’},
{‘label’: ‘Fiber’, ‘value’: ‘Fiber’},
{‘label’: ‘Folate (Vitamin B9)’, ‘value’: ‘Folate (Vitamin B9)’},
{‘label’: ‘Iron’, ‘value’: ‘Iron’},
{‘label’: ‘Magnesium’, ‘value’: ‘Magnesium’},
{‘label’: ‘Manganese’, ‘value’: ‘Manganese’},
{‘label’: ‘Molybdenum’, ‘value’: ‘Molybdenum’},
{‘label’: ‘Monounsaturated Fats’, ‘value’: ‘Monounsaturated Fats’},
{‘label’: ‘Niacin (Vitamin B3)’, ‘value’: ‘Niacin (Vitamin B3)’},
{‘label’: ‘Omega Six (Linoleic Acid)’, ‘value’: ‘Omega Six (Linoleic Acid)’},
{‘label’: ‘Omega Three (Linoleic Acid)’, ‘value’: ‘Omega Three (Linoleic Acid)’},
{‘label’: ‘Phosphorus’, ‘value’: ‘Phosphorus’},
{‘label’: ‘Polyunsaturated Fats’, ‘value’: ‘Polyunsaturated Fats’},
{‘label’: ‘Potassium’, ‘value’: ‘Potassium’},
{‘label’: ‘Protein’, ‘value’: ‘Protein’},
{‘label’: ‘Pyridoxine (Vitamin B6)’, ‘value’: ‘Pyridoxine (Vitamin B6)’},
{‘label’: ‘Riboflavin (Vitamin B2)’, ‘value’: ‘Riboflavin (Vitamin B2)’},
{‘label’: ‘Saturated Fat’, ‘value’: ‘Saturated Fat’},
{‘label’: ‘Selenium’, ‘value’: ‘Selenium’},
{‘label’: ‘Sodium’, ‘value’: ‘Sodium’},
{‘label’: ‘Sugar, total’, ‘value’: ‘Total Sugar’},
{‘label’: ‘Sugars, alcohol’, ‘value’: ‘Sugars Alcohol’},
{‘label’: ‘Thiamine (Vitamin B1)’, ‘value’: ‘Thiamine (Vitamin B1)’},
{‘label’: ‘Trans Fats’, ‘value’: ‘Trans Fats’},
{‘label’: ‘Vitamin A RAE’, ‘value’: ‘Vitamin A RAE’},
{‘label’: ‘Vitamin C’, ‘value’: ‘Vitamin C’},
{‘label’: ‘Vitamin D’, ‘value’: ‘Vitamin D’},
{‘label’: ‘Vitamin K’, ‘value’: ‘Vitamin K’},
{‘label’: ‘Zinc’, ‘value’: ‘Zinc’}

    ], value=[]

),

dcc.Graph(id='displaybarchart'),

])

@app.callback(
Output(‘displaybarchart’, ‘figure’),
Input(‘genderadio’, ‘value’),
Input(‘agesradio’, ‘value’),
Input(‘unitsradio’, ‘value’),
Input(‘nutrients_checklist’, ‘value’))

def display_graph(selected_gender, selected_ages, selected_units, selected_nutrients):

df = pd.read_csv('chart_data011622.csv')
dff = df
Amounts = dff.Amounts.unique()
Nutrients = dff.Nutrients.unique()
dff = px.data.gapminder().query("genderadio == selected_gender" and "agesradio == selected_ages" and "unitsradio == selected_units" and "nutrients_checklist == selected_nutrients")
['Genders', 'AgeGroups', 'Nutrients', 'Units', 'Benchmarks', 'Amounts']
fig = px.bar(dff, y='Amounts', x='Nutrients', text='pop')
fig.update_traces(texttemplate='%{text:.2s}', textposition='outside')
fig.update_layout(uniformtext_minsize=8, uniformtext_mode='hide')

return fig

if name == ‘main’:
app.run_server(debug=True)


Here is a snippet of the data:

![Capture|581x500](upload://wdjPTZNYE5ECw4KMql3KoTdIvzj.png)