2017-03-23 2 views
1

私はmatplotlibとpython 2.7を使ってテーブルを作成しています。テーブルを保存すると、テーブルが1〜2行だけであっても、画像は正方形になり、後で自動生成されたPDFに後で追加すると空きスペースが多くなります。 は、私は、コードを使用している方法の例は、plt.show()を使用して You can see you can see the white space around itmatplotlibテーブルを保存するとたくさんの空白が作成されます

変なふうには白いずにGUIでテーブルを作成

これは、このような画像を生成
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') 

... ...ここにありますスペース。

さまざまな形のtight_layout=Trueを使ってみましたが、バックグラウンドを透明にする(透明になりましたが、まだそこにあります)。

ご協力いただければ幸いです。

答えて

0

テーブルは軸内に作成されるので、最終的なプロットサイズは軸のサイズに依存します。ですから、原理的には、Figureのサイズを設定するか、最初にAxesのサイズを設定して、テーブルをそれに適応させることができます。

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

別の解決策は、そのままテーブルが描画させて、保存する前に、テーブルのバウンディングボックスを見つけることです。これは、テーブルの周りに本当にタイトなイメージを作成することができます。第2の方法は完璧に動作することを

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

+0

!助けてくれてありがとう、これは巨大な修正です! – halolord01

関連する問題