python - Matplotlib 和 Ipython 笔记本 : Displaying exactly the figure that will be saved

标签 python matplotlib ipython ipython-notebook jupyter-notebook

我目前经常使用 ipython-notebook 进行数值分析和数据绘图。在准备出版质量图的过程中,有很多调整以使布局恰到好处,但是我无法让 ipython/matplotlib 显示我将在浏览器中保存的内容。让这个过程比它应该的更痛苦,因为我必须不断打开新的输出文件来检查它。

有没有办法让内联显示的图像与保存的图像相同?

示例如下,为了清楚起见,facecolor='gray':

import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

fig = plt.figure(figsize=(6,4),facecolor='gray')
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
x = np.linspace(0,2*np.pi,1000)
y = np.sin(x)
ax.plot(x,y,label=r'$\sin(x)$')
ax.set_xlim(0,2*np.pi)
ax.set_ylim(-1.2,1.2)
ax.set_xlabel(r'$x$')
ax.set_ylabel(r'$y$')
ax.legend(loc='upper right', frameon=False)
fig.savefig('mypath.png',dpi=300, facecolor='gray')
plt.show()

请注意,我已经明确选择了我的轴尺寸,以便它们与结果图像的两侧等距。这在保存的图像中得到尊重,但在笔记本中显示的图像中被忽略:

笔记本显示图片:

Notebook displayed image

保存图片:

enter image description here

最佳答案

正如@andrew 所指出的,默认情况下 ipython 魔法正在执行 bbox_inches='tight'。这可以使用其他魔法覆盖,如 ipython documentation 中所述。 :

%matplotlib inline
%config InlineBackend.print_figure_kwargs = {'bbox_inches':None}

生成与 savefig 生成的相同的内联图像。

关于python - Matplotlib 和 Ipython 笔记本 : Displaying exactly the figure that will be saved,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37864735/

相关文章:

python : Import modules once then share with several files

python - 从 ColumnDataSource 中选取 Bokeh HoverTool 输出的数据

matplotlib - 获取文本的边界框并更新 Canvas

python - 如何在matplotlib中使主轴透明,同时使zoomed_inset_axes不透明

ipython - 在干净的 Ubuntu 14.04 LTS 上安装 Jupyter Notebook 失败

python - IPython.parallel 不使用多核?

python - tkinter py2app 应用程序不会关闭

python - 无法使用带有 os.system 的 taskkill 来终止 VLC.exe

python - 为什么我需要从我的 matplotlib Axes 中删除补丁两次才能将它们全部删除?

python - 类型错误 : boxplot() got an unexpected keyword argument 'labels'