首页 > 解决方案 > matplotlib中表格和图形大小之间的关系

问题描述

我无法弄清楚如何“同步”表格和图形的大小,以便表格完全位于图形内。

import matplotlib.pyplot as plt
from string import ascii_uppercase
from random import choice

#content for the table
height = 9
width = 9
grid = [[choice(ascii_uppercase) for j in range(width)] for i in range(height)]

#desired size of a cell
cell_size = 0.3

fig = plt.figure(figsize=(width * cell_size, height * cell_size))
ax = fig.add_subplot(1, 1, 1)

the_table = ax.table(cellText=grid, loc='center')

for pos, cell in the_table._cells.items():
    cell._height = cell._width = cell_size

plt.show()

输出

我的理解是轴内的区域(+一些外边距)图形 - 当我将它保存为图像文件时,它只保存这个区域,裁剪所有其余部分,并且图像的大小为 194x194,匹配图形大小和 DPI:

fig.get_size_inches()
>>array([2.7, 2.7])
fig.dpi
>>72.0

所以我想我的问题是当我在表格中设置单元格大小时,它不是以英寸为单位(与图形大小相同)吗?还是表的 DPI 不同?我找不到 matplotlib.table.Table 类的任何与 dpi 相关的方法或属性。

标签: pythonmatplotlib

解决方案


默认情况下,单元格的宽度会自动调整以适应轴的宽度,如果loc="center".
剩下的就是设置单元格的高度。这是以轴坐标为单位给出的。因此,为了填充轴的完整高度(轴坐标中 == 1),您可以将 1 除以表中的行数以获得每个单元格的高度。然后将高度设置为所有单元格。

import matplotlib.pyplot as plt
from string import ascii_uppercase
from random import choice

#content for the table
height = 9
width = 9
grid = [[choice(ascii_uppercase) for j in range(width)] for i in range(height)]


fig, ax  = plt.subplots()
#ax.plot([0,2])

the_table = ax.table(cellText=grid, loc='center')
the_table.auto_set_font_size(False)

cell_height = 1 / len(grid)
for pos, cell in the_table.get_celld().items():
    cell.set_height(cell_height)

plt.show()

在此处输入图像描述


推荐阅读