Search code examples
pythondatatablebackground-colorplotly-dash

Plotly Dash: data_table background color for individual cell


I display in a dash_table.DataTable a dataframe where there is a column with color names in hex format, with this code:

import dash
import dash_table
import pandas as pd

df = pd.DataFrame(data = dict(COLOR = ['#1f77b4', '#d62728', '#e377c2', '#17becf', '#bcbd22'],
                              VALUE = [1, 2, 3, 4, 5]))

app = dash.Dash(__name__)

app.layout = html.Div([dash_table.DataTable(id = 'table',
                                            columns = [{"name": i, "id": i} for i in df.columns],
                                            data = df.to_dict('records'))],
                      style = dict(width = '200px'))

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

This is what I get:

enter image description here

I would like to set the background color (and maybe the font color) of each individual cell with its content, but only for that column (which is always the first column of the table) in order to get this:

enter image description here

To me is ok to replace the dash_table.DataTable with plotly.graph_objects.Table (documentation), which maybe it is more customizable; provided that I can implement the plotly.graph_objects.Table in a dash dashboard.

Version info:

Python               3.7.0
dash                 1.12.0
dash-table           4.7.0
plotly               4.7.0

Solution

  • You can define the background color and the font color (as well as several other properties) of each individual cell using style_data_conditional, see https://dash.plotly.com/datatable/conditional-formatting.

    import dash
    from dash import html,dash_table
    import pandas as pd
    
    df = pd.DataFrame(data=dict(COLOR=['#1f77b4', '#d62728', '#e377c2', '#17becf', '#bcbd22'],
                                VALUE=[1, 2, 3, 4, 5]))
    
    app = dash.Dash(__name__)
    
    app.layout = html.Div([
    
        dash_table.DataTable(
            id='table',
            columns=[{'name': i, 'id': i} for i in df.columns],
            data=df.to_dict('records'),
            style_data_conditional=[{'if': {'row_index': i, 'column_id': 'COLOR'}, 'background-color': df['COLOR'].iloc[i], 'color': df['COLOR'].iloc[i]} for i in range(df.shape[0])]
        ),
    
    ], style=dict(width='100px'))
    
    if __name__ == '__main__':
        app.run_server()