顶部和底部Python matplotlib图上的白色空间

时间:2017-12-18 10:17:58

标签: python matplotlib

我必须在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')

输出: tabular table 另外,我想将标题指向图表的顶部和左侧。 '有些文字在这里'是标题,黄线显示我想要另一个标题。 期望的输出顶部没有额外的空白区域。 Desired

2 个答案:

答案 0 :(得分: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

在这种情况下,外线是弯曲的,因为线延伸到其位置的两侧。人们仍然可以在桌子周围添加一点填充物。例如。有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

答案 1 :(得分:0)

我认为你不能删除桌子上方和下方的空白区域。 Reading the documentation,您已经拥有了 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')

Result

我强烈建议您在完全绘制之后调整轴/数字设置