189

以下代码绘制到两个PostScript (.ps) 文件,但第二个包含两行。

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab

plt.subplot(111)
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("first.ps")


plt.subplot(111)
x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("second.ps")

如何告诉 matplotlib 重新开始第二个情节?

4

7 回答 7

201

有一个明确的数字命令,它应该为你做:

plt.clf()

如果您在同一个图中有多个子图

plt.cla()

清除当前坐标区。

于 2009-04-12T17:08:30.220 回答
136

例如,您可以使用figure创建一个新图,或close在第一个图之后使用。

于 2009-04-12T14:43:47.260 回答
36

正如 David Cournapeau 所说,使用 figure()。

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab

plt.figure()
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("first.ps")


plt.figure()
x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("second.ps")

或 subplot(121) / subplot(122) 用于相同的情节,不同的位置。

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab

plt.subplot(121)
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")

plt.subplot(122)
x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("second.ps")
于 2009-04-12T21:44:36.063 回答
13

只需plt.hold(False)在第一个 plt.plot 之前输入,就可以坚持原来的代码。

于 2012-03-22T10:52:09.110 回答
13

如果您以交互方式使用 Matplotlib,例如在 Web 应用程序中(例如 ipython),您可能正在寻找

plt.show()

而不是plt.close()or plt.clf()

于 2016-08-16T13:33:22.047 回答
2

如果它们都没有工作,那么检查一下..说如果你沿着各自的轴有 x 和 y 数据数组。然后检查您已将 x 和 y 初始化为空的单元格(jupyter)。这是因为,也许您正在将数据附加到 x 和 y 而不重新初始化它们。所以情节也有旧数据。所以检查那个..

于 2018-02-10T12:45:53.510 回答
1

来自matplotlib.pyplot的源代码,在figure()文档下:

If you are creating many figures, make sure you explicitly call
    `.pyplot.close` on the figures you are not using, because this will
    enable pyplot to properly clean up the memory.

所以,正如其他人所说,plt.close()当你完成每个人物时,使用它,你会很高兴的!

注意:如果您通过创建图形f = plt.figure(),您可以通过plt.close( f )而不是关闭它f.close()

于 2021-09-24T23:34:33.187 回答