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

如何解决Matplotlib表格与图表重叠的布局问题?

解决Matplotlib表格与柱状图重叠的整洁布局方法

方法1:手动调整坐标轴位置

直接压缩柱状图所在坐标轴的宽度,给右侧表格预留空间,操作简单快速:

import matplotlib.pyplot as plt
import seaborn as sns

plt.figure(figsize=(9, 5), dpi=300)
ax = sns.barplot(
    x=range(1, 3),
    y=[15, 30],
    legend=False,
)
# 调整坐标轴位置:[左偏移, 下偏移, 宽度, 高度],缩小宽度给表格腾空间
ax.set_position([0.1, 0.1, 0.6, 0.8])
plt.table(cellText=['A','B','C'], rowLabels=['X','Y','Z'], colWidths=[0.15], loc='right')
plt.show()

方法2:使用GridSpec分区域布局

通过网格布局将图表和表格分配到独立区域,排版更规整,无需手动调试边界:

import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.gridspec import GridSpec

fig = plt.figure(figsize=(9, 5), dpi=300)
# 创建1行2列的网格,图表与表格宽度占比8:2
gs = GridSpec(1, 2, width_ratios=[8, 2])

# 第一列绘制柱状图
ax = fig.add_subplot(gs[0])
sns.barplot(x=range(1, 3), y=[15, 30], legend=False, ax=ax)

# 第二列放置表格,隐藏该区域的坐标轴
table_ax = fig.add_subplot(gs[1])
table_ax.axis('off')
plt.table(cellText=['A','B','C'], rowLabels=['X','Y','Z'], colWidths=[0.5], loc='center', ax=table_ax)

plt.tight_layout()
plt.show()

方法3:动态计算表格边界框

基于坐标轴位置自动计算表格的bbox参数,适配不同图表尺寸,避免手动试值:

import matplotlib.pyplot as plt
import seaborn as sns

plt.figure(figsize=(9, 5), dpi=300)
ax = sns.barplot(
    x=range(1, 3),
    y=[15, 30],
    legend=False,
)
# 获取当前坐标轴的位置信息
ax_pos = ax.get_position()
# 计算表格的边界框:[左, 下, 宽, 高],与坐标轴底部对齐,右侧留出间隙
table_bbox = [ax_pos.x1 + 0.02, ax_pos.y0, 0.15, ax_pos.height]
plt.table(cellText=['A','B','C'], rowLabels=['X','Y','Z'], colWidths=[0.8], bbox=table_bbox)
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 08:27:39