保存 matplotlib 表格会创建很多空白空间

8

我正在使用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')

这会生成像这样的一张图片... 你可以看到周围有白色空间

奇怪的是,使用plt.show()会在GUI中显示表格而没有白边。

我尝试使用多种形式的tight_layout=True,但都没成功,还尝试过将背景设置成透明(虽然变成了透明但依旧存在)。

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

1个回答

12

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

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

另一种解决方案是让表格保持原状,并在保存前找出表格的边框框。这样可以创建一个真正紧贴表格的图像。

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()

在此输入图片描述


1
第二种方法完美地运作了!感谢您的帮助,这是一个巨大的修复! - halolord01

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接