Dash ag grid: highlighting the max on each row

Hello

I have started migrating some of my tables from datatable to ag-grid.
I am struggling to replicate something I had done in datatable:
I would like to highlight by changing the colour the max of each row in my grid. My data is updated regularly, so I cannot use predefined maxs.
I should be using class rules I guess but I haven’t managed to find any example / do it on my own.
Could anyone help me on this?
Thanks in advance

Hello @mc2pezwb,

Can you give a starting point for your data and grid?

This should be able to be accomplished. :slight_smile:

Hello @jinnyzor

Sure, I was using the code for the “styling cells like a Heatmap with custom function” on Dash to start with.
Basically instead of doing a heatmap I would want to just highlight the max on each row. So the first row would have “52” in let’s say red, the second row it would be “-8” etc

Sure, the best way to do this is cellClassRules as the whole row gets reevaluated as data is updated.

app.py

from dash import Dash, html
import dash_ag_grid as dag
import pandas as pd
import numpy as np

app = Dash(__name__)

cellClassRules = {
                "max": "params.value == MaxObject(params.data)"
            }

df = pd.DataFrame(np.random.randint(-100, 100, size=(10, 3)), columns=list("abc"))
df = df[:5]
df["items"] = [f"Item {i}" for i in range(len(df))]
df_numeric_columns = df.select_dtypes("number")


columnDefs = [{"field": "items"},] + [
    {
        "field": field,
        "type": "numericColumn",
        "valueSetter": {"function": "MakeFloat(params)"}
    }
    for field in ["a", "b", "c"]
]


defaultColDef = {
    "resizable": True,
    "sortable": True,
    "editable": True,
    "minWidth": 100,
    "cellClassRules": cellClassRules
}


grid = dag.AgGrid(
    columnDefs=columnDefs,
    rowData=df.to_dict("records"),
    columnSize="responsiveSizeToFit",
    defaultColDef=defaultColDef,
    dashGridOptions={"suppressRowHoverHighlight": True},
)

app.layout = html.Div(
    [
        grid,
    ],
    style={"margin": 20},
)

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

js functions:

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

dagfuncs.MaxObject = (obj) => {
    return Math.max(...Object.values(obj).filter((v) => {if (typeof(v) == 'number') { return v}}))
}

dagfuncs.MakeFloat = (params) => {
             params.data[params.column.colId] = parseFloat(params.newValue);
             return true;
         }

Please note, the inputs were being classified as strings, which is why I had to adjust the valueSetter to MakeFloat

2 Likes

This is really fantastic, thank you very much. And now I can ask GPT-4 to explain me why this works :slight_smile:

1 Like