Skip to content
Advertisement

How to put text at a fixed position when updating an animation

Here’s the whole code: (main problem is explained below)

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)

I used matplotlib.animation to animate the graph. Everything went good.
Now I wanted to put the seed (the number) in top right corner of the graph, so I did this:
plt.text((i+5)*0.8,o*0.88, ("Seed: " +str(N)))
This add the text at every frame iteration (as I wanted) but the previous text remains in the graph and move back (because my axes updates).
So how can I put only one text at a fixed position?
I am using PyCharm on Windows 10.
(I am new to matplotlib and python, so any other suggestions are also appreciated.)

Advertisement

Answer

You have to initialize a matplotlib.axes.Axes.text and then dynamically set its text and position with set_text and set_position methods. You have also to return it in init and animate functions.

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,

enter image description here

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement