Dash AG Grid: Sortable, Filterable Tables Linked to Charts

Show a pandas DataFrame in a sortable, filterable, paginated grid with dash-ag-grid, format and color cells, update a Plotly chart from the rows the user filters or selects, and react to edits.

To show a pandas DataFrame as a sortable, filterable table in Dash, use dag.AgGrid from dash-ag-grid: pass rowData=df.to_dict("records") and a columnDefs list with one dictionary per column. It replaces dash_table.DataTable, which is deprecated in Dash 4.5, and it has the features people expect from a spreadsheet: column filters, pagination, resizing, pinned columns, cell editing and row selection. Install it with pip install dash-ag-grid. This post was run with Dash 4.5 and dash-ag-grid 35.3, which wraps AG Grid 35.

Quick Example

The data are 300 simulated invoices (seeded, so you get the same rows). Save this as app.py:

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

rng = np.random.default_rng(402)
n = 300
customers = ["Alder Foods", "Birch Labs", "Cedar Print", "Dune Logistics",
             "Elm Studio", "Fjord Marine", "Grove Energy", "Harbor Textiles"]
invoices = pd.DataFrame({
    "invoice": [f"INV-{1000 + i}" for i in range(n)],
    "customer": rng.choice(customers, n),
    "region": rng.choice(["West", "East", "North", "South"], n, p=[0.3, 0.3, 0.2, 0.2]),
    "amount": rng.lognormal(7.2, 0.8, n).round(2),
    "status": rng.choice(["Paid", "Open", "Overdue"], n, p=[0.6, 0.25, 0.15]),
    "issued": (pd.Timestamp("2026-01-01") + pd.to_timedelta(rng.integers(0, 330, n), unit="D"))
              .strftime("%Y-%m-%d"),
})

columns = [
    {"field": "invoice", "pinned": "left"},
    {"field": "customer"},
    {"field": "region"},
    {"field": "amount", "type": "rightAligned", "filter": "agNumberColumnFilter",
     "valueFormatter": {"function": "d3.format('$,.2f')(params.value)"}},
    {"field": "status"},
    {"field": "issued", "filter": "agDateColumnFilter"},
]

app = Dash()

app.layout = html.Div([
    html.H2("Invoices"),
    dag.AgGrid(
        id="grid",
        rowData=invoices.to_dict("records"),
        columnDefs=columns,
        defaultColDef={"sortable": True, "filter": True, "resizable": True},
        columnSize="sizeToFit",
        dashGridOptions={"pagination": True, "paginationPageSize": 10, "paginationPageSizeSelector": False,
                         "domLayout": "autoHeight"},
    ),
], style={"maxWidth": "900px", "margin": "auto", "fontFamily": "sans-serif"})


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

Dash AG Grid table of invoices with columns for invoice, customer, region, amount, status and issue date, ten rows per page

Click a column header to sort, and again to reverse. Click the filter icon in a header to filter that column. Drag a column border to resize it. The pieces of the grid are:

  • rowData is a list of dictionaries, one per row. df.to_dict("records") makes it.
  • columnDefs describes the columns. Each field must match a key in the row dictionaries.
  • defaultColDef holds settings every column shares. sortable and filter are set there so each column gets them.
  • dashGridOptions passes raw AG Grid options. Pagination is switched on here with pagination and paginationPageSize. In columnDefs, "filter": "agNumberColumnFilter" gives a number column filters like "greater than" and "between". Text is the default, and agDateColumnFilter compares dates.
  • "domLayout": "autoHeight" sizes the grid to its rows. The alternative is a fixed style={"height": "480px"}, which a grid needs if it isn't auto-height. Without either it renders at zero height. "paginationPageSizeSelector": False hides the page-size dropdown, which would otherwise show an empty box for a page size such as 8 that isn't one of its choices.

Dates should reach the grid as YYYY-MM-DD strings to work with agDateColumnFilter.

Format Numbers and Color Cells

A valueFormatter changes how a value is shown without changing the value, so sorting and filtering still use the number. Formatters are JavaScript, written as a {"function": "..."} dictionary. Dash AG Grid makes the d3 library available to them, which is why d3.format('$,.2f') works. A cellStyle with styleConditions colors cells by rule. Replace everything from app = Dash() down:

columns[3]["cellStyle"] = {"styleConditions": [
    {"condition": "params.value >= 3000", "style": {"fontWeight": "bold"}},
]}
columns[4]["cellStyle"] = {"styleConditions": [
    {"condition": "params.value == 'Overdue'", "style": {"backgroundColor": "#fde2e0", "color": "#a4281b"}},
    {"condition": "params.value == 'Paid'", "style": {"backgroundColor": "#e1f3e8", "color": "#1d6b3c"}},
]}

app = Dash()

app.layout = html.Div([
    html.H2("Invoices"),
    dag.AgGrid(
        id="grid",
        rowData=invoices.to_dict("records"),
        columnDefs=columns,
        defaultColDef={"sortable": True, "filter": True, "resizable": True},
        columnSize="sizeToFit",
        dashGridOptions={"pagination": True, "paginationPageSize": 10, "paginationPageSizeSelector": False,
                         "domLayout": "autoHeight"},
    ),
], style={"maxWidth": "900px", "margin": "auto", "fontFamily": "sans-serif"})


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

Dash AG Grid with the status column colored green for Paid, red for Overdue and uncolored for Open, and amounts of 3,000 dollars or more in bold

params.value is the cell's value, and params.data is the whole row, so a condition can look at other columns too (params.data.amount > 3000 && params.data.status == 'Open'). The condition is a JavaScript expression in a string, not Python, so use == and &&.

Update a Chart from the Filtered Rows

The grid has properties that callbacks can read. virtualRowData holds the rows after sorting and filtering, so a chart can follow whatever the user filtered. selectedRows holds the rows the user selected. Here both feed charts:

app = Dash()

app.layout = html.Div([
    html.H2("Invoices"),
    dag.AgGrid(
        id="grid",
        rowData=invoices.to_dict("records"),
        columnDefs=columns,
        defaultColDef={"sortable": True, "filter": True, "resizable": True},
        columnSize="sizeToFit",
        dashGridOptions={"pagination": True, "paginationPageSize": 8, "paginationPageSizeSelector": False,
                         "domLayout": "autoHeight", "rowSelection": {"mode": "multiRow"}},
    ),
    html.P(id="summary", style={"margin": "12px 0"}),
    dcc.Graph(id="by-region"),
], style={"maxWidth": "900px", "margin": "auto", "fontFamily": "sans-serif"})


@callback(
    Output("by-region", "figure"),
    Output("summary", "children"),
    Input("grid", "virtualRowData"),
    Input("grid", "selectedRows"),
)
def update(visible, selected):
    rows = pd.DataFrame(selected or visible or [], columns=invoices.columns)
    source = "selected" if selected else "filtered"
    totals = rows.groupby("region", as_index=False)["amount"].sum()
    fig = px.bar(totals, x="region", y="amount", template="plotly_white",
                 category_orders={"region": ["West", "East", "North", "South"]},
                 labels={"region": "", "amount": "Amount"}, color_discrete_sequence=["#6d597a"])
    fig.update_layout(height=300, margin=dict(l=60, r=10, t=30, b=30))
    return fig, f"{len(rows)} {source} invoices, ${rows['amount'].sum():,.0f} in total"


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

Dash AG Grid with four rows selected and a bar chart of the amount by region for just those four invoices

With nothing selected, the chart shows every row that passes the current filters (all pages, not only the visible one). Select rows with the checkboxes and it switches to those. "rowSelection": {"mode": "multiRow"} adds the checkbox column and allows several rows. Use "singleRow" for one. The object form of rowSelection replaced the older "rowSelection": "multiple" string in AG Grid 32.2.

Let Users Edit Cells

Add "editable": True to a column and double-click a cell to edit it. The cellValueChanged property reports each change, so a callback can validate it or save it:

columns[4].update({"editable": True, "cellEditor": "agSelectCellEditor",
                   "cellEditorParams": {"values": ["Paid", "Open", "Overdue"]}})

app = Dash()

app.layout = html.Div([
    html.H2("Edit an invoice status"),
    dag.AgGrid(
        id="grid",
        rowData=invoices.to_dict("records"),
        columnDefs=columns,
        defaultColDef={"sortable": True, "filter": True, "resizable": True},
        columnSize="sizeToFit",
        dashGridOptions={"pagination": True, "paginationPageSize": 8, "paginationPageSizeSelector": False,
                         "domLayout": "autoHeight"},
    ),
    html.P(id="log", style={"margin": "12px 0"}),
], style={"maxWidth": "900px", "margin": "auto", "fontFamily": "sans-serif"})


@callback(Output("log", "children"), Input("grid", "cellValueChanged"), prevent_initial_call=True)
def log_change(changes):
    change = changes[0]
    return (f"{change['data']['invoice']}: {change['colId']} changed from "
            f"{change['oldValue']} to {change['value']}")


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

Dash AG Grid after the status of the first invoice was changed, with a message below the table naming the invoice and its old and new status

Edits live in the browser, so a page reload brings back the original rowData. To keep them, write the change to a database in the callback. rowData also updates from a callback, which is how you reload the grid after a save.

Dash AG Grid vs DataTable vs a dbc.Table

dag.AgGrid dash_table.DataTable dbc.Table
Status in Dash 4.5 Recommended Deprecated Fine for static tables
Sort, filter, paginate Built in Built in None
Thousands of rows Yes (row virtualization) Slower No
Cell formatting JavaScript valueFormatter and cellStyle Python dictionaries Python only
Editing, selection, pinned columns Yes Partly No
Install pip install dash-ag-grid Built into Dash pip install dash-bootstrap-components

Formatting is the biggest adjustment. DataTable described styles in Python, while AG Grid expects small JavaScript expressions in strings.

Practical Tips

  • Set a height. Use "domLayout": "autoHeight" for short or paginated tables, or style={"height": "480px"} for a scrolling grid. With neither, the grid has no height.
  • Match field to the keys exactly. A typo gives an empty column with no error.
  • Send plain Python types. rowData is JSON. Convert dates to strings and avoid NumPy objects.
  • Use the row count wisely. The grid virtualizes rows, so tens of thousands are fine, but every row goes to the browser. For millions, use AG Grid's server-side row model.
  • Start from defaultColDef. Put shared options there and override per column in columnDefs.

Similar Topics