Plotly Table条件格式化:为DataFrame数值设置自定义文本颜色
Plotly Table 条件格式化修正方案
问题根因
- 条件判断逻辑倒置:包含
-符号的单元格对应匹配判断返回True,原代码错误将该场景赋值为红色 - 列遍历范围错误:第一列不需要做颜色判断,原代码遍历了所有DataFrame列
- 空值场景未兼容:空单元格不需要应用红/绿着色规则
修正后完整代码
import plotly.graph_objects as go import pandas as pd d = {'col1': ['a', 'b', 'c', 'd', 'e', 'f', 'g'], 'col2': ['', '+1%', '+4%', '-6%', '', '+0%', '+5%'], 'col3': ['' , '-2%', '+0%', '+9%', '', '-1%', '+6%'], 'col4': ['', '-7.5%', '+3.75%', '+5.2%', '', '-2.34%', '-3.17%']} df = pd.DataFrame(d) # 生成颜色规则列表 font_color = [ # 第一列统一为黑色 ['black'] * len(df), # 从第二列开始按条件判断 *[ [ 'green' if '-' in str(v) else 'red' if str(v).strip() else 'black' for v in df[col] ] for col in df.columns[1:] ] ] table_trace = go.Table( header = dict(height = 50, values = [['<b>Col1</b>'], ['<b>Col2</b>'], ['<b>Col3</b>'], ['<b>Col4</b>']], align = ['left']*4, fill_color = '#386dea', font_color = '#fcfcfc', font_size =14), cells = dict(values = [df['col1'], df['col2'], df['col3'], df['col4']], line = dict(color='#506784'), align = ['left']*4, font_color=font_color, font_family="Arial", font_size=14, height = 30, fill = dict(color='rgb(245,245,245)')) ) layout = go.Layout(width=400, height=415, autosize=False, title_text='Table title', title_x=0.5, showlegend=False) fig = go.Figure(data=[table_trace], layout=layout) fig.show()
实现效果
- 第一列所有内容保持黑色
- 第二至第四列中,包含
-符号的数值显示为绿色 - 第二至第四列中,非空的正数值、0值显示为红色
- 空单元格保持黑色,不应用着色规则
内容的提问来源于stack exchange,提问作者Maleficent
相关产品推荐
相关产品推荐

