我对Python中的动画有一些疑问。我不明白,为什么动画只绘制初始化帧。根本没有调用函数redraw
,这就是问题所在。对我来说,函数redraw
和init
之间没有区别,所以这很奇怪。参数k
也许是帧号
我试图在文档matplotlib.animation.FuncAnimation中找到某些内容,但未成功
那么有人可以帮忙吗?
import random
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# function of initialization
def init(x, y, a, b, bottom, top, ax):
ax.plot(x, y, color = 'blue', linewidth = 1)
ax.plot([a, a], [bottom, top], color = 'red', linewidth = 1)
ax.plot([a, b], [top, top], color = 'red', linewidth = 1)
ax.plot([b, b], [top, bottom], color = 'red', linewidth = 1)
ax.plot([b, a], [bottom, bottom], color = 'red', linewidth = 1)
# this function draw dot with random coordinates
def redraw(k, a, b, bottom, top, f, ax):
x_dot = random.uniform(a, b)
y_dot = random.uniform(bottom, top)
if y_dot <= f(x_dot) and y_dot >= 0:
clr = 'blue'
else:
clr = 'red'
ax.plot(x_dot, y_dot, color = clr, marker = 'o', markersize = 10)
# main function with animation
def method_monte_carlo(f, N, a, b):
delta_x = 0.01
x = np.arange(a, b+delta_x, delta_x)
y = f(x)
bottom = 0
top = np.max(y)
fig = plt.figure(figsize = (15, 15))
ax = fig.add_subplot(1, 1, 1)
animation.FuncAnimation(fig, redraw, frames = N, interval = 10,
init_func = init(x, y, a, b, bottom, top, ax), repeat = False,
fargs = (a, b, bottom, top, f, ax))
def g(x):
return np.cos(x)**2
method_monte_carlo(g, 1000, 0, np.pi)
P.S。我使用Spyder v.3.3.2