Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Matplotlib, how can I clear an axes' contents without erasing its axis labels?

Tags:

matplotlib

Is there an alternative to axes.clear() that leaves the axis labels untouched, while erasing the axes' contents?

Context: I have an interactive script that flips through some flow images, and for each image, plots it using axes.quiver(). If I don't call axes.clear() between calls to axes.quiver(), each quiver() call just adds more arrows to the plot without first erasing the previously added arrows. However, when I call axes.clear(), it nukes the axes labels. I can re-set them, but it's a bit annoying.

like image 451
SuperElectric Avatar asked Mar 28 '17 17:03

SuperElectric


People also ask

How do you clear a graph in Python?

Use plt. clf() to clear a plot Call plt. clf() to clear the current figure of plt .

Which command is used to clear the plot in Python?

pyplot. clf(). Used to clear the current Figure's state without closing it.


1 Answers

You can remove the artists from an axes using the remove() of the artists. Below is a code showing two options to do so.

import matplotlib.pyplot as plt
import numpy as np

X, Y = np.meshgrid(np.arange(0, 2 * np.pi, .2), np.arange(0, 2 * np.pi, .2))
U = np.cos(X)
V = np.sin(Y)

plt.figure()
plt.title('Arrows scale with plot width, not view')
plt.xlabel('xlabel')
plt.xlabel('ylabel')

Q = plt.quiver(X, Y, U, V, units='width')
l, = plt.plot(X[0,:], U[4,:]+2)

# option 1, remove single artists
#Q.remove()
#l.remove()

# option 2, remove all lines and collections
for artist in plt.gca().lines + plt.gca().collections:
    artist.remove()

plt.show()
like image 192
ImportanceOfBeingErnest Avatar answered Oct 21 '22 17:10

ImportanceOfBeingErnest