如何告诉matplotlib我已完成绘图?

208 投票
8 回答
250227 浏览
提问于 2025-04-15 11:06

下面的代码会生成两个 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 从头开始绘制第二个图呢?

8 个回答

38

正如@DavidCournapeau所说,使用 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")
222

这里有一个很简单的命令,可以帮你完成这个任务:

plt.clf()

如果你在同一个图形中有多个子图的话,

plt.cla()

这个命令会清除当前的坐标轴。

140

你可以用 figure 来创建一个新的图表,比如说,或者在第一个图表之后使用 close 来关闭它。

撰写回答