Update text in plot

Question:

I want to change text in matplotlib’s plot with loop. I am able to print text with loop, but unable to delete the previous text and they got printed on top of each other.

import numpy as np 
import matplotlib.pyplot as plt


x = np.array([1,2,3,4,5])
y = np.array([1,2,3,4,5])

fig, ax = plt.subplots()
ax.set_xlim([0,5])
ax.set_ylim([0,5])
for i in x:
    pt = ax.plot(i, i, 'o')
    tx = ax.text(1, 2, str(i), fontsize = 12)
        
    plt.pause(1)
    removePt = pt.pop()
    removePt.remove()

I tried to delete text by

removeTx = tx.pop()
removeTx.remove()

but it has not worked.

Kindly suggest how can I remove the previous text from plot.

Asked By: pkj

||

Answers:

Just add tx.remove() after the pause:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([1, 2, 3, 4, 5])
y = np.array([1, 2, 3, 4, 5])

fig, ax = plt.subplots()
ax.set_xlim([0, 5])
ax.set_ylim([0, 5])
for i in x:
    pt = ax.plot(i, i, 'o')
    tx = ax.text(1, 2, str(i), fontsize = 12)

    plt.pause(1)
    tx.remove()

plt.show()

enter image description here

Answered By: Zephyr