How do I tell matplotlib that I am done with a plot?
PythonMatplotlibPlotPython Problem Overview
The following code plots to two PostScript (.ps) files, but the second one contains both lines.
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")
How can I tell matplotlib to start afresh for the second plot?
Python Solutions
Solution 1 - Python
There is a clear figure command, and it should do it for you:
plt.clf()
If you have multiple subplots in the same figure
plt.cla()
clears the current axes.
Solution 2 - Python
You can use figure
to create a new plot, for example, or use close
after the first plot.
Solution 3 - Python
As stated from @DavidCournapeau, use 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")
Or subplot(121)
/ subplot(122)
for the same plot, different position.
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")
Solution 4 - Python
Just enter plt.hold(False)
before the first plt.plot, and you can stick to your original code.
Solution 5 - Python
If you're using Matplotlib interactively, for example in a web application, (e.g. ipython) you maybe looking for
plt.show()
instead of plt.close()
or plt.clf()
.
Solution 6 - Python
If none of them are working then check this.. say if you have x and y arrays of data along respective axis. Then check in which cell(jupyter) you have initialized x and y to empty. This is because , maybe you are appending data to x and y without re-initializing them. So plot has old data too. So check that..
Solution 7 - Python
From the source code of matplotlib.pyplot, under the figure()
documentation:
> If you are creating many figures, make sure you explicitly call
> .pyplot.close
on the figures you are not using, because this will
> enable pyplot to properly clean up the memory.
So, as others have said, use plt.close()
on each figure when you're done with it, and you'll be good to go!
NOTE: if you create the figure via f = plt.figure()
, you can close it via plt.close( f )
instead of f.close()
.