2017-12-18 258 views
1

我必須在Python中繪製表格圖並將此表保存爲jpeg/png。然後在郵件中使用這個圖像。問題是我在圖表的頂部和底部獲得了空白區域。代碼我用來實現這一目標:頂部和底部的白色空間Python matplotlib圖

nrows, ncols = len(df)+1, len(df.columns) 
hcell, wcell = 0.5, 1.5 
hpad, wpad = 0, 0 
fig, ax = plt.subplots(figsize=(ncols*wcell+wpad, nrows*hcell+hpad)) 

ax.axis('off') 
ax.axis('tight') 
ax.xaxis.set_visible(False) 
ax.yaxis.set_visible(False) 

ax.table(cellText=df.values, colLabels=df.columns, loc='center') 
fig.savefig('table1.png', bbox_inches='tight') 

輸出: tabular table 另外,我想給圖表的標題到頂部和左側。 'Some text Here'是標題,黃線顯示我想要另一個標題的位置。 所需的輸出沒有額外的空白在頂部。 Desired

+1

你可能想給我們一個工作示例,所以我們可以複製你的情況,以及它的工作。 – IMCoins

+0

我給了代碼。數據可以複製。 –

+0

答案已經給出wtf – IMCoins

回答

2

一個選項是指定表​​格的邊框作爲保存圖形時要使用的邊框。

from matplotlib import pyplot as plt 

fig, ax = plt.subplots() 

colums = ['col1', 'col2'] 
rows = ['row1', 'row2'] 
values = [[0, 1], [1, 0]] 
table = ax.table(cellText=values, colLabels=colums, rowLabels=rows, loc='center') 

ax.axis('off') 

fig.canvas.draw() 
bbox = table.get_window_extent(fig.canvas.get_renderer()) 
bbox_inches = bbox.transformed(fig.dpi_scale_trans.inverted()) 

fig.savefig('plop.png', bbox_inches=bbox_inches) 

plt.show() 

enter image description here

在這種情況下,外線croped因爲線延伸到其位置的兩側。人們仍然可以在表格周圍添加一些填充。例如。有5個像素填充,

bbox = table.get_window_extent(fig.canvas.get_renderer()) 
bbox = bbox.from_extents(bbox.xmin-5, bbox.ymin-5, bbox.xmax+5, bbox.ymax+5) 
bbox_inches = bbox.transformed(fig.dpi_scale_trans.inverted()) 

enter image description here

+0

謝謝,愛你。 – IMCoins

0

我不認爲你可以刪除表格上方和下方的空格。 Reading the documentation,你已經有最高你將永遠實現。

bbox_inches:STR或B-盒,可選

B-盒英寸。只有該圖的給定部分被保存。如果「緊」,試圖找出數字的緊密bbox。如果沒有,使用savefig.bbox

不過,我已經爲你設置正確的行和列的工作示例。 下面是圖片後面的代碼。

from matplotlib import pyplot as plt 

fig = plt.figure() 
ax = fig.add_subplot(1, 1, 1) 

colums = ['col1', 'col2'] 
rows = ['row1', 'row2'] 
values = [[0, 1], [1, 0]] 
ax.table(cellText=values, colLabels=colums, rowLabels=rows, loc='center') 

ax.axis('off') 
ax.xaxis.set_visible(False) 
ax.yaxis.set_visible(False) 

fig.savefig('plop.png', bbox_inches='tight') 

Result

我強烈建議您調整軸/圖設置後您的情節完全抽出。

+0

當然,你可以擺脫空白,但'bbox_inches ='tight''不會有太大的幫助。只要問題顯示[mcve],我很樂意提供一個答案顯示如何。 – ImportanceOfBeingErnest

+0

我很想知道你會怎麼做。我能找到的唯一方法是使用[Bbox](https://matplotlib.org/api/transformations.html#matplotlib.transforms.Bbox)實例,但我沒有時間來封裝其功能馬上。如果你能夠給我一個直接的信息和我應該研究的選項,我會很高興。 – IMCoins

+0

好吧,我把你的例子用於使用'bbox_inches'的答案。當然還有其他的選擇,比如讓桌子和桌子一樣大。 – ImportanceOfBeingErnest