Python 调用 pyplot.show() 后保存图形会生成一个空文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/21875356/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Saving a figure after invoking pyplot.show() results in an empty file
提问by andreasdr
The following example code generates a simple plot, then saves it to 'fig1.pdf', then displays it, then saves it again to 'fig2.pdf'. The first image looks as expected, but the second one is blank (contains a white square). What's actually going on here? The line plt.show()apparently messes something up, but I can't figure out what/how!
下面的示例代码生成一个简单的绘图,然后将其保存到“fig1.pdf”,然后显示它,然后再次将其保存到“fig2.pdf”。第一个图像看起来像预期的那样,但第二个图像是空白的(包含一个白色方块)。这里到底发生了什么?这条线plt.show()显然搞砸了,但我不知道是什么/如何!
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1, 1, 100)
y = x**2
plt.plot(x,y)
plt.savefig('fig1.pdf')
plt.show()
plt.savefig('fig2.pdf')
采纳答案by Joe Kington
If you want to save the figure after displaying it, you'll need to hold on to the figure instance. The reason that plt.savefigdoesn't work after calling showis that the current figure has been reset.
如果要在显示图形后保存图形,则需要保留图形实例。plt.savefig调用后不起作用的原因show是当前数字已重置。
pyplotkeeps track of which figures, axes, etc are "current" (i.e. have not yet been displayed with show) behind-the-scenes.  gcfand gcaget the current figure and current axes instances, respectively.  plt.savefig(and essentially any other pyplotmethod) just does plt.gcf().savefig(...).  In other words, get the current figure instance and call its savefigmethod.  Similarly plt.plotbasically does plt.gca().plot(...).
pyplot跟踪哪些图形、轴等是“当前的”(即尚未显示show)在幕后。  gcf和gca克等的Çurrent ˚Figure和电流一个分别XES实例。  plt.savefig(以及基本上任何其他pyplot方法)只是这样做plt.gcf().savefig(...)。换句话说,获取当前图形实例并调用其savefig方法。同样plt.plot基本上是这样plt.gca().plot(...)。
After showis called, the list of "current" figures and axes is empty.
之后show被称为的“当前”数字和轴的列表是空的。
In general, you're better off directly using the figure and axes instances to plot/save/show/etc, rather than using plt.plot, etc, to implicitly get the current figure/axes and plot on it. There's nothing wrong with using pyplotfor everything (especially interactively), but it makes it easier to shoot yourself in the foot. 
通常,您最好直接使用图形和轴实例来绘制/保存/显示/等,而不是使用plt.plot等来隐式获取当前图形/轴并在其上绘图。pyplot为所有东西使用(尤其是交互式)并没有错,但它可以更容易地用脚射击自己。
Use pyplotfor plt.show()and to generate a figure and an axes object(s), but then use the figure or axes methods directly. (e.g. ax.plot(x, y)instead of plt.plot(x, y), etc) The main advantage of this is that it's explicit.  You know what objects you're plotting on, and don't have to reason about what the pyplot state-machine does (though it's not that hard to understand the state-machine interface, either).
使用pyplotforplt.show()和 生成图形和轴对象,然后直接使用图形或轴方法。(例如,ax.plot(x, y)而不是plt.plot(x, y)等) 这样做的主要优点是它是明确的。你知道你在什么对象上绘图,并且不必推理 pyplot 状态机的作用(尽管理解状态机接口也不难)。
As an example of the "recommended" way of doing things, do something like:
作为“推荐”做事方式的示例,请执行以下操作:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1, 1, 100)
y = x**2
fig, ax = plt.subplots()
ax.plot(x, y)
fig.savefig('fig1.pdf')
plt.show()
fig.savefig('fig2.pdf')
If you'd rather use the pyplotinterface for everything, then just grab the figure instance before you call show. For example:
如果您更愿意将pyplot接口用于所有内容,那么只需在调用show. 例如:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1, 1, 100)
y = x**2
plt.plot(x, y)
fig = plt.gcf()
fig.savefig('fig1.pdf')
plt.show()
fig.savefig('fig2.pdf')
回答by miles82
pyplot.showblocks and destroys the plot upon closing. You can use
pyplot.show在关闭时阻止并破坏情节。您可以使用
plt.show(block=False)
after which the save to fig2.pdf will work or you can plot it again before saving
之后保存到 fig2.pdf 将起作用,或者您可以在保存之前再次绘制它
plt.plot(x,y)
plt.savefig('fig2.pdf')
回答by Nick Desaulniers
I had to run plt.cla()and plt.clf()before plotting the second one.  Clear current axes and clear current plot, respectively.
我只好跑plt.cla()并plt.clf()绘制在第二个之前。分别清除当前轴和清除当前图。
回答by serv-inc
If you just want to see the figure before saving, you can call
如果你只是想在保存前看图,你可以调用
plt.ion()
before plotting, which starts interactive mode, and shows all figures as they are drawn. This mostly removes the need to call plt.show(). You no longer need to close the figures to continue.
在绘图之前,启动交互模式,并在绘制时显示所有图形。这主要消除了调用plt.show(). 您不再需要关闭数字以继续。
To disable interactive mode again, call plt.ioff().
要再次禁用交互模式,请调用plt.ioff()。

