Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

python - matplotlib.pyplot will not forget previous plots - how can I flush/refresh?

How do you get matplotlib.pyplot to "forget" previous plots

I am trying to plot multiple time using matplotlib.pyplot

The code looks like this:

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.

I have looked at these questions:

How to "clean the slate"?

Matplotlib pyplot show() doesn't work once closed

(python) matplotlib pyplot show() .. blocking or not?

and tried using plt.show(), plt.clf() and plt.close to no avail.

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...