[英]White space on top and bottom Python matplotlib plot
我必須在Python中繪制表格圖表,然后將此表格另存為jpeg / png。 然后在郵件中使用此圖像。 問題是我在圖表的頂部和底部出現空白。 我用來實現此目的的代碼:
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')
輸出: 另外,我想將標題放在圖表的頂部和左側。 “此處有一些文字”是標題,黃線顯示了我想要其他標題的位置。 所需的輸出,頂部沒有多余的空白。
一種選擇是將表格的邊框指定為保存圖形時要使用的邊框。
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()
在這種情況下,外部線將被裁剪,因為該線延伸到其位置的兩側。 您可能仍會在桌子周圍添加一些填充。 例如具有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())
我認為您無法刪除表格上方和下方的空白。 閱讀文檔 ,你已經擁有你永遠不會實現tighest。
bbox_inches:str或Bbox,可選
Bbox英寸。 僅保存圖的給定部分。 如果“太緊”,請嘗試找出該圖的緊緊bbox。 如果為None,請使用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')
我強烈建議您在繪圖完全繪制后調整軸/圖形設置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.