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

如何设置Matplotlib中行标签(rowLabels)列的宽度?代码设置无效

解决Matplotlib表格行标签列宽度无法设置的问题

Matplotlib中,colWidths参数仅作用于数据列和列标签对应的列,不包含行标签列;直接遍历所有单元格设置set_width时,行标签列的宽度会被自动布局逻辑覆盖,导致设置无效。

解决方案

通过单元格位置索引筛选出行标签列(索引为-1的列),单独设置其宽度,同时可通过set_bbox调整表格整体布局,避免宽度被挤压:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.axis('tight')
ax.axis('off')
colLabels = ['ColA', 'ColB', 'ColC', 'ColD', 'ColE']
rowLabels = ['Row1', 'Row2', 'Row3', 'Row4']
dados = [
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10],
    [11, 12, 13, 14, 15],
    [16, 17, 18, 19, 20],
]
table = ax.table(
    cellText=dados, loc='center', 
    colLabels=colLabels, 
    rowLabels=rowLabels
)

# 分别设置数据列和行标签列的宽度
for cell in table.get_celld().values():
    cell_loc = cell.get_loc()
    if cell_loc[1] != -1:
        # 数据列与列标签列设置宽度
        cell.set_width(0.15)
    else:
        # 行标签列单独设置宽度
        cell.set_width(0.2)

# 手动调整表格在轴域内的位置与大小,确保宽度生效
table.set_bbox([0.1, 0.1, 0.8, 0.8])

plt.show()

关键说明

  • 行标签列的单元格位置为(行号, -1),通过cell.get_loc()[1] == -1可精准筛选该行标签单元格。
  • set_bbox参数格式为[left, bottom, width, height],取值范围0-1,对应轴域的相对位置,可根据需求调整,避免表格布局挤压导致宽度设置失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 17:01:25