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

如何调整Matplotlib表格周围空白匹配尺寸,修复标题错位并居中

Matplotlib表格空白消除与标题居中解决方案

针对表格周围多余空白、标题错位覆盖、无法居中的问题,可通过以下调整彻底解决:

核心修改点

  • 合理计算画布尺寸,预留标题垂直空间
  • 让轴自适应表格大小,消除内部空白
  • 微调标题位置,避免与表格重叠
  • 优化布局边距,清除画布边缘空白

修改后的完整代码

import matplotlib.pyplot as plt
import pandas as pd

def create_pivot_table(
        title: str,
        pivot_table: pd.core.frame.DataFrame,
):
    \"\"\"
    Creates a Matplotlib table from a Pandas pivot table.
    Returns fig and ax.
    \"\"\"
    # 计算画布尺寸,额外预留标题的垂直空间
    fig_width = 1 + len(pivot_table.columns) * 0.6
    fig_height = 1 + len(pivot_table) * 0.3 + 0.6  # 新增标题区域空间
    figsize=(fig_width, fig_height)
    fig, ax = plt.subplots(figsize=figsize)

    # 设置标题,调整垂直位置避免覆盖表格
    ax.set_title(
        title,
        fontsize=16,
        weight='bold',
        loc='center',
        y=1.02  # 标题上移,与表格拉开距离
    )
    ax.axis('off')

    table = ax.table(
        cellText=pivot_table.values,
        colLabels=pivot_table.columns,
        rowLabels=pivot_table.index,
        cellLoc='center',
        loc='center'
    )

    table.auto_set_font_size(False)

    # 保留原表格样式逻辑
    for (row, column), cell in table.get_celld().items():
        if row == 0:
            cell.set_text_props(weight='bold')
            cell.set_fontsize(8)
            cell.set_height(0.05)

            if column % 2 == 0:
                cell.set_facecolor('#dadada')
            else:
                cell.set_facecolor('#ffffff')
        else:
            cell.set_fontsize(10)
            cell.set_height(0.03)

            if row % 2 == 0:
                cell.set_facecolor('#ffffff')
            else:
                cell.set_facecolor('#e6f7ff')

            if column % 2 == 0:
                cell.set_facecolor('#dadada' if row % 2 == 0 else '#b9d5d3')
            else:
                cell.set_facecolor('#ffffff' if row % 2 == 0 else '#e6f7ff')

    # 让轴自适应表格尺寸,消除内部空白
    ax.autoscale()
    # 调整画布边距,清除边缘空白并保证居中
    plt.subplots_adjust(left=0.05, right=0.95, top=0.9, bottom=0.05)

    return fig, ax

测试代码

import pandas as pd
import numpy as np

# 测试35行数据,验证标题不覆盖问题
data = np.random.randint(1, 100, size=(35, 4))
df = pd.DataFrame(data, index=[f'Row{i}' for i in range(35)], columns=[1, 2, 3, 4])

title = '测试表格标题'

fig, ax = create_pivot_table(
    title=title,
    pivot_table=df
)
plt.show()

调整说明

  1. 画布高度优化:在fig_height中增加0.6的空间,确保标题不会挤压表格区域
  2. 标题位置微调:通过y=1.02将标题向上偏移,既保持居中又避免覆盖表格顶部
  3. 轴自适应:ax.autoscale()让轴的范围完全适配表格大小,消除画布内的多余空白
  4. 边距调整:subplots_adjust精准控制画布边缘空白,确保表格和标题整体居中显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 09:03:10