python - Python matplotlib 绘图顶部和底部的空白

标签 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

最佳答案

一种选项是将表格的边界框指定为保存图形时要使用的边界框。

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

在这种情况下,外部线条会被裁剪,因为线条延伸到其位置的两侧。人们仍然可以在 table 周围添加一点填充物。例如。有 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

关于python - Python matplotlib 绘图顶部和底部的空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47866272/

相关文章:

python - 在 ssh 中导入 pyplot 时,TypeError 构造函数返回 NULL

python - 如何将图例标题的一部分加粗(不是整个图例标题)

Python pandas 空 df 但列有元素

python - <function>(str1, str2) 分别调用它们

python - 用 Python 播放声音

python - 带回调的 Pyro4

Python 在 Windows 7 上启动非常慢

python - Python 3.4 的 py2exe 错误 : Errno2 , 缺少文件 'run-py3 .4-win32.exe'

python - matplotlib:使加号变粗

python-2.7 - matplotlib具有奇数个子图