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不同?我找不到与dpi相关的方法或matplotlib.table.Table类的属性。

认真的重要性

默认情况下,单元格的宽度会自动调整为适合轴的宽度(如果为)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()

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章