plotly / dash-ag-grid

Dash AG Grid is a high-performance and highly customizable component that wraps AG Grid, designed for creating rich datagrids.
https://dash.plotly.com/dash-ag-grid
MIT License
172 stars 25 forks source link

Bug-PivotComparator Sorting Issue in Ag-Grid Pivoted Table #324

Closed andre996 closed 1 week ago

andre996 commented 1 week ago

Description:

When attempting to implement the pivotComparator property on a pivoted table, using the function code from the Ag-Grid documentation for sorting, the pivot table fails to work as expected. The data is neither compared nor sorted correctly.

dash-ag-grid version:

Sample:

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, 
    "pivotComparator": {"function" : "(a, b) =>  {b.localeCompare(a)}"}
    },
    {"field": "year"},
    {"field": "date"},
    {"field": "gold", "aggFunc": "sum"},
]

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

app.layout = html.Div(
    [
        dcc.Markdown("Demonstration of pivot in a Dash AG Grid."),
        dcc.Markdown(
            "The example below shows a simple pivot on the Sport column using the Gold, Silver and Bronze columns for values."
        ),
        dag.AgGrid(
            id="pivot-ag-grid-example",
            columnDefs=columnDefs,
            rowData=df.to_dict("records"),
            dashGridOptions={
                "autoGroupColumnDef": {"minWidth": 250},
                "animateRows": False,
                "pivotMode": True,
            },
            defaultColDef=defaultColDef,
            # Pivot groupings is an ag-grid Enterprise feature.
            # A license key should be provided if it is used.
            # License keys can be passed to the `licenseKey` argument of dag.AgGrid
            enableEnterpriseModules=True,
        ),
    ]
)

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

Note: Same behavior with the function on a JS file.

AnnMarieW commented 1 week ago

Hi @andre996

Thanks for reporting. In the next release, you can use the pivotComparitor in the columnDefs like this:

columnDefs = [
  {"field": "sport", "pivot": True, "pivotComparator": {"function": "sortColumns"}},
  #...

]

Then define the function in dashAgGridFunctions.js

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

dagfuncs.sortColumns = (a, b) => b.localeCompare(a)