python - 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 相关的方法或属性。
解决方案
默认情况下,单元格的宽度会自动调整以适应轴的宽度,如果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()
推荐阅读
- sql - 在存储过程中从另一个数据库访问表
- java - Tomcat更改配置后加载时间长
- python - 如何修复 python 脚本中的“int <> 以 10 为底的无效文字”错误
- c# - 找出字符串列表是否包含来自另一个字符串的单词排列(每个组合的计数器)
- javascript - 如何为特定网站添加网站点击计数器
- javascript - 为什么我的 javascript 函数不能在整个页面中运行
- docker - 使用 Docker 时将配置/数据部署到卷
- sql - 转换 SQL 查询联合的数据类型的问题
- entity-framework - 无法跟踪 ASP.Net Core EF MM 实例
- python - 以第一行格式从 Mongodb 集合中检索记录