问题描述
你如何让 matplotlib.pyplot
忘记"之前的图
How do you get matplotlib.pyplot
to "forget" previous plots
我正在尝试使用 matplotlib.pyplot
代码如下:
def plottest():
import numpy as np
import matplotlib.pyplot as plt
a=np.random.rand(10,)
b=np.random.rand(10,)
c=np.random.rand(10,)
plt.plot(a,label='a')
plt.plot(b,label='b')
plt.plot(c,label='c')
plt.legend(loc='upper left')
plt.ylabel('mag')
plt.xlabel('element)')
plt.show()
e=np.random.rand(10,)
f=np.random.rand(10,)
g=np.random.rand(10,)
plt.plot(e,label='e')
plt.plot(f,label='f')
plt.plot(g,label='g')
plt.legend(loc='upper left')
plt.ylabel('mag')
plt.xlabel('element)')
plt.show()
不幸的是,无论我做什么,我都会得到相同的情节(实际上是从我不久前运行并完成的其他一些代码中获得的).
Unfortunately I keep getting the same plot (actually from some other code which I ran and completed a while ago) no matter what I do.
类似的代码以前对我有用.
Similar code has worked previously for me.
我看过这些问题:
Matplotlib pyplot show() 一旦关闭就不起作用
(python) matplotlib pyplot show() .. 阻塞与否?
并尝试使用 plt.show()
、plt.clf()
和 plt.close
无济于事.
and tried using plt.show()
, plt.clf()
and plt.close
to no avail.
有什么想法吗?
推荐答案
我宁愿在每个 plt.show()
之后使用 plt.clf()
到 只需清除当前图形而不是关闭并重新打开它,保持窗口大小并为您提供更好的性能和更好的内存使用率.
I would rather use plt.clf()
after every plt.show()
to just clear the current figure instead of closing and reopening it, keeping the window size and giving you a better performance and much better memory usage.
同样,您可以执行 plt.cla()
来清除当前的 轴.
Similarly, you could do plt.cla()
to just clear the current axes.
要清除特定的轴,当您在一个图形中有多个轴时很有用,您可以例如:
To clear a specific axes, useful when you have multiple axes within one figure, you could do for example:
fig, axes = plt.subplots(nrows=2, ncols=2)
axes[0, 1].clear()
这篇关于matplotlib.pyplot 不会忘记以前的图 - 我如何刷新/刷新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!