Mastiff
Mastiff

Reputation: 2240

How can I make matplotlib forget about removed plot elements?

I'm using matplotlib within a GUI and elements come and go from the plot. I'm trying to keep the axis tight on the data, but have noticed that if an element is removed, axis('tight') still expands the axis as though it were there. How can this be addressed?

Example:

fig,ax = plt.subplots()
h1 = ax.plot(1,1,'.')
h2 = ax.plot(10,10,'.')
h3 = ax.plot(20,20,'.')
ax.axis('tight')  # (1,20,1,20)
h3[0].remove()
ax.axis('tight')  # still (1,20,1,20), desire (1,10,1,10)

Upvotes: 1

Views: 57

Answers (1)

Craig
Craig

Reputation: 4855

After removing the element from the plot, call ax.relim() on the axis so that it recalculates the limits before calling ax.axis('tight').

import matplotlib.pyplot as plt

fig,ax = plt.subplots()
h1 = ax.plot(1,1,'.')
h2 = ax.plot(10,10,'.')
h3 = ax.plot(20,20,'.')
ax.axis('tight')  # (1,20,1,20)
h3[0].remove()
ax.relim()        # recalculates that limits for the axis
ax.axis('tight')  # will rescale the plot correctly to the new limits
plt.show()

Upvotes: 1

Related Questions