2017-03-23 1 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') 

... ... 여기입니다 공간.

다양한 형태의 행운을 빕니다. 배경을 투명하게 만들뿐 아니라 (투명하지만 여전히 존재합니다).

도움을 주시면 감사하겠습니다.

답변

0

테이블이 축 안에서 작성되므로 최종 플롯 크기는 축의 크기에 따라 달라집니다. 따라서 원칙적으로 솔루션은 그림 크기를 설정하거나 축 크기를 먼저 설정하고 표를 적용 할 수 있습니다.

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

enter image description here

+0

는 두 번째 방법은 완벽하게 작동합니다! 도움을 주셔서 감사합니다, 이것은 큰 수정입니다! – halolord01

관련 문제