gpt4 book ai didi

python - 保存 matplotlib 表会产生大量空白

转载 作者:太空狗 更新时间:2023-10-30 02:55:17 24 4
gpt4 key购买 nike

我正在使用 matplotlib 和 python 2.7 创建一些表格。当我保存表格时,图像是正方形的,即使表格只有 1 - 2 行,当我稍后将它们添加到自动生成的 PDF 时会产生很多空白空间。我如何使用代码的示例在这里...

import matplotlib.pyplot as plt

t_data = ((1,2), (3,4))
table = plt.table(cellText = t_data, colLabels = ('label 1', 'label 2'), loc='center')
plt.axis('off')
plt.grid('off')
plt.savefig('test.png')

这会产生这样的图像...... You can see you can see the white space around it

奇怪地使用 plt.show() 在 GUI 中生成没有空格的表格。

我试过使用各种形式的 tight_layout=True 但没有成功,也尝试过使背景透明(它变得透明,但仍然存在)。

如有任何帮助,我们将不胜感激。

最佳答案

由于表格是在轴内创建的,因此最终绘图大小将取决于轴的大小。所以原则上一个解决方案可以是要么设置图形大小,要么先设置轴大小,让表格适应它。

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(6,1))

t_data = ((1,2), (3,4))
table = plt.table(cellText = t_data,
colLabels = ('label 1', 'label 2'),
rowLabels = ('row 1', 'row 2'),
loc='center')

plt.axis('off')
plt.grid('off')

plt.savefig(__file__+'test2.png', bbox_inches="tight" )
plt.show()

enter image description here

另一种方案是让表格原样绘制,在保存前找出表格的边界框。这允许创建一个非常紧密地围绕在 table 周围的图像。

import matplotlib.pyplot as plt
import matplotlib.transforms

t_data = ((1,2), (3,4))
table = plt.table(cellText = t_data,
colLabels = ('label 1', 'label 2'),
rowLabels = ('row 1', 'row 2'),
loc='center')

plt.axis('off')
plt.grid('off')

#prepare for saving:
# draw canvas once
plt.gcf().canvas.draw()
# get bounding box of table
points = table.get_window_extent(plt.gcf()._cachedRenderer).get_points()
# add 10 pixel spacing
points[0,:] -= 10; points[1,:] += 10
# get new bounding box in inches
nbbox = matplotlib.transforms.Bbox.from_extents(points/plt.gcf().dpi)
# save and clip by new bounding box
plt.savefig(__file__+'test.png', bbox_inches=nbbox, )

plt.show()

enter image description here

关于python - 保存 matplotlib 表会产生大量空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42987799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com