Home > Enterprise >  Can someone help me write an animation function for this python code?
Can someone help me write an animation function for this python code?

Time:04-21

I am trying to learn how to animate this graph that calculates the integral of a function using the montecarlo method but to no success. I don't have much understanding of python, this is my first code besides learning some language basics a few years ago. This is what I wrote so far.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
N = 100000
print("N=", N)
x_list = []
y_list = []
x_list.append(np.random.uniform(low=-5, high=5, size=[N, 1]))
y_list.append(np.random.uniform(low=0, high=2, size=[N, 1]))


x = np.array(x_list)
y = np.array(y_list)

ins = y - np.exp((-x**2) / 2) < 0
ap_pi = 20 * np.sum(ins) / N
print('pi: {}, approximation: {}'.format(np.pi, ap_pi))
print(ap_pi)
x_in = x[ins]
y_in = y[ins]

fig = plt.figure(figsize=[10, 10])

plt.text(1, 2.145, "Value of the integral:", fontsize=14)
plt.text(4, 2.15, ap_pi, bbox=dict(facecolor='red', alpha=0.5))
plt.scatter(x_list, y_list, s=1)
plt.scatter(x_in, y_in, color='r', s=1)


def animation(i):
    

anim = FuncAnimation(fig, animation, frames=100, interval=20)
plt.pause(0.01)
plt.show()

I did try moving plt.scatter to the animation function but this only resulted in animating the colors somehow. I also tried multiple stuff but ended up with loops of opening the graph itself. I have no idea how to proceed towards this. Any help?

CodePudding user response:

This should be a good starting point:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
N = 100000
print("N=", N)

x = np.random.uniform(-5, 5, N)
y = np.random.uniform(0, 2, N)

ins = y - np.exp((-x**2) / 2) < 0
ap_pi = 20 * np.sum(ins) / N
print('pi: {}, approximation: {}'.format(np.pi, ap_pi))
print(ap_pi)
x_in = x[ins]
y_in = y[ins]

def animation(i):
    line1.set_data(x[:i], y[:i])
    if i < len(x_in):
        # remember that len(x_in) < N
        line2.set_data(x_in[:i], y_in[:i])

fig = plt.figure(figsize=[10, 10])
ax = fig.add_subplot(1, 1, 1)

ax.set_xlim(-5, 5)
ax.set_ylim(0, 2)
ax.text(1, 2.145, "Value of the integral:", fontsize=14)
ax.text(4, 2.15, ap_pi, bbox=dict(facecolor='red', alpha=0.5))

# initialize empty scatter plots. They will receive updated data below.
# NOTE: I'm using `ax.plot` because I know what method I have to call
# when updating data. If I use `ax.scatter`, who knows... :|
line1, = ax.plot([], [], 'o')
line2, = ax.plot([], [], 'o', color='r')

# The length of the animation is given by N
anim = FuncAnimation(fig, animation, frames=N, interval=20)
plt.show()
  • Related