Matplotlib and Ipython-notebook: Displaying exactly the figure that will be saved

大兔子大兔子 提交于 2019-11-26 04:01:28

问题


I am using ipython-notebook a lot at the moment for numerical analysis and plotting of data. In the process of preparing publication quality plots there is a lot of tweaking to get the layout just right, however I can\'t get ipython/matplotlib to show me what I will be saving in the browser. Making the process more painful than it should be because I have to keep opening the new output file to check it.

Is there a way to get the image that is displayed inline to be the same as the image that is saved?

Example as follows, facecolor=\'gray\' for clarity:

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()

Note here I have explicity chosen my axes dimensions so that they are equidistant from the two sides of the resulting image. This is respected in the saved image, but ignored in the image shown in the notebook:

Notebook displayed image:

Savefig image:


回答1:


As noted by @andrew, the ipython magics are enforcing bbox_inches='tight' by default. This can be overridden using other magics as explained in the ipython documentation:

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

produces an inline image identical to that produced by savefig.




回答2:


The behavior is due to the fact that the magic %matplotlib inline defaults to using the bbox_inches='tight' when rendering inline.

I know you asked about changing the behavior of plt.show(), but alternatively, you could change the behavior of savefig() to use the same settings as the notbeook.

fig.savefig('mypath.png',dpi=300, facecolor='gray',  bbox_inches='tight')

New 'savefig' image:



来源:https://stackoverflow.com/questions/37864735/matplotlib-and-ipython-notebook-displaying-exactly-the-figure-that-will-be-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!