Color Formatting Dash Datatable

I am trying to use conditional formatting to set colors of a datatable cell. I have tried going thru forum questions and the official documentation but could not get to my specific requirement. I am new to the Dash World and was looking for some suggestions from the experts here.

I have picked the sample program from Dash Documentation to work upon but could not understand how.

I need to updated the last cell of column ‘Humidity’ with color “Green” or “Red” depending on the value of the first cell of the same column. If the value of second cell has increased (meaning greater than) it gets the color green and if the value of second cell has decreased ( meaning lesser than) it gets the color red.

Note: The actual dataframe has thousands of rows but I just need to look at the last 2 rows as new data is added every 5 minutes.

Any Input/Suggestion will be of great help.

from dash import Dash, dash_table
import pandas as pd
from collections import OrderedDict

data = OrderedDict(
    [
        ("Date", ["2015-01-01", "2015-01-02"]),
        ("Region", ["Montreal", "Montreal"]),
        ("Temperature", [1, -20]),
        ("Humidity", [14, 12]),
        ("Pressure", [2, 10924]),
    ]
)

df = pd.DataFrame(data)

app = Dash(__name__)

app.layout = dash_table.DataTable(
    data=df.to_dict('records'),
    sort_action='native',
    columns=[{'name': i, 'id': i} for i in df.columns],
    style_data_conditional=[
        {
            'if': {
                'filter_query': '{{{}}} >= {}'.format(col, value),
                'column_id': col
            },
            'backgroundColor': '#B10DC9',
            'color': 'white'
        } for (col, value) in df.quantile(0.9).iteritems()
    ]
)

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

I don’t think you can filter based on the color of the first cell, but instead focus on the criteria used to set the color of the first cell.

There are a few ways to tackle this. I would recommend setting the style_cell_conditional in a callback with a state of data.

First_cell = data[0][‘column_name’]
Last_cell = data[len(data)][‘column_name’]

Then build the conditional based on column_id and row_index.

If you want to detect if it increased, you will need to load data_previous and compare the two.

It’s not color but the value of the first cell… it was a typo and I have corrected the question now. apologies

Hi @sukhiaatma

Here is an example where the values of a column are highlighted based on the value of the first row of the column:


from dash import Dash, dash_table
import pandas as pd
from collections import OrderedDict

data = OrderedDict(
    [
        ("Date", ["2015-01-01", "2015-10-24", "2016-05-10", "2017-01-10", "2018-05-10", "2018-08-15"]),
        ("Region", ["Montreal", "Toronto", "New York City", "Miami", "San Francisco", "London"]),
        ("Temperature", [1, -20, 3.512, 4, 10423, -441.2]),
        ("Humidity", [10, 20, 30, 40, 50, 60]),
        ("Pressure", [2, 10924, 3912, -10, 3591.2, 15]),
    ]
)

df = pd.DataFrame(data)

app = Dash(__name__)

def highlight_above_and_below_first_row(df):
    df_numeric_columns = df.select_dtypes('number')
    return (
        [
            {
                'if': {
                    'filter_query': '{{{}}} > {}'.format(col, df[col].iloc[0]),
                    'column_id': col
                },
                'backgroundColor': '#3D9970',
                'color': 'white'
            } for col in df_numeric_columns.columns
        ] +
        [
            {
                'if': {
                    'filter_query': '{{{}}} <= {}'.format(col, df[col].iloc[0]),
                    'column_id': col
                },
                'backgroundColor': '#FF4136',
                'color': 'white'
            } for col in df_numeric_columns.columns
        ]
    )


app.layout = dash_table.DataTable(
        data=df.to_dict('records'),
        columns=[{'name': i, 'id': i} for i in df.columns],
        style_data_conditional=highlight_above_and_below_first_row(df)
    )


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



Hi @AnnMarieW ,

Thanks for showing the way. That’s exactly how I wanted it.
However, With your code the first cell values is always taking color red.

I Will Try working on it for my desired output. Actually I just wanted the cells from second row to be ‘Green’ or ‘Red’.

still better if you provide some inputs.

Thanks a Lot. I appreciate your input and time :slightly_smiling_face:

Oh that’s easy - just change the <= to <:

 'filter_query': '{{{}}} < {}'.format(col, df[col].iloc[0]),
1 Like

Hi Ann,

Your Instant replies to my queries had me feeling as if we were a team working face to face. I have an issue and you have an answer. Amazing.

Your code works perfectly.

I just started with Dash and the next issue I faced was passing data to the style conditioner as my data was being generated in the callback. I read through the forums and got my code working.

thanks a lot.

I’m so happy I could help, and thanks for your kind words - that means a lot to me :smiling_face:

It sounds like you are making great progress :rocket: Good luck with all your future Dash projects ,