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

Matplotlib表格文本未居中求助:如何实现文本居中与紧凑布局

问题描述

我尝试了多种方法,但仍无法正确实现表格列中文本的居中对齐,也无法让表格布局更紧凑。恳请您提供帮助。

当前代码

plt.close()
colors = []
for _, row in mail_decision_table.iterrows():
    colors_in_column = ["aliceblue", "lightgrey"]
    if row["Decision"]=="SELL":
        colors_in_column[1] = "lightcoral"
    else:
        colors_in_column[1] = "lightgreen"
    colors.append(colors_in_column)

fig, ax = plt.subplots()
ax.axis('tight')
ax.axis('off')


the_table = ax.table(cellText = mail_decision_table.values,
    colLabels = mail_decision_table.columns,
    loc='center',
    rowLoc='center',
    colColours = ["grey","grey"],
    cellColours=colors)


for key, cell in the_table.get_celld().items():
    cell.set_linewidth(0.5)
    cell.set_linestyle("dashed")
    cell.set_edgecolor("grey")
    cell._loc = 'center'
    if key[0] ==0 :
        cell._text.set_color('white')

plt.show()

当前效果

表格效果截图

解决方案

1. 修复文本居中对齐

替换直接修改私有属性的cell._loc = 'center',改用规范的API设置文本水平+垂直居中:

cell.set_text_props(ha='center', va='center')

2. 让表格布局更紧凑

  • 给表格添加bbox=[0, 0, 1, 1]参数,让表格填满整个轴域,消除多余空白;
  • 通过the_table.set_fontsize()缩小字体,减少单元格占用空间;
  • 调整画布figsize,匹配表格内容的尺寸比例;
  • 调用plt.tight_layout()优化整体布局。

修改后的完整代码:

plt.close()
colors = []
for _, row in mail_decision_table.iterrows():
    colors_in_column = ["aliceblue", "lightgrey"]
    if row["Decision"]=="SELL":
        colors_in_column[1] = "lightcoral"
    else:
        colors_in_column[1] = "lightgreen"
    colors.append(colors_in_column)

# 按需调整画布尺寸
fig, ax = plt.subplots(figsize=(6, 4))
ax.axis('tight')
ax.axis('off')

the_table = ax.table(
    cellText=mail_decision_table.values,
    colLabels=mail_decision_table.columns,
    loc='center',
    colColours=["grey", "grey"],
    cellColours=colors,
    bbox=[0, 0, 1, 1]  # 让表格完全填充轴域
)

# 设置字体大小,压缩布局
the_table.set_fontsize(10)

for key, cell in the_table.get_celld().items():
    cell.set_linewidth(0.5)
    cell.set_linestyle("dashed")
    cell.set_edgecolor("grey")
    # 规范设置文本居中
    cell.set_text_props(ha='center', va='center')
    if key[0] == 0:
        cell._text.set_color('white')

plt.tight_layout()
plt.show()

内容的提问来源于stack exchange,提问作者Finance Guy Wanna Code

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 21:10:21