Dash AG Grid with pivot, pinned columns and total row

A question came up recently about how to pin columns and add a total row when using Dash AG Grid in pivot mode. Since there are not a lot of Enterprise examples in the dash docs, I thought I would post it here. Note that this requires a license from AG Grid. See more info here:

"""

This uses AG Grid Enterprise - a license is required.

For more information:

 - AG Grid Docs:  https://www.ag-grid.com/react-data-grid/pivoting/#pivot-result-column-definitions
 - Dash AG Grid Docs: - https://dash.plotly.com/dash-ag-grid/enterprise-pivot

Note - this example is for dash-ag-grid==31.2.0.  In future releasese `groupIncludeTotalFooter` - deprecated, use `grandTotalRow` instead  

"""


import dash_ag_grid as dag
from dash import Dash, html, dcc
import pandas as pd

import os

app = Dash(__name__)


df = pd.read_csv(
    "https://raw.githubusercontent.com/plotly/datasets/master/ag-grid/olympic-winners.csv"
)


columnDefs = [
    {"field": "country", "rowGroup": True, "enableRowGroup": True},
    {"field": "sport", "pivot": True},
    {"field": "year"},
    {"field": "date"},
    {"field": "gold", "aggFunc": "sum"},
    {"field": "silver", "aggFunc": "sum"},
    {"field": "bronze", "aggFunc": "sum"},
]

defaultColDef = {"flex": 1, "minWidth": 150}

app.layout = html.Div(
    [
        dcc.Markdown("### Dash AG Grid Enterprise Example - Pivot with Pinned Column and Total Row."),
        dag.AgGrid(
            id="pivot-ag-grid-example",
            columnDefs=columnDefs,
            rowData=df.to_dict("records"),
            dashGridOptions={
                "autoGroupColumnDef": {"minWidth": 250},
                "animateRows": False,
                "pivotMode": True,
                "processPivotResultColDef": {"function": "pinned(params)"},
                "groupIncludeTotalFooter": True
            },
            defaultColDef=defaultColDef,
            enableEnterpriseModules=True,
        ),
    ]
)


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

Place the following int he dashAgGridFunctions.js file in the assets folder:


var dagfuncs = (window.dashAgGridFunctions = window.dashAgGridFunctions || {});

dagfuncs.pinned = (colDef) => {
    if ( colDef.colId=== 'pivot_sport_Wrestling_gold') {       
        colDef.pinned='left';
        colDef.lockPinned=true;
    }
};

5 Likes