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

PythonMatplotlib

Python Problem Overview


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:

https://stackoverflow.com/questions/10819363/how-to-clean-the-slate

https://stackoverflow.com/questions/5158447/matplotlib-pyplot-show-doesnt-work-once-closed?rq=1

https://stackoverflow.com/questions/6187603/python-matplotlib-pyplot-show-blocking-or-not

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

Any ideas?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

I discovered that this behaviour only occurs after running a particular script, similar to the one in the question. I have no idea why it occurs.

It works (refreshes the graphs) if I put

plt.clf()
plt.cla()
plt.close()

after every plt.show()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionatomh33lsView Question on Stackoverflow
Solution 1 - PythonSaullo G. P. CastroView Answer on Stackoverflow
Solution 2 - Pythonatomh33lsView Answer on Stackoverflow