下面的代码绘制了两个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为第二个情节重新开始?


当前回答

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

其他回答

如果没有一个在工作,然后检查这个。假设你在各自的轴上有x和y数组的数据。然后检查哪个单元格(jupyter)已将x和y初始化为空。这是因为,可能您正在将数据追加到x和y,而没有重新初始化它们。图中也有旧数据。检查一下。

正如@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")

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

如果要创建许多图形,请确保显式调用 “.pyplot。关闭你不使用的数字,因为这将 启用pyplot以正确地清理内存。

因此,正如其他人所说,当您完成每个图形时,请在它上使用plt.close(),然后您就可以开始了!

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

在第一个plt之前输入plt.hold(False)。绘图,你可以坚持你的原始代码。

你试过plt.close()吗?这对我来说很有效,并确保我不会意外地多次保存相同的情节。

代码:

def save_to(root: Path, plot_name: str = 'plot', close: bool = True):
    """
    Assuming there is a plot in display, saves it to local users desktop users desktop as a png, svg & pdf.

    note:
        - ref on closing figs after saving: https://stackoverflow.com/questions/741877/how-do-i-tell-matplotlib-that-i-am-done-with-a-plot
        - clf vs cla https://stackoverflow.com/questions/16661790/difference-between-plt-close-and-plt-clf
    """
    root: Path = root.expanduser()
    plt.savefig(root / f'{plot_name}.png')
    plt.savefig(root / f'{plot_name}.svg')
    plt.savefig(root / f'{plot_name}.pdf')
    if close:
        # plt.clf()
        # plt.cla()
        plt.close()

在我的终极utils lib: https://github.com/brando90/ultimate-utils