首页 > 解决方案 > Matplotlib 表格大小和位置

问题描述

我正在尝试制作一个尺寸为 Nx7 的表格,其中 N 是一个变量。
通过 matplotlib 制作合适大小的表格非常具有挑战性。
我想把它放在情节的中心,标题就在桌子的正上方。
这是我的代码

data = [
   ['A', 'B', 'C', 'D', 'E', 'F'],
   ['100%', '200%', 'O', 'X', '1.2%', '100', '200'],
   ['100%', '200%', 'O', 'X', '1.2%', '100', '200'],
   ['100%', '200%', 'O', 'X', '1.2%', '100', '200'],
   ['100%', '200%', 'O', 'X', '1.2%', '100', '200'],
   ['100%', '200%', 'O', 'X', '1.2%', '100', '200']]

fig, ax1 = plt.subplots(dpi=200)

column_headers = data.pop(0)
row_headers = [x.pop(0) for x in data]
rcolors = np.full(len(row_headers), 'linen')
ccolors = np.full(len(column_headers), 'lavender')

cell_text = []
for row in data:
    cell_text.append([x for x in row])

table = ax1.table(cellText=cell_text,
                  cellLoc='center',
                  rowLabels=row_headers,
                  rowColours=rcolors,
                  rowLoc='center',
                  colColours=ccolors,
                  colLabels=column_headers,
                  loc='center')
fig.tight_layout()

table.scale(1, 0.5)
table.set_fontsize(16)
# Hide axes
ax1.get_xaxis().set_visible(False)
ax1.get_yaxis().set_visible(False)

# Add title
ax1.set_title('{}\n({})'.format(title, subtitle), weight='bold', size=14, color='k')

fig.tight_layout()
plt.savefig(filename)

在我的代码中,有几个问题。

  1. 标题重叠在桌子上。
  2. 整个数字不知何故从中心向右移动。(结果图像的左侧被空白区域填充)
  3. 表格中文字的大小不是16。(比标题小很多)

谢谢你。

标签: matplotlib

解决方案


这是一些绘制表格的代码。

一些评论:

  • 在 matplotlib 中的支持table是相当基本的。它主要用于在现有绘图上以表格形式添加一些文本。
  • 使用.pop()使代码难以推理。在 Python 中,通常从给定列表开始创建新列表。
  • 由于绘图的足够大小高度取决于行数,因此可以将其计算为某个倍数。确切的值取决于完整的表格,尝试一下是有意义的。下面的值似乎适用于给定的示例数据。
  • dpitight边界框可以设置为参数savefig()
  • 不同的 matplotlib 版本的行为可能略有不同。下面的代码是用 matplotlib 3.3.3 测试的。
import numpy as np
import matplotlib.pyplot as plt

N = 10
data = [['A', 'B', 'C', 'D', 'E', 'F']] + [['100%', '200%', 'O', 'X', '1.2%', '100', '200']] * N
column_headers = data[0]
row_headers = [row[0] for row in data[1:]]
cell_text = [row[1:] for row in data[1:]]

fig, ax1 = plt.subplots(figsize=(10, 2 + N / 2.5))

rcolors = np.full(len(row_headers), 'linen')
ccolors = np.full(len(column_headers), 'lavender')

table = ax1.table(cellText=cell_text,
                  cellLoc='center',
                  rowLabels=row_headers,
                  rowColours=rcolors,
                  rowLoc='center',
                  colColours=ccolors,
                  colLabels=column_headers,
                  loc='center')
table.scale(1, 2)
table.set_fontsize(16)
ax1.axis('off')
title = "demo title"
subtitle = "demo subtitle"
ax1.set_title(f'{title}\n({subtitle})', weight='bold', size=14, color='k')

plt.savefig("demo_table.png", dpi=200, bbox_inches='tight')

示例图


推荐阅读