Plotly Dash:data_table 单个单元格的背景颜色

Plotly Dash: data_table background color for individual cell

我在 dash_table.DataTable 数据框中显示一个数据框,其中有一列颜色名称为十六进制格式,代码如下:

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()

这是我得到的:

我想设置每个单元格及其内容的背景颜色(可能还有字体颜色),但仅针对该列(始终是 table 的第一列)按顺序设置得到这个:

对我来说可以将dash_table.DataTable替换为plotly.graph_objects.Tabledocumentation),这样可能更可定制;前提是我可以在 dash 仪表板中实施 plotly.graph_objects.Table

版本信息:

Python               3.7.0
dash                 1.12.0
dash-table           4.7.0
plotly               4.7.0

您可以使用 style_data_conditional 定义每个单元格的背景颜色和字体颜色(以及其他几个属性),参见 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()