Plotly-Dash中如何按数值为表格着色且保留行列索引无着色
实现方案
Plotly 表格组件的样式规则支持按列类型匹配,你只需要将背景色规则限定在数据列即可自动跳过行索引和表头,实现你要的效果。以下是两种常用的实现方式:
方式1:使用 Dash 原生 dash_table.DataTable(推荐在Dash项目中使用)
import dash from dash import dash_table, html import pandas as pd # 替换为你自己的DataFrame df = pd.DataFrame({ "A": [1,0,1,0], "B": [0,1,0,1], "C": [1,1,0,0], "D": [0,0,1,1] }) app = dash.Dash(__name__) app.layout = html.Div([ dash_table.DataTable( # 传入数据 data=df.to_dict("records"), # 配置列信息 columns=[{"name": col, "id": col} for col in df.columns], # 开启原生行索引渲染,无需手动处理索引列 index=True, # 单元格背景色规则 style_data_conditional=[ # 数值为1的单元格设绿色背景,仅作用于数据列 { "if": { "filter_query": "{{{}}} = 1".format(col), "column_type": "data" }, "backgroundColor": "green", "color": "#fff" } for col in df.columns ] + [ # 数值为0的单元格设灰色背景,仅作用于数据列 { "if": { "filter_query": "{{{}}} = 0".format(col), "column_type": "data" }, "backgroundColor": "grey", "color": "#fff" } for col in df.columns ], # 保留表头默认样式 style_header={ "backgroundColor": "#fff", "fontWeight": "bold", "border": "1px solid #e0e0e0" }, # 通用单元格样式 style_cell={ "border": "1px solid #e0e0e0", "padding": "6px 12px" } ) ]) if __name__ == "__main__": app.run_server(debug=True)
方式2:使用 plotly.graph_objects.Table 实现
import plotly.graph_objects as go import pandas as pd # 替换为你自己的DataFrame df = pd.DataFrame({ "A": [1,0,1,0], "B": [0,1,0,1], "C": [1,1,0,0], "D": [0,0,1,1] }) # 构造颜色矩阵,第一列为行索引,统一设为默认白色 colors = [] colors.append(["#fff"]*len(df)) # 遍历数据列生成对应背景色 for col in df.columns: col_colors = [] for val in df[col]: col_colors.append("green" if val ==1 else "grey") colors.append(col_colors) # 生成表格 fig = go.Figure(data=[go.Table( # 表头配置,保留默认样式 header=dict( values=["行索引"] + df.columns.tolist(), fill_color="#fff", align="left" ), # 单元格配置 cells=dict( values=[df.index.tolist()] + [df[col] for col in df.columns], fill_color=colors, align="left" ) )]) fig.show()
内容的提问来源于stack exchange,提问作者philein-sophos
相关产品推荐
相关产品推荐

