[英]Saving matplotlib table creates a lot of whitespace
我正在使用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
而沒有運氣,以及使背景透明(它變得透明,但仍然存在)。
任何幫助將不勝感激。
由於表是在軸內創建的,因此最終的繪圖大小將取決於軸的大小。 所以原則上解決方案可以是設置圖形尺寸或首先設置軸尺寸,讓表適應它。
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.