我一直在尝试在matplotlib
中重建this动画,大致遵循以下线索的答案:matplotlib animation multiple datasets(这是PI的蒙特卡罗近似值)。你知道吗
我想知道如何在我的绘图中积累帧,以便每帧在先前绘制的帧的基础上添加额外的点,这样随着时间的推移,这些点变得越来越密集。另外,我是否必须从根本上重写代码,因为PI的近似值要求我在每次迭代中计算蓝点和红点的数量?你知道吗
fig, ax = plt.subplots(figsize=(5,5))
plt.rcParams['animation.ffmpeg_path'] = r'C:\FFmpeg\bin\ffmpeg'
b_sc = ax.scatter([],[],s=1,c='b')
r_sc = ax.scatter([],[],s=1,c='r')
def init():
ax.set_ylim(0,1)
ax.set_xlim(0,1)
return b_sc,r_sc
def update(frame):
org = np.array([0,0])
r, b = (0,0)
np.random.seed(frame)
dots = np.random.rand(100,2)
blue = np.array([dot for dot in dots if np.linalg.norm(org-dot) <= 1])
red = np.array([dot for dot in dots if np.linalg.norm(org-dot) > 1])
dr, db = red.shape[0], blue.shape[0]
r += dr
b += db
pi = b/(frame*(100))*4
if db != 0:
b_sc.set_offsets(blue)
if dr != 0:
r_sc.set_offsets(red)
# ax.figure.canvas.draw()
return b_sc,r_sc
FFwriter = animation.FFMpegWriter(fps=144)
ani = FuncAnimation(fig, update, frames=range(1,100), interval=1,
init_func=init, blit=True)
plt.show()
实际上,您可以使用
extend
方法为该动画利用列表的可变性。你知道吗这个小小的编辑让我感觉很好。多有趣的计算圆周率的方法啊!你知道吗
相关问题 更多 >
编程相关推荐