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

Matplotlib同画布多子图表格单元格文本字号修改问题咨询

问题原因

Matplotlib 的表格对象默认开启了字号自动适配逻辑,会根据单元格的尺寸自动调整文本大小,你手动设置的字号会被该逻辑覆盖,和是否在子图场景下使用无关。

解决方法

在调用set_fontsize之前,先关闭表格的自动字号适配即可,如果调整字号后单元格显示拥挤,可以调用scale方法缩放单元格尺寸适配文本。

修正后可正常运行的代码如下:

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt

figure = plt.figure(figsize=(11, 5.5))
grid = figure.add_gridspec(2, 2)

ax1 = figure.add_subplot(grid[0, 0])
ax2 = figure.add_subplot(grid[1, 0])
ax3 = figure.add_subplot(grid[0, 1])
ax4 = figure.add_subplot(grid[1, 1])

df = pd.DataFrame(np.random.randn(5, 5))

ax1.axis('off')
t = ax1.table(cellText=df.values, colLabels=df.columns, rowLabels=df.index, loc='center')
t.auto_set_font_size(False) # 关闭自动字号适配
t.set_fontsize(14)
t.scale(1, 1.5) # 可选:纵向缩放单元格,避免文本拥挤

ax2.axis('off')
t = ax2.table(cellText=df.values, colLabels=df.columns, rowLabels=df.index, loc='center')
t.auto_set_font_size(False)
t.set_fontsize(14)
t.scale(1, 1.5)

ax3.axis('off')
t = ax3.table(cellText=df.values, colLabels=df.columns, rowLabels=df.index, loc='center')
t.auto_set_font_size(False)
t.set_fontsize(14)
t.scale(1, 1.5)

ax4.axis('off')
t = ax4.table(cellText=df.values, colLabels=df.columns, rowLabels=df.index, loc='center')
t.auto_set_font_size(False)
t.set_fontsize(14)
t.scale(1, 1.5)

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 21:48:04