How to use External Filters with Dash AG Grid

Thanks to the dedicated work of Dash Community member @Skiks, the Dash AG Grid documentation is continuously improving. Keep an eye out for regular updates!

He recently added the documentation for External Filters, which is a powerful way to filter grid data using external Dash components such as figures, dropdowns, and sliders.

This new addition served as inspiration for my latest tutorial on the Dash AG Grid Examples site.

Learn how to leverage the grid’s External Filter API and explore alternatives like updating the rowData or the Filter Model in a callback.

Please note, the gif does not fully capture the lightning-fast grid updates. Be sure to check out the site to see this and other examples live!

Here is the code for the first example:

from dash import Dash, dcc, html, Input, Output, callback, no_update
import plotly.express as px
import pandas as pd
import dash_ag_grid as dag

app =  Dash(__name__)

df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k-multi-year.csv")

fig = px.scatter_mapbox(
    df[df.year==2018],
    lat="lat", lon="lon",
    hover_data=["City", "State"],
    size="Population",  color="Population",
    zoom=4,
)
fig.update_layout(mapbox_style="open-street-map")
fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})

app.layout = html.Div(
    [
        html.H3("Population 2018"),
        html.H4("Filter the grid by hovering on the map"),
        dcc.Graph(id="graph", figure=fig),
        dag.AgGrid(
            id="grid",
            rowData=df.to_dict("records"),
            columnDefs=[{"field": i} for i in ["City", "State", "Population", "year"]],
            defaultColDef={"flex": 1, "filter": True},
        ),
    ],
)


@callback(
    Output("grid", "dashGridOptions"),
    Input("graph", "hoverData"),
)
def generate_chart(hoverdata):
    if not hoverdata:
        return no_update

    city = hoverdata["points"][0]["customdata"][0]
    state = hoverdata["points"][0]["customdata"][1]

    return {
        "isExternalFilterPresent": {"function": "true"},
        "doesExternalFilterPass": {"function": f"params.data.City === '{city}' && params.data.State === '{state}'"}
    }


if __name__ == "__main__":
    app.run(debug=True)

3 Likes

Thanks @AnnMarieW for those amazing examples!
I love the idea to filter the grid while hovering the graph :star_struck:

4 Likes

Thank you @Skiks for your constant and thorough work in the Docs. The radio button / ag-grid example was really fun to play with and amazingly fast.

@AnnMarieW , what a great new set of examples. I can’t even see a lag in the data updating every time I move my mouse :astonished: It’s so fast. I think I’m going to promote this on social media as well if that’s ok by you. Let me know. I want more people to see these examples.

3 Likes