user7752142
user7752142

Reputation:

How can i remove a plot with Python?

I have some data that I plotted with Python but now I want to erase the plots but not the figure itself.

I have some thing like this :

import numpy as np
import pylab as plt

a = np.array([1,2,3,4,5,6,7,8,9,10])
b = np.array([1,2,3,4,5,6,7,8,9,10])
c = plt.plot(a,b,'r.')

So to clear this I tried this :

a = np.array([])
b = np.array([])
c = plt.plot(a,b,'r.')

but it does not work. What is the best way to accomplish this?

Upvotes: 1

Views: 9596

Answers (3)

litepresence
litepresence

Reputation: 3277

From here:

When to use cla(), clf() or close() for clearing a plot in matplotlib?

plt.cla() clears an axis, i.e. the currently active axis in the current figure. It leaves the other axes untouched.

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.

plt.close() closes a window, which will be the current window, if not specified otherwise.

Also if you prefer doing it line by line, you can remove them like this even if you've lost original references:

for l in ax.get_lines():
    xval = l.get_xdata()[0]
    if (xval == my_criteria):
        l.remove()

or for all, simply:

for l in ax.get_lines():
            l.remove()

likewise you can do the same indexing by y values.

Upvotes: 0

MaiaraSC
MaiaraSC

Reputation: 11

To have axes with the same values of your a, b arrays, you can do:

import matplotlib.pyplot as plt
plt.clf() # To clear the figure.
plt.axis([1,10,1,10])

enter image description here

Upvotes: 0

Suever
Suever

Reputation: 65430

You can use the remove method of the returned plot object. This is true of any plot object that inherits from Artist.

c = plt.plot(a,b,'r.')

for handle in c:
    handle.remove()

Upvotes: 4

Related Questions