How to create a callback when selecting a checkbox in a AG Grid with Dash

I am confused with how to access the Ticker field of checked ag grid rows. I successfully created a callback to update my graph previously when I just had a dropdown selector, but I would like to use an ag grid because it has more features. So I messed up some of the update graph code. Sorry for the long post segment of code but I can not seem to figure this out and would very much appreciate help. Thanks.

#options for commodities
# Fetch data for FRED series Ids:
selected_series_id = {
    "CONSTRUCTION4GVMT_df": get_fred_data('WPUFD432'),
    "ELECRICALCONTRACTORSNONRESBUILDINGWORK_df": get_fred_data('PCU23821X23821X'),
    "MULTIFAM_df": get_fred_data('WPUIP231120'),
    "ENGRSERVICES_df": get_fred_data('WPU4532'),
    "CEMENT_df": get_fred_data('WPU1322'),
}

# indices and categories
indices = [
    {'label': 'Construction For Government', 'value': 'WPUFD432'},
    {'label': 'Electrical Contractors Non-Residential', 'value': 'PCU23821X23821X'},
    {'label': 'Multi Family', 'value': 'WPUIP231120'},
    {'label': 'Engineering Services', 'value': 'WPU4532'},
    {'label': 'Cement', 'value': 'WPU1322'},
]
category = ['Consumer, Producer & Construction prices', 
           'new, repair & maintenance work by subcontractors', 
           'inputs to construction industries',
           'services important to construction',
           'processed goods important to construction',
           'unprocessed goods important to construction',
           'total compensation, wages & salaries']




#grid Columns and Rows
column_defs = [
    {'headerName':"Category", 'field':'category', 'sortable':False, 'filter':True,"checkboxSelection": True, "headerCheckboxSelection": True,},
    {'headerName':"Indice", 'field':'indice', 'sortable':False, 'filter':True},
    {'headerName':"Ticker", 'field':'ticker', 'sortable':False, 'filter':True},
    {'headerName':"PPI", 'field':'ppi', 'sortable':False, 'filter':True},
    {'headerName':"YOY%", 'field':'yoy%', 'sortable':False, 'filter':True},
    {'headerName':"Date", 'field':'date', 'sortable':False, 'filter':True, "filter": "agDateColumnFilter", 
     "filterValueGetter": {"function": "d3.timeParse('%d/%m/%Y')(params.data.date)"}, "filterParams": {
                                                                                                        "browserDatePicker": True,
                                                                                                        "minValidYear": 2000,
                                                                                                        "maxValidYear": 2021,
                                                                                                      },
    },
]


row_data = [
    {'category':"Consumer, Producer & Construction prices", "indice":"Construction For Government", "ticker":"WPUFD432", "ppi":167.184, "yoy%":-0.75, "date":"1/24/2024"},
    {'category':"new, repair & maintenance work by subcontractors", "indice":"Electrical Contractors Non-Residential", "ticker":"PCU23821X23821X", "ppi":167.129, "yoy%":-4.70, "date":"1/24/2024"},
    {'category':"inputs to construction industries", "indice":"Multi Family", "ticker":"WPUIP231120", "ppi":149.403, "yoy%":2.09, "date":"1/24/2024"},
    {'category':"services important to construction", "indice":"Engineering Services", "ticker":"WPU4532", "ppi":136.993, "yoy%":1.98, "date":"1/24/2024"},
    {'category':"processed goods important to construction", "indice":"Cement", "ticker":"WPU1322", "ppi":351.768, "yoy%":8.17, "date":"1/24/2024"},
    
]







#callbacks to update Graph when selected from grid checkbox
#id, value 
@app.callback(
    Output('central-graph', 'figure'),
    Input('dash-griddy', 'selectedRows') #change to column checkbox id, ticker name serves as value to select that graph

)
#change this function to know what is being selected and updated  #this is what i need to fix!!!!!!!!! for the graph to update
#what is selected_series_id??????
def update_graph(selected_series_id):
    df = get_fred_data(selected_series_id)
    corresponding_title = get_label_for_value(selected_series_id)

    return {
        'data': [{'x': df['date'], 
                  'y': df['value'], 
                  'type': 'line','line': {'width': 3},
                  'hovertemplate': '<br><b>%{x}: </b>%{y:.2f}<extra></extra>'},
                  ], 
                                       
        'layout': {'title': 'Construction For Government',
                   'xaxis': {'title': 'Date', 'hoverformat': ''},
                    'yaxis': {'title': 'PPI','hoverformat': ''}, 
                    "colorway": ["red"],
                    "hovermode": "x", #do x unified if i end up doing multiple graphs, with the dropdown multi select
                    'hoverlabel': {
                                    'bgcolor':"white",
                                    'font_size':25,
                                    'font_family':"Helvetica"
                                    },                                      
                            }
    }
#used in the callback above, this gathers the correct title of the graph from the series id 
#change to grid #change to grid#change to grid #change to grid#change to grid #change to grid#change to grid #change to grid
def get_label_for_value(value, options):
    for option in options:
        if option['value'] == value:
            return option['label']
    return None




# Layout to be Displayed on app.py container
layout = html.Div(
    [
        dcc.Graph(
            id='central-graph',
            figure={
                'data': [
                    {
                        'x': selected_series_id['date'],         #switch these to variables (and it gets updated with ex: ELECRICALCONTRACTORSNONRESBUILDINGWORK_df or
                                                                                                # MULTIFAM_df)
                        'y': selected_series_id['value'],
                        'type': 'line',
                        'name': 'Construction For Government',
                        'line': {'width': 3},
                        'hovertemplate': '<br><b>%{x}: </b>%{y:.2f}<extra></extra>',
                    }
                ],
                'layout': {
                    'title': 'Construction For Government',
                    'xaxis': {'title': 'Date', 'hoverformat': ''},
                    'yaxis': {'title': 'PPI', 'hoverformat': ''},
                    "colorway": ["red"],
                    "hovermode": "x",
                    'hoverlabel': {
                        'bgcolor': "white",
                        'font_size': 25,
                        'font_family': "Helvetica"
                    },
                }
            },
            className="graph-container"
        ),
        #data grid
        dag.AgGrid(
            id="dash-griddy", #use this id for callbacks to update the graph when check boxes are selected
            columnDefs=column_defs,
            rowData=row_data,
            columnSize= "responsiveSizeToFit",
            defaultColDef={"filter": True},
            dashGridOptions={
            "rowSelection": "multiple",
            'suppressRowClickSelection': True,
             'suppressMovableColumns': True,
            },
        ),
    ],
)

Hi @samorouji

You might find this example helpful:

Note that the selectedRows will have the data for the entire row . So for example, if you selected the first row, it would be

selectedRows =  [
    {'category': "Consumer, Producer & Construction prices", "indice": "Construction For Government",
     "ticker": "WPUFD432", "ppi": 167.184, "yoy%": -0.75, "date": "1/24/2024"}]

You can get the ticker like this:
ticker = selectedRows[0]["ticker"]

2 Likes