1 回答

TA貢獻1946條經驗 獲得超3個贊
您似乎誤解了matplotlib.animation.funcanimation的工作原理,我強烈建議您查看網上可以找到的眾多示例中的一些。讓我們試試這個版本,如下所示:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import random
vertices = np.array([[0,0],
[2,0],
[1,2.5],
[0,0]])
dots = 1000
# lower and higher bounds for x to be generated
int_lb = np.min(vertices[:,0])
int_hb = np.max(vertices[:,0])
def newPos(index, old_x, old_y):
vertex_x = vertices[index][0]
vertex_y = vertices[index][1]
new_x = 0.5*(vertex_x + old_x)
new_y = 0.5*(vertex_y + old_y)
return([new_x,new_y])
# evaluating all your points
points = np.array([[0.25, 0.1]])
for j in range(dots-1):
points = np.concatenate((points, [newPos(random.randint(int_lb,int_hb), points[j][0], points[j][1])]), axis=0)
fig = plt.figure()
ax = plt.gca()
ax.set_xlim([np.min(vertices[:,0])-0.05*np.max(vertices[:,0]),1.05*np.max(vertices[:,0])])
ax.set_ylim([np.min(vertices[:,1])-0.05*np.max(vertices[:,1]),1.05*np.max(vertices[:,1])])
ax.set_title('Chaos Game with {a} Vertices and Steps'.format(a=len(vertices)-1, b=dots))
# draw boundaries
ax.plot(vertices[:,0],vertices[:,1],'k-', linewidth=1)
# initialize scatter object for current step and all evaluated dots
scat_curr = ax.scatter([], [], marker='X', s=15, c='black')
scat_dots = ax.scatter([], [], marker='o', s=5, c='#1f77b4',zorder=-1)
def init():
scat_curr.set_offsets(np.c_[vertices[0,0], vertices[0,1]])
scat_dots.set_offsets(np.c_[vertices[0,0], vertices[0,1]])
return scat_curr, scat_dots
def animate(i):
scat_curr.set_offsets(np.c_[points[i,0], points[i,1]])
scat_dots.set_offsets(np.c_[points[:i,0], points[:i,1]])
ax.legend([scat_curr],['iter i = {a}'.format(a=i)], loc='upper left')
return scat_curr, scat_dots
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=dots, interval=10)
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)
anim.save('some_nice_triforces.mp4', writer=writer)
這使:
https://i.stack.imgur.com/6X68l.gif
如果您有任何問題,我會添加更多評論,但由于這主要是您自己在這里的工作,我相信您會發現您所嘗試的遠比應該做的復雜:)。希望這可以幫助。
添加回答
舉報