Home > front end >  FuncAnimation how to update text after each iteration
FuncAnimation how to update text after each iteration

Time:05-29

I am trying to create an animation of a Monte-Carlo estimation of the number pi, for each iteration I would like the numerical estimation to be in text on the plot, but the previous text is not removed and makes the values unreadable. I tried Artist.remove(frame) with no success. The plot is done with Jupiter Notebook.

#Enable interactive plot
%matplotlib notebook
import math
from matplotlib.path import Path
from matplotlib.animation import FuncAnimation
from matplotlib.path import Path
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import ConvexHull
from matplotlib.artist import Artist

N = 10000

#create necessary arrays
x = np.arange(0,N)
y = np.zeros(N)

#set initial points to zero
inHull = 0

def inCircle(point):
    #the function is given a point in R^n
    #returns a boolean stating if the norm of the point is smaller than 1.
    if np.sum(np.square(point)) <= 1:
        return True
    else:
        return False
    
#iterate over each point
for i in range(N):
    random_point = np.random.rand(2)*2 - 1
    
    #determine if the point is inside the hull
    if inCircle(random_point):
        inHull  = 1
        
    #we store areas in array y.
    y[i]  = (inHull*4)/(i 1)
    

fig = plt.figure()
ax = plt.subplot(1, 1, 1)
data_skip = 20

def init_func():
    ax.clear()
    plt.xlabel('n points')
    plt.ylabel('Estimated area')
    plt.xlim((x[0], x[-1]))
    plt.ylim((min(y)- 1, max(y) 0.5))
    

    
def update_plot(i):
    ax.plot(x[i:i data_skip], y[i:i data_skip], color='k')
    ax.scatter(x[i], y[i], color='none')
    
    Artist.remove(ax.text(N*0.6, max(y) 0.25, "Estimation: "  str(round(y[i],5))))
    ax.text(N*0.6, max(y) 0.25, "Estimation: "  str(round(y[i],5)))


anim = FuncAnimation(fig,
                     update_plot,
                     frames=np.arange(0, len(x), data_skip),
                     init_func=init_func,
                     interval=20)
plt.show()

Thank you.

CodePudding user response:

As you have already done in init_func, you should clear the plot in each iteration with ax.clear(). Then it is necessary to edit slighlty the plot function:

ax.plot(x[i:i data_skip], y[i:i data_skip], color='k')

And finally you have to fix x axis limits in each iteration with ax.set_xlim(0, N).

Complete Code

#Enable interactive plot
%matplotlib notebook
import math
from matplotlib.path import Path
from matplotlib.animation import FuncAnimation
from matplotlib.path import Path
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import ConvexHull
from matplotlib.artist import Artist

N = 10000

# create necessary arrays
x = np.arange(0, N)
y = np.zeros(N)

# set initial points to zero
inHull = 0


def inCircle(point):
    # the function is given a point in R^n
    # returns a boolean stating if the norm of the point is smaller than 1.
    if np.sum(np.square(point)) <= 1:
        return True
    else:
        return False


# iterate over each point
for i in range(N):
    random_point = np.random.rand(2)*2 - 1

    # determine if the point is inside the hull
    if inCircle(random_point):
        inHull  = 1

    # we store areas in array y.
    y[i] = (inHull*4)/(i   1)

fig = plt.figure()
ax = plt.subplot(1, 1, 1)
data_skip = 20
txt = ax.text(N*0.6, max(y)   0.25, "")

def init_func():
    ax.clear()
    plt.xlabel('n points')
    plt.ylabel('Estimated area')
    plt.xlim((x[0], x[-1]))
    plt.ylim((min(y) - 1, max(y)   0.5))


def update_plot(i):
    ax.clear()
    ax.plot(x[:i   data_skip], y[:i   data_skip], color = 'k')
    ax.scatter(x[i], y[i], color = 'none')

    ax.text(N*0.6, max(y)   0.25, "Estimation: "   str(round(y[i], 5)))
    ax.set_xlim(0, N)


anim = FuncAnimation(fig,
                     update_plot,
                     frames = np.arange(0, len(x), data_skip),
                     init_func = init_func,
                     interval = 20)

plt.show()

Animation

enter image description here

  • Related