如何在满足指定条件时修改matplotlib表格整行的文本颜色
pandas DataFrame转matplotlib表格整行样式设置方案
需求调整说明
原有实现仅能对包含uptrend/downtrend关键字的单个单元格设置文本样式:
- 包含
uptrend的单元格文本设为绿色粗体 - 包含
downtrend的单元格文本设为红色粗体
调整后需求为:只要某行内任意一个单元格匹配上述关键字,整行所有单元格文本都按照对应规则统一样式。
核心修改逻辑
先提前遍历所有数据行,预标记每行对应的样式属性,后续设置单元格样式时直接按行标记统一赋值即可,无需逐个单元格判断内容。
完整可运行代码
import pandas as pd import numpy as np import matplotlib.pyplot as plt import six trend = ['uptrend', 'downtrend', '10 uptrend', '20 downtrend'] value = ['10', '20', '30', '50'] df = pd.DataFrame({'Trend':trend, 'Value':value}) def render_mpl_table(data, col_width=3.0, row_height=0.625, font_size=14, header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w', bbox=[0, 0, 1, 1], header_columns=0, ax=None, **kwargs): if ax is None: size = (np.array(data.shape[::-1]) + np.array([0, 1])) * np.array([col_width, row_height]) fig, ax = plt.subplots(figsize=size) ax.axis('off') mpl_table = ax.table(cellText=data.values, bbox=bbox, colLabels=data.columns, **kwargs) mpl_table.auto_set_font_size(False) mpl_table.set_fontsize(font_size) # 新增:预标记每行对应的样式 row_styles = {} # 行号从1开始,0为表头行 for row_idx in range(1, len(data) + 1): has_uptrend = False has_downtrend = False # 遍历当前行所有列判断是否包含关键字 for col_idx in range(len(data.columns)): cell_text = mpl_table._cells[(row_idx, col_idx)].get_text().get_text() if 'uptrend' in cell_text: has_uptrend = True if 'downtrend' in cell_text: has_downtrend = True # 存储当前行样式配置 if has_uptrend: row_styles[row_idx] = {'weight': 'bold', 'color': 'g'} elif has_downtrend: row_styles[row_idx] = {'weight': 'bold', 'color': 'r'} else: row_styles[row_idx] = {} for k, cell in six.iteritems(mpl_table._cells): cell.set_edgecolor(edge_color) if k[0] == 0 or k[1] < header_columns: cell.set_text_props(weight='bold', color='w') cell.set_facecolor(header_color) else: cell.set_facecolor(row_colors[k[0]%len(row_colors) ]) # 替换原单个单元格判断逻辑,按行标记设置样式 if k[0] in row_styles and row_styles[k[0]]: cell.set_text_props(**row_styles[k[0]]) return ax render_mpl_table( df, header_columns=0, header_color='#40466e', edge_color='grey', row_height = 1, col_width=2.5 ) plt.show()
内容的提问来源于stack exchange,提问作者SamuraiSam
相关产品推荐
相关产品推荐

