205

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Stefano Borini
  • 138,652
  • 96
  • 297
  • 431
  • 7
    as a point of style, there's no need to use subplot when you only have one plot per figure. – Autoplectic Apr 12 '09 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. – Charlie Parker May 21 '22 at 14:44
  • perhaps useful: https://stackoverflow.com/questions/16661790/difference-between-plt-close-and-plt-clf – Charlie Parker May 21 '22 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. – Charlie Parker May 21 '22 at 14:50

8 Answers8

219

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
randlet
  • 3,628
  • 1
  • 17
  • 21
  • 1
    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() – Ben DeMott Nov 11 '11 at 16:54
  • 5
    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. – D.J.Duff Jul 26 '13 at 12:58
  • 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. – Charlie Parker May 21 '22 at 14:42
138

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

Tom
  • 42,844
  • 35
  • 95
  • 101
David Cournapeau
  • 78,318
  • 8
  • 63
  • 70
  • 24
    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. – Jouni K. Seppänen Apr 12 '09 at 20:03
  • 7
    You can use plt.close()/pylab.close() to remove all old figures – Calvin1602 Jan 24 '13 at 08:32
  • 3
    After first plot, do you mean after `plt.savefig("first.ps")`? – Sigur May 24 '17 at 17:54
  • @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.". – rph Sep 14 '18 at 05:26
  • 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. – Charlie Parker May 21 '22 at 14:40
  • Also note that you can call `plt.close("all")` to close *all* figure windows, not just the current one. – Florian Brucker Oct 11 '22 at 06:09
39

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")
Canica
  • 2,650
  • 3
  • 18
  • 34
lmount
  • 1,282
  • 11
  • 9
14

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

Dirklinux
  • 1,075
  • 1
  • 11
  • 19
  • 8
    in matplotlib==2.0.2, I get this message: MatplotlibDeprecationWarning: pyplot.hold is deprecated. – Jonathan Jul 07 '17 at 00:10
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().

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Damo
  • 374
  • 5
  • 11
6

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

jvriesem
  • 1,859
  • 3
  • 18
  • 40
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..

Seeni
  • 1,518
  • 1
  • 14
  • 22
1

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

Charlie Parker
  • 5,884
  • 57
  • 198
  • 323