You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Dash Plotly 表格格式化时自定义颜色图例的方法咨询

实现表格数值极端值红色、中间值绿色高亮的修改方案

你只需要修改代码中色阶取值的逻辑即可,具体调整如下:

核心修改点

原来的代码使用了默认的RdYlGn发散色阶(低值红、高值绿),你需要自定义色阶列表,让色阶两端为红色、中间为绿色/蓝色。

修改后完整代码

def discrete_background_color_bins(df, n_bins=7, columns='all'):
    # 自定义色阶:两端为红色,中间为绿色,可根据需求调整颜色值
    custom_colors = [
        '#d73027', # 极小值:红色
        '#f46d43', # 次小值:浅红
        '#fee08b', # 偏小值:浅黄过渡
        '#1a9850', # 中间值:绿色
        '#fee08b', # 偏大值:浅黄过渡
        '#f46d43', # 次大值:浅红
        '#d73027'  # 极大值:红色
    ]
    # 如果需要中间值为蓝色,可把custom_colors替换为:
    # custom_colors = [
    #     '#d73027', '#f46d43', '#fee08b', '#4575b4', 
    #     '#fee08b', '#f46d43', '#d73027'
    # ]
    bounds = [i * (1.0 / n_bins) for i in range(n_bins+1)]
    if columns == 'all':
        if 'id' in df:
            df_numeric_columns = df.select_dtypes('number').drop(['id'], axis=1)
        else:
            df_numeric_columns = df.select_dtypes('number')
    else:
        df_numeric_columns = df[columns]
    df_max = df_numeric_columns.max().max()
    df_min = df_numeric_columns.min().min()
    ranges = [
        ((df_max - df_min) * i) + df_min
        for i in bounds
    ]
    styles = []
    legend = []
    for i in range(1, len(bounds)):
        min_bound = ranges[i - 1]
        max_bound = ranges[i]
        # 替换原来的RdYlGn色阶取值,使用自定义色阶
        backgroundColor = custom_colors[i-1]
        color = 'black'

        for column in df_numeric_columns:
            styles.append({
                'if': {
                    'filter_query': (
                        '{{{column}}} >= {min_bound}' +
                        (' && {{{column}}} < {max_bound}' if (i < len(bounds) - 1) else '')
                    ).format(column=column, min_bound=min_bound, max_bound=max_bound),
                    'column_id': column
                },
                'backgroundColor': backgroundColor,
                'color': color
            })
        legend.append(
            html.Div(style={'display': 'inline-block', 'width': '60px'}, children=[
                html.Div(
                    style={
                        'backgroundColor': backgroundColor,
                        'borderLeft': '1px rgb(50, 50, 50) solid',
                        'height': '10px'
                    }
                ),
                html.Small(round(min_bound, 2), style={'paddingLeft': '2px'})
            ])
        )

    return (styles, html.Div(legend, style={'padding': '5px 0 5px 0'}))

可调优化项

  • 如果你修改了n_bins的数值,对应调整custom_colors列表的长度和颜色取值即可
  • 可以更换颜色的十六进制值,调整红色、绿色的深浅和过渡段的颜色效果

内容的提问来源于stack exchange,提问作者FlyUFalcon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 22:30:06