由于表格是在轴内创建的,因此最终的绘图大小将取决于轴的大小。所以原则上一个解决方案可以是设置图形大小或先设置轴大小,然后让表格适应它。
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()
另一种解决方案是让表格按原样绘制,并在保存之前找出表格的边界框。这允许创建一个在桌子周围非常紧凑的图像。
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()