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

Matplotlib绘制表格无法显示全部预期行的问题求助

解决Matplotlib表格无法显示全部行的问题

问题描述

我尝试用Python的Matplotlib库创建表格,代码如下:

# -*- coding: utf-8 -*-
import sys
import matplotlib.pyplot as plt 

val1 = ["ABC", "CDE", "AEX", "SM12", "AEX", "AEX", "AEX", "AEX", "AEX", "AEX", "AEX", "AEX", "AEX", "ABC", "AEF", "AEF", "SC", "SV", "JAVA", "TBS", "AEF", "AEF", "AEF", "ABC"]
val2 = ["KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "LOL"]
val3 = [["" for c in range(24)] for r in range(35)] 
def cration_tableau():
    creation_of_table = True
    fig, ax = plt.subplots() 
    ax.set_axis_off() 
    table = ax.table( 
        cellText = val3,  
        rowLabels = val2,  
        colLabels = val1, 
        rowColours = ["palegreen"] * 35,  
        colColours = ["palegreen"] * 24, 
        cellColours = [["grey"] * 24] * 35,
        cellLoc ='center',  
        loc ='upper left') 
    ax.set_title('DATA TABLE', fontweight ="bold") 
    plt.show()
    
def main():
    tab = cration_tableau()

if __name__ == '__main__':
   main()

问题在于:val2列表包含35行数据,但表格仅显示到索引24的行,无法展示全部内容。

解决方案

核心问题是默认图表尺寸不足以容纳所有行,通过调整图表大小、行高和布局即可解决:

1. 调整图表尺寸并设置行缩放比例

创建子图时指定更大的高度(根据行数调整),同时用table.scale()放大行高,避免内容拥挤。

2. 自动适配布局

调用plt.tight_layout()让图表元素自动调整位置,防止内容被裁剪。

修改后的完整代码:

# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt 

val1 = ["ABC", "CDE", "AEX", "SM12", "AEX", "AEX", "AEX", "AEX", "AEX", "AEX", "AEX", "AEX", "AEX", "ABC", "AEF", "AEF", "SC", "SV", "JAVA", "TBS", "AEF", "AEF", "AEF", "ABC"]
val2 = ["KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "KPG", "LOL"]
val3 = [["" for c in range(24)] for r in range(35)] 

def cration_tableau():
    # 调整图表尺寸,高度设为18以容纳35行
    fig, ax = plt.subplots(figsize=(12, 18)) 
    ax.set_axis_off() 
    table = ax.table( 
        cellText = val3,  
        rowLabels = val2,  
        colLabels = val1, 
        rowColours = ["palegreen"] * 35,  
        colColours = ["palegreen"] * 24, 
        cellColours = [["grey"] * 24] * 35,
        cellLoc ='center',  
        loc ='upper left') 
    # 放大行高,提升可读性
    table.scale(1, 1.2)
    ax.set_title('DATA TABLE', fontweight ="bold") 
    # 自动调整布局,避免内容被裁剪
    plt.tight_layout()
    plt.show()
    
def main():
    tab = cration_tableau()

if __name__ == '__main__':
   main()

额外优化(可选)

如果自动布局仍有问题,可手动调整图表边界:

plt.subplots_adjust(left=0.1, bottom=0.05, top=0.95)

通过调整left、bottom、top参数,给表格留出足够的显示空间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:05:18