215

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?

4
  • 7
    as a point of style, there's no need to use subplot when you only have one plot per figure. Commented Apr 12, 2009 at 20:12
  • I'm confused when do I use plt.clf() vs plt.cla()? I have a general function that saves open figures (makes no assumptions, does not take the fig object) and I want inside of it to have a way to completely close everything after it saves so that when I start producing the next plot the next call to the save function doesn't save the same plot again by accident. Is it ok if I ALWAYS run plt.clf() vs plt.cla() in my save function no matter what? Does it always close everything? plt.show() did do that but in cluster that can lead to bugs. Commented May 21, 2022 at 14:44
  • perhaps useful: stackoverflow.com/questions/16661790/… Commented May 21, 2022 at 14:45
  • 1
    did you try plt.close()? that worked for me and made sure I didn't accidentally save the same plot multiple times. Commented May 21, 2022 at 14:50

8 Answers 8

227

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! If you are using the PDF backend (which allows you to save multiple plots) you will need to call this after each call to plt.save()
In my case, plt.clf() was sufficient to clear the figure but insufficient to stop memory leaks, but first calling plt.close() stopped the memory leak. Python 2.7, matplotlib 1.1.1rc1 (ubuntu 12.04). FYI.
I'm confused when do I use plt.clf() vs plt.cla()? I have a general function that saves open figures (makes no assumptions, does not take the fig object) and I want inside of it to have a way to completely close everything after it saves so that when I start producing the next plot the next call to the save function doesn't save the same plot again by accident. Is it ok if I ALWAYS run plt.clf() vs plt.cla() in my save function no matter what? Does it always close everything? plt.show() did do that but in cluster that can lead to bugs.
142

You can use figure to create a new plot, for example, or use close after the first plot.

6 Comments

The pyplot tutorial does mention clf() in the "multiple figures" section. Note that if you just create a new plot with figure() without closing the old one with close() (even if you close the GUI window), pyplot retains a reference to your old figure, which may look like a memory leak.
You can use plt.close()/pylab.close() to remove all old figures
After first plot, do you mean after plt.savefig("first.ps")?
@JouniK.Seppänen Just to add to your comment, Python will by default warn you if you open many figures: "RuntimeWarning: More than 20 figures have been opened.".
Do you have to call plt.close() or plt.figure()? Your answer is much more helpful, it's self-contained with exact code -- especially if it's one single command.
|
38

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

2 Comments

you should still use plt.clf(), figures are held in memory until explicitly closed
where is your plt.close()?
14

Just enter plt.hold(False) before the first plt.plot, and you can stick to your original code.

1 Comment

in matplotlib==2.0.2, I get this message: MatplotlibDeprecationWarning: pyplot.hold is deprecated.
13

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

1 Comment

you just saved me a bunch of time I didn't have to lose
7

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

Comments

2

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..

Comments

2

Did you try plt.close()? that worked for me and made sure I didn't accidentally save the same plot multiple times.

Code:

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

in my ultimate utils lib: https://github.com/brando90/ultimate-utils

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.