问题描述
我想使用 matplotlib.pyplot
在 Python 中创建不同的图形.然后,我想将其中一些保存到文件中,而其他一些则应使用 show()
命令在屏幕上显示.
I'd like to create different figures in Python using matplotlib.pyplot
. I'd then like to save some of them to a file, while others should be shown on-screen using the show()
command.
然而,show()
显示所有创建的图形.我可以通过在创建不想在屏幕上显示的图后调用 close()
来避免这种情况,如下面的代码所示:
However, show()
displays all created figures. I can avoid this by calling close()
after creating the plots which I don't want to show on-screen, like in the following code:
import matplotlib.pyplot as plt
y1 = [4, 2, 7, 3]
y2 = [-7, 0, -1, -3]
plt.figure()
plt.plot(y1)
plt.savefig('figure1.png')
plt.close()
plt.figure()
plt.plot(y2)
plt.show()
plt.close('all')
这将保存第一个图形并显示第二个图形.但是,我收到一条错误消息:
This saves the first figure and shows the second one. However, I get an error message:
无法调用事件"命令:应用程序在执行时已被破坏
是否可以更优雅地选择要显示的人物?
Is it possible to select in a more elegant way which figures to show?
此外,第一个 figure()
命令是否多余?给与不给似乎没什么区别.
Also, is the first figure()
command superfluous? It doesn't seem to make a different whether I give it or not.
非常感谢.
推荐答案
更好的方法是使用 plt.clf()
而不是 plt.close()
.此外, plt.figure()
创建一个新图形,而您只需使用 plt.clf()
:
The better way is to use plt.clf()
instead of plt.close()
.Moreover plt.figure()
creates a new graph while you can just clear previous one with plt.clf()
:
import matplotlib.pyplot as plt
y1 = [4, 2, 7, 3]
y2 = [-7, 0, -1, -3]
plt.figure()
plt.plot(y1)
plt.savefig('figure1.png')
plt.clf()
plt.plot(y2)
plt.show()
plt.clf()
此代码不会产生错误或警告,例如无法调用事件"命令...
This code will not generate errors or warnings such can't invoke "event" command...
这篇关于使用Python的matplotlib选择要在屏幕上显示的图形以及将哪些图形保存到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!