Bring Drag & Drop to Dash with Dashboard Engine. 💫 Learn how at our next webinar!

Need help with conditional formatting

Hi, I need help to understand how to set conditional formatting in a specific row elements if they match a specific value.
Supose I have a row that has the book/value of a company, the columns represents different reports dates.
I want to apply different background colors for each element of that row if they are less than 1 or grather than 1 in order to quikly visualize if that parameter is above or below the given value (in this case the “1”)
Thanks in advance.
Eduardo

Hi @Eduardo

There is an example here that should help: Plotly Annotated Heatmap Colorscale (DASH)

Let me know if you still have any questions.

thanks AnnMarie for your quick response.
I understand that your solution is for the entire table, I need to evaluate a specific row.
I have a table where each row has a specific data (parameter) for the Company and each parameter has a different value to compare with.
For example: row 2 has “Book value / Share Price”, if this value is below “1” I want to format in green, if the value is above “1” format yellow.
For row 3 I have “Income growth” if the values are positive I want to format in green if negative in red.
And doing the same for each row in the table.
The problem is that each row has diferent parameter to compare with.
I am evaluating to solve the issue transposing the table and using the conditional format for each column, but the layout of the page dont look nice.
Thanks again.
Eduardo

Well, that does add another layer of complexity…

Here is a simple example of how you could apply a different format for each row. It doesn’t seem like an ideal solution though.

import dash
import dash_table

import pandas as pd

app = dash.Dash(__name__)


import numpy as np
np.random.seed(1)

df = pd.DataFrame(np.random.randn(3, 4), columns=list('ABCD'))

# define a different style for each row
style_dict={}
style_dict[0] = {'col': np.where(df.iloc[0].values < 0), 'color':'red'}
style_dict[1] = {'col': np.where(df.iloc[1].values > 1), 'color':'yellow'}
style_dict[2] = {'col': np.where(df.iloc[2].values > 0), 'color':'green'}


def style_row_by_row(df):    
    styles = []
    for i in range(len(df)):
        row = df.loc[i, :]
        for j in style_dict[i]['col']:
            styles.append({
                'if': {
                    'filter_query': '{{id}} = {}'.format(i),
                    'column_id': row.keys()[j]
                },
                'backgroundColor': style_dict[i]['color'],
                'color': 'white'
            })
    return styles

df['id'] = df.index
app.layout = dash_table.DataTable(
    data=df.to_dict('records'),
    sort_action='native',
    columns=[{'name': i, 'id': i} for i in df.columns if i != 'id'],
    style_data_conditional=style_row_by_row(df)
)       

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

1 Like

Thanks Ann Marie !!!
This is what I was looking for. :heart_eyes:

Muchas gracias.
Eduardo

1 Like

I added an additional loop using “style_dict2” in order to set two color option for the same row.
I dont know if it is the best solution but it works.

here is the code:

import dash
import dash_table

import pandas as pd

app = dash.Dash(name)

import numpy as np
np.random.seed(1)

df = pd.DataFrame(np.random.randn(3, 4), columns=list(‘ABCD’))

style_dict={}
style_dict2={}
style_dict[0] = {‘col’: np.where(df.iloc[0][1:].values > 1), ‘color’:‘red’}
style_dict2[0] = {‘col’: np.where(df.iloc[0][1:].values < 1), ‘color’:‘green’}

style_dict[1] = {‘col’: np.where(df.iloc[1][1:].values > 0), ‘color’:‘green’}
style_dict2[1] = {‘col’: np.where(df.iloc[1][1:].values < 0), ‘color’:‘blue’}

style_dict[2] = {‘col’: np.where(df.iloc[2][1:].values > 1), ‘color’:‘green’}
style_dict2[2] = {‘col’: np.where(df.iloc[2][1:].values < 1), ‘color’:‘orange’}

print(style_dict)

def style_row_by_row(df):
styles =
for i in range(len(df)):
row = df.loc[i, :]
for j in style_dict[i][‘col’]:
styles.append({
‘if’: {
‘filter_query’: ‘{{id}} = {}’.format(i),
‘column_id’: row.keys()[j+1]
},
‘backgroundColor’: style_dict[i][‘color’],
‘color’: ‘white’
})

for i in range(len(df)):
    row = df.loc[i, :]
    for j in style_dict2[i]['col']:     
        styles.append({
            'if': {
                'filter_query': '{{id}} = {}'.format(i),
                'column_id': row.keys()[j+1]
            },
            'backgroundColor': style_dict2[i]['color'],
            'color': 'white'
        })

return styles

df[‘id’] = df.index
app.layout = dash_table.DataTable(
data=df.to_dict(‘records’),
sort_action=‘native’,
columns=[{‘name’: i, ‘id’: i} for i in df.columns if i != ‘id’],
style_data_conditional=style_row_by_row(df)
)

if name == “main”:
app.run_server(debug=True)