SuperElectric
SuperElectric

Reputation: 18874

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

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.

Upvotes: 14

Views: 17254

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339170

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

Upvotes: 15

Related Questions