简体   繁体   中英

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:

在此处输入图像描述

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:

在此处输入图像描述

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

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/style .

import dash
import dash_table
import dash_html_components as html
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'][i], 'color': df['COLOR'][i]} for i in range(df.shape[0])]
    ),

], style=dict(width='100px'))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM