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

Matplotlib如何为表格指定列范围添加颜色并跳过文本列

问题描述

为Matplotlib表格添加colormap时,全数值数据场景下功能可正常运行,但当表格包含一列全为文本内容的STRINGS列时程序运行崩溃,触发报错:
TypeError: '<' not supported between instances of 'int' and 'str'
需要实现colormap映射时自动跳过文本列的效果。

原错误实现代码如下:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import colors
from matplotlib.colors import ListedColormap

# define figure and axes
fig, ax = plt.subplots()

# hide the axes
fig.patch.set_visible(False)
ax.axis('off')
ax.axis('tight')

# create data
df = pd.DataFrame({
    'STRINGS': ['STRING1', 'STRING2', 'STRING3', 'STRINGS4', 'STRINGS5'],
    'Success Rate 1': [95, .02, -.03, 92, .05],
    'Success Rate 2': [-95, .06, .03, 92, .05]
})

#Colors
red_green = ListedColormap(['red', '#70e000', '#38b000'])
bounds = [-20, 0, 1, 100]
norm = colors.BoundaryNorm(bounds, red_green.N)

# create table
matplotlib_table = plt.table(
    cellText=df.values,
    colLabels=df.columns,
    loc='center',
    cellColours=red_green(norm(df.values)) # 直接传入含字符串的全量数据触发报错
)

# display table
fig.tight_layout()
plt.show()

运行效果预期参考:
带colormap的表格运行效果

报错原因

原代码直接将包含字符串的全量DataFrame数组传入归一化、颜色映射流程,字符串类型无法参与数值大小比较逻辑,因此触发类型错误。

修复方案
  • 先创建和表格尺寸一致的颜色数组,文本列默认设置为白色背景
  • 自动筛选所有数值类型的列,仅对这部分列执行colormap映射,将映射结果填充到颜色数组的对应位置
  • 将构造完成的颜色数组传入cellColours参数即可

修复后的完整可运行代码:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import colors
from matplotlib.colors import ListedColormap

# 定义画布和轴
fig, ax = plt.subplots()

# 隐藏默认坐标轴
fig.patch.set_visible(False)
ax.axis('off')
ax.axis('tight')

# 构造测试数据
df = pd.DataFrame({
    'STRINGS': ['STRING1', 'STRING2', 'STRING3', 'STRINGS4', 'STRINGS5'],
    'Success Rate 1': [95, .02, -.03, 92, .05],
    'Success Rate 2': [-95, .06, .03, 92, .05]
})

# 定义colormap和归一化规则
red_green = ListedColormap(['red', '#70e000', '#38b000'])
bounds = [-20, 0, 1, 100]
norm = colors.BoundaryNorm(bounds, red_green.N)

# 初始化单元格颜色数组,默认所有单元格为白色背景
cell_colors = np.full((df.shape[0], df.shape[1]), fill_value='white', dtype=object)
# 自动筛选所有数值列,无需硬编码要跳过的文本列名
numeric_cols = df.select_dtypes(include='number').columns
# 获取数值列在DataFrame中的位置索引
numeric_col_idx = [df.columns.get_loc(col) for col in numeric_cols]
# 仅对数值列应用颜色映射
cell_colors[:, numeric_col_idx] = red_green(norm(df[numeric_cols].values))

# 生成表格
matplotlib_table = plt.table(
    cellText=df.values,
    colLabels=df.columns,
    loc='center',
    cellColours=cell_colors
)

# 展示表格
fig.tight_layout()
plt.show()

该写法无需手动指定要跳过的文本列名,会自动识别所有数值列做映射,后续新增/删除文本列也不需要修改颜色映射逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 02:48:39