Aggregation with Custom Functions

Aggregation with custom functions is an AG Grid Enterprise feature, so you’ll need a license key to use it. See Using AG Grid Enterprise for an example of how to use your license key with Dash AG Grid components.

The following example demonstrates how to use a custom function that calculates a ratio. To run the example, add the JavaScript content that follows the example to the dashAgGridFunctions.js file in your app’s assets folder.


from dash import Dash, html, dcc
import dash_ag_grid as dag
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 = [
    # Row group by country and by year is enabled.
    {
        "field": "country",
        "rowGroup": True,
        "hide": True,
        "suppressColumnsToolPanel": True,
    },
    {
        "field": "sport",
        "rowGroup": True,
        "hide": True,
        "suppressColumnsToolPanel": True,
    },
    {
        "field": "year",
        "pivot": True,
        "hide": True,
        "suppressColumnsToolPanel": True,
    },
    {"field": "gold", "sortable": True, "filter": True, "aggFunc": "sum"},
    {"field": "silver", "sortable": True, "filter": True, "aggFunc": "sum"},
    {
        "headerName": "ratio",
        "colId": "goldSilverRatio",
        "aggFunc": {"function": "ratioAggFunc(params)"},
        "valueGetter": {"function": "ratioValueGetter(params)"},
        "valueFormatter": {"function": "ratioFormatter(params)"},
    },
]

app.layout = html.Div(
    [
        dcc.Markdown(
            "This is an example of how to calculate a ratio using values from multiple columns."
        ),
        dag.AgGrid(
            id="enterprise-aggregation-example-custom",
            enableEnterpriseModules=True,
            licenseKey = os.environ['AGGRID_ENTERPRISE'],
            columnDefs=columnDefs,
            rowData=df.to_dict("records"),
            dashGridOptions={
                "rowSelection": "multiple",
                "suppressAggFuncInHeader": True,
                "animateRows": False,
            }
        ),
    ]
)


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

This is an example of how to calculate a ratio using values from multiple columns.

JavaScript function

Add the following to the dashAgGridFunctions.js file in your app’s assets folder:

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

dagfuncs.ratioValueGetter = function (params) {
  if (!(params.node && params.node.group)) {
    // no need to handle group levels - calculated in the 'ratioAggFunc'
    return createValueObject(params.data.gold, params.data.silver);
  }
}
dagfuncs.ratioAggFunc = function (params) {
  let goldSum = 0;
  let silverSum = 0;
  params.values.forEach((value) => {
    if (value && value.gold) {
      goldSum += value.gold;
    }
    if (value && value.silver) {
      silverSum += value.silver;
    }
  });
  return createValueObject(goldSum, silverSum);
}

function createValueObject(gold, silver) {
  return {
    gold: gold,
    silver: silver,
    toString: () => `${gold && silver ? gold / silver : 0}`,
  };
}

dagfuncs.ratioFormatter = function (params) {
  if (!params.value || params.value === 0) return '';
  return '' + Math.round(params.value * 100) / 100;
}