在 matplotlib 动画中更新轴时如何将文本放在固定位置?

How to put text at a fixed position when I am updating the axes in matplotlib animation?

完整代码如下:(主要问题解释如下)

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from datetime import datetime as dt
start=dt.now()

def collatz(num):
    if num==1:return 0
    if (num % 2 == 0):return ((num // 2))
    if (num % 2 == 1):return ((3 * num + 1))

def ab(num,n,t):
    for i in range(n):
        # if not (num):break
        t.append(num)
        num=collatz(num)
N=820
fig = plt.figure()
ax = plt.axes(xlim=(0, 5), ylim=(0, 1.1*N))
line, = ax.plot([], [], 'g--')
ots, = ax.plot([], [], 'b.')

def init():
    line.set_data([], [])
    ots.set_data([], [])
    return line, ots,

def animate(i):
    t = []
    ab(N, i + 1, t)
    y = t
    plt.xlim([0, i+5])
    o=max(t)
    plt.ylim([0, 1.1*o])
    plt.text((i+5)*0.8,o*0.88, ("Seed: " +str(N)))
    x=np.array([k for k in range(0,i+1)])
    line.set_data(x, y)
    ots.set_data(x,y)
    return line, ots,
ount=0
tmp=N
while tmp!=1:
    ount+=1
    tmp=collatz(tmp)

anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=ount+4, interval=400, blit=False)

plt.show()
print(dt.now()-start)

我使用 matplotlib.animation 为图表制作动画。一切顺利。
现在我想把种子(数字)放在图表的右上角,所以我这样做了:
plt.text((i+5)*0.8,o*0.88, ("Seed: " +str(N)))
这会在每一帧迭代中添加文本(如我所愿),但之前的文本仍保留在图形中并向后移动(因为我的轴更新)。
那么如何才能在一个固定的位置只放置一个文本呢?
我在 Windows 10.
上使用 PyCharm (我是 matplotlib 和 python 的新手,因此也欢迎任何其他建议。)

您必须初始化一个 matplotlib.axes.Axes.text,然后使用 set_textset_position 方法动态设置其文本和位置。您还必须在 initanimate 函数中 return 它。

N=820
fig = plt.figure()
ax = plt.axes(xlim=(0, 5), ylim=(0, 1.1*N))
line, = ax.plot([], [], 'g--')
ots, = ax.plot([], [], 'b.')
text = ax.text(0, 0, '')

def init():
    line.set_data([], [])
    ots.set_data([], [])
    text.set_text('')
    text.set_position((0, 0))
    return line, ots, text,

def animate(i):
    t = []
    ab(N, i + 1, t)
    y = t
    plt.xlim([0, i+5])
    o=max(t)
    plt.ylim([0, 1.1*o])
    text.set_text("Seed: " + str(N))
    text.set_position(((i+5)*0.8, o*0.88))
    x=np.array([k for k in range(0,i+1)])
    line.set_data(x, y)
    ots.set_data(x,y)
    return line, ots, text,