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

如何让Matplotlib图表尺寸匹配Pandas DataFrame生成的表格?

解决Matplotlib表格与图表尺寸不匹配问题

需求:编写函数接收行数1至25的Pandas DataFrame,生成匹配尺寸的Matplotlib表格图表,当前存在图表与表格尺寸不匹配的问题,尝试过调整坐标轴、图表frame、尺寸、tight_layout()等方法均无效。

原代码:

def create_table_fig(df):
    fig = plt.figure(frameon = False)
    table = plt.table(cellText = df.values, colLabels = df.columns, fontsize = 'large', loc = 'lower left')
    table.auto_set_column_width(col=list(range(len(df.columns))))
    table.set_figure(fig)
    plt.close()
    
    return fig

测试代码:

data = {'Name': ['Alice', 'Bob', 'Charlie', 'Dave'],
    'Age': [25, 30, 35, 40],
    'Salary': [50000, 60000, 70000, 80000]}
df = pd.DataFrame(data)
table = create_table_fig(df)
table

当前效果:
当前效果
期望效果:
期望效果


修正后的代码

import matplotlib.pyplot as plt
import pandas as pd

def create_table_fig(df):
    # 创建图表和坐标轴,隐藏坐标轴消除多余空白
    fig, ax = plt.subplots(frameon=False)
    ax.axis('off')
    
    # 创建表格,设置bbox让表格填满整个坐标轴区域
    table = ax.table(
        cellText=df.values,
        colLabels=df.columns,
        fontsize='large',
        bbox=[0, 0, 1, 1]  # 左、下、宽、高参数,让表格占满坐标轴
    )
    
    # 自动调整列宽适配内容
    table.auto_set_column_width(col=list(range(len(df.columns))))
    
    # 根据表格行数、列数动态计算图表尺寸
    row_height = 0.3
    col_width = 1.2
    # +1是为表头预留高度
    fig.set_size_inches(col_width * len(df.columns), row_height * (len(df) + 1))
    
    plt.close()
    return fig

关键改动说明

  • 创建并隐藏坐标轴:避免默认坐标轴的空白区域占用空间,让表格可以完全填充图表
  • 设置bbox=[0,0,1,1]:强制表格填满整个坐标轴区域,消除边缘空白
  • 动态计算图表尺寸:根据列数和行数(包含表头)设置图表大小,确保表格内容完全显示,适配1-25行的DataFrame
  • 使用ax.table()替代plt.table():更精准地控制表格在坐标轴内的位置

测试修正后的函数,生成的图表会和表格尺寸完全匹配,达到期望效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 02:10:16