从 ipython 笔记本中保存绘图会生成剪切图像

Saving plot from ipython notebook produces a cut image

我正在使用 ipython 笔记本绘制带有 2 个 ylabel 的绘图,在笔记本内部可视化时图像看起来不错。

这是我的做法:

import matplotlib.pyplot as plt 

fig, ax1 = plt.subplots()
plt.title('TITLE')
plt.xlabel('X')

plt.plot(x, y1, '-', color='blue', label='SNR')
ax1.set_ylabel('y1', color='blue')
for tl in ax1.get_yticklabels():
    tl.set_color('blue')

ax2 = ax1.twinx()
plt.plot(x, y2, '--', color='red', label='Ngal')
ax2.set_ylabel('y2', color='red')
for tl in ax2.get_yticklabels():
    tl.set_color('red')

问题是当我尝试用命令保存它时

plt.savefig('output.png', dpi=300)

因为输出将是在右侧剪切的图像:如果正确的数字很大,基本上我看不到正确的 ylabel。

默认情况下,matplotlib 为 x 和 y 轴标签和刻度标签留出很小的空间,因此您需要调整图形以包含更多填充。幸运的是,这再简单不过了。在你调用savefig之前,你可以调用call

fig.tight_layout()
plt.savefig('output.png', dpi=300)

或者,您可以将 bbox_inches='tight' 传递给 savefig,它也会调整图形以包括所有 x 和 y 标签

plt.savefig('output.png', dpi=300, bbox_inches='tight')