Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 811
atomh33ls Avatar asked Jun 14 '13 10:06

atomh33ls


People also ask

What is the command to clear all existing plots?

plt. clf() clears the entire current figure with all its axes, but leaves the window opened, such that it may be reused for other plots.

How do I refresh a plot in matplotlib?

To update the plot with x and y values, we use ion() function. To plot the line, we use plot() function. To define labels, we use xlabel() and ylabel() function. Then we update the variables x and y with set_xdate() and set_ydata() function.


2 Answers

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() 
like image 183
Saullo G. P. Castro Avatar answered Sep 18 '22 20:09

Saullo G. P. Castro


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

like image 24
atomh33ls Avatar answered Sep 17 '22 20:09

atomh33ls