【问题标题】:Saving plot from ipython notebook produces a cut image从 ipython 笔记本保存绘图会产生剪切图像
【发布时间】:2015-04-22 16:09:40
【问题描述】:

我正在使用 ipython notebook 绘制一个带有 2 个 ylabels 的图,当在 notebook 中可视化时,图像看起来不错。

这是我的做法:

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。

【问题讨论】:

  • 在savefig 命令之前尝试fig.tight_layout()

标签: python matplotlib ipython ipython-notebook


【解决方案1】:

默认情况下,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')

【讨论】:

    猜你喜欢
    • 2015-10-15
    • 1970-01-01
    • 2013-02-09
    • 2016-04-11
    • 1970-01-01
    • 2014-05-16
    • 2015-11-10
    • 2015-06-17
    • 2013-10-24
    相关资源
    最近更新 更多