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

如何使用Python3的matplotlib.pyplot在表格左上角空白处添加表格名称

How to Add Table Names to the Top-Left Blank Cell in Matplotlib Tables

I get it—you've got these nicely formatted tables in matplotlib, but that empty top-left cell is begging for a table name. Here's a straightforward way to fill that spot by leveraging the table's own cell objects:

Step-by-Step Fix

When you create a table with ax.table(), the top-left blank area corresponds to the cell at index (0, 0) in the table's cell grid. We can directly modify this cell to add your table name and style it as needed.

Here's your modified code with the table name functionality added:

import matplotlib.pyplot as plt
data = [
    [100, 150, 50, 200],
    [200, 150, 150, 300],
    [50, 50, 50, 300],
    [50, 90, 80, 70],
]
col_labels = ['bbbbbbbbb1', 'bbbbbbbbb2', 'bbbbbbbbb3', 'bbbbbbbbb4']
row_labels = ['aaaaaaaa1', 'aaaaaaaa2', 'aaaaaaaa3', 'aaaaaaaa4']
low = 100
mid = 160
high = 200
cell_text = list()
cell_colors = list()
for row in data:
    row_text = list()
    row_color = list()
    for val in row:
        row_text.append('%.1f' % val)
        if val < low:
            color = 'g'
        elif low <= val < mid:
            color = 'y'
        elif mid <= val < high:
            color = 'b'
        else: # val >= high
            color = 'r'
        row_color.append(color)
    cell_text.append(row_text)
    cell_colors.append(row_color)
n = 5
fig, axs = plt.subplots(n, 1)
for i in range(n):
    axs[i].axis('off')
    # Assign the table to a variable to access its cells
    tbl = axs[i].table(
        cellText=cell_text,
        colLabels=col_labels,
        rowLabels=row_labels,
        cellColours=cell_colors,
        loc='center',
    )
    table_name = f'TableName {i}'
    # Target the top-left cell and add the table name
    top_left_cell = tbl[(0, 0)]
    top_left_cell.set_text_props(text=table_name, weight='bold', ha='center', va='center')
    # Optional: Add a background color to make the name stand out
    # top_left_cell.set_facecolor('#f5f5f5')
plt.tight_layout()
plt.show()

Key Details

  • We store the table object in tbl when creating it—this lets us interact with its individual cells.
  • The (0, 0) cell is the empty intersection of row labels and column labels. Using set_text_props(), we add the name and style it (bold text, centered alignment in this example).
  • Uncomment the optional line if you want to add a light background color to make the table name more prominent.

This approach keeps the name integrated directly into the table structure, which looks cleaner than adding a separate text box nearby.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 09:29:04