无法让我的程序在matplotlib

时间:2018-02-18 19:53:12

标签: python animation matplotlib plot

我正在尝试使用n在2D中设置matplotlib个圈子的动画,但是在运行时,我的代码只显示一个静止的圆圈,无论我做什么n。有谁知道如何解决它,以及它有什么问题?

%matplotlib notebook
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

fig=plt.figure()
ax = plt.axes(xlim=(0, 40), ylim=(0, 40))

number_of_particles = int(input("How many particles would you like?"))
data = np.zeros((1000,number_of_particles))
dict_of_circles = {}
for n in range(number_of_particles):
    data[:,n] = [20*(1+np.sin(float(x)/50*n+50)) for x in range(1000)]
    dict_of_circles["circle"+str(n+1)] = plt.Circle((data[0,n],1.0),0.5,fc='b')


def init():
    for n in range(number_of_particles):
        dict_of_circles["circle"+str(n+1)].center = (data[0,n],1)
        ax.add_patch(dict_of_circles["circle"+str(n+1)])
        return dict_of_circles["circle"+str(n+1)]

def animate(i):
    for n in range(number_of_particles):
        dict_of_circles["circle"+str(n+1)].center = (data[i,n],1)
        return dict_of_circles["circle"+str(n+1)]

anim=animation.FuncAnimation(fig,animate,init_func=init,frames=1000,blit=True)

plt.show()

1 个答案:

答案 0 :(得分:1)

两个问题:

  1. 缩进是错误的。您需要从函数返回而不是从循环中返回。
  2. 您需要返回一个可迭代的艺术家,而不是一个艺术家,因为您希望所有艺术家都能更新。
  3. 完整代码:

    import numpy as np
    from matplotlib import pyplot as plt
    from matplotlib import animation
    
    fig=plt.figure()
    ax = plt.axes(xlim=(0, 40), ylim=(0, 40))
    
    number_of_particles = 10
    data = np.zeros((1000,number_of_particles))
    dict_of_circles = {}
    for n in range(number_of_particles):
        data[:,n] = [20*(1+np.sin(float(x)/50*n+50)) for x in range(1000)]
        dict_of_circles["circle"+str(n+1)] = plt.Circle((data[0,n],1.0),0.5,fc='b')
    
    
    def init():
        for n in range(number_of_particles):
            dict_of_circles["circle"+str(n+1)].center = (data[0,n],1)
            ax.add_patch(dict_of_circles["circle"+str(n+1)])
        return dict_of_circles.values()
    
    def animate(i):
        for n in range(number_of_particles):
            dict_of_circles["circle"+str(n+1)].center = (data[i,n],1)
        return dict_of_circles.values()
    
    anim=animation.FuncAnimation(fig,animate,init_func=init,frames=1000,blit=True)
    
    plt.show()