从ipython notebook中保存绘图会产生剪切图像 [英] Saving plot from ipython notebook produces a cut image

查看:142
本文介绍了从ipython notebook中保存绘图会产生剪切图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ipython笔记本绘制带有2个ylabels的情节,并且在笔记本内部可视化时图像看起来很好。

I am plotting a plot with 2 ylabels using ipython notebook and the image looks good when visualized inside the 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')

问题在于,当我尝试使用命令保存它时

The problem is that when I try to save it with the command

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

因为输出将是一个被剪切的图像右边:基本上我没有看到如果正确的数字很大,则为正确的ylabel。

since the output will be an image which is cut on the right side: basically I don't see the right ylabel if the right numbers are large.

推荐答案

默认情况下,matplotlib为x和y轴标签留下的空间很小勾选标签,因此您需要调整图形以包含更多填充。幸运的是,这可能不容易。在你调用savefig之前,你可以拨打电话

By default, matplotlib leaves very little room for x and y axis labels and tick labels, therefore you need to adjust the figure to include more padding. Fortunately this could not be easier to do. Before you call savefig, you can call call

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

或者,您可以将bbox_inches ='tight'传递给savefig调整数字以包含所有x和y标签

Alternatively, you can pass bbox_inches='tight' to savefig which will also adjust the figure to include all of the x and y labels

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

这篇关于从ipython notebook中保存绘图会产生剪切图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆