pad_inches = 0和bbox_inches ="tight"使得图小于声明的figsize

cau*_*chy 22 plot matplotlib

我正在制作一个嵌入乳胶的出版品质图,我希望在尺寸和字体方面非常精确(因此字体在文章中与图中的尺寸相同).为了防止绘图缩小乳胶,我希望它具有确切的尺寸,但我不能.这是我的代码:

import matplotlib.pyplot as plt
from matplotlib import rc, rcParams
from numpy import sin

rc('text', usetex=True)
rc('font', family='serif', serif='Computer Modern Roman', size=8)
rc('legend', fontsize=10)

width_in = 5
fig = plt.figure(1, figsize=(width_in, 2))
ax = fig.add_subplot(111)
ax.plot(range(0,100), sin(range(0,100)))

fig.tight_layout()
fig.savefig('test.eps', bbox_inches='tight', pad_inches=0)
plt.close()
Run Code Online (Sandbox Code Playgroud)

问题在于bbox_inches ='tight'和pad_inches = 0.添加这些选项使我的绘图宽4.76英寸而不是声明5英寸.但我希望他们节省空间.那怎么解决呢?

编辑:嗯,答案建议删除bbox_inches='tight',pad_inches=0并使用只tight_layout().然后图像大小合适,但它仍然有一些白色的填充物.我可以删除它fig.tight_layout(pad=0),但随后在框内移动的图标题,看起来很难看.另一方面,我可以使用tight_layout(rect=[...])并获得所需的结果,但这是一个手动工作,以使数字正确 - 我不喜欢它.因此,目前我没有看到任何简单而通用的解决方案.

tac*_*ell 23

你遇到的问题是,bbox_inches='tight'只是删除你图形周围的所有额外空白区域,它实际上并没有在渲染后重新排列你图中的任何东西.

您可能需要调整传递给tight_layout(教程)的参数以获得所需的效果.

希望这能让你指向正确的方向.


Kyr*_*ion 7

我在为 LaTeX 制作 matplotlib 绘图时遇到同样的问题。由于我的地块不允许使用tight_layout,给出警告,我最终使用了fig.subplots_adjust(bottom=bottom_pos, top=top_pos, left=left_pos, right=right_pos)。请参阅本教程。它需要手动找到最佳值等,bottom_pos但在我的情况下,这似乎是获得没有太多空白的图像而不改变输出的图形大小的唯一可能性。