matplotlib动画打印所有点,而不仅仅是最新的迭代

2024-09-23 22:29:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用matplotlib设置一组在2D空间中移动的点的动画。它目前的工作方式是,它的代码确实产生了一个动画点,但这不是我认为它将如何工作。它不是在每一个时间点绘制点,而是在所有时间点绘制它们。

例如,如果代码运行时有20个点,我希望它在一个帧显示20个点,然后在下一个帧显示相同的点,依此类推。相反,它保留了之前的帧点,而不只是显示新的帧点。

有人能告诉我我哪里出错了吗?

当我的研究发现一个真正的动画问题时,我也会把它作为一个真正的问题来追溯,但我也会把它作为一个真正的问题来解决:

文件“C:\Users\Anaconda3\lib\site packages\matplotlib\动画.py“,第1568行,在绘图框中 a、 设置动画(self.\u blit)

属性错误:'努比·恩达雷'对象没有属性'set\u animated'

我也不知道为什么会这样,网上搜索也没有帮助。

代码如下:

import matplotlib.pyplot as plt #Import plotting library
from matplotlib import animation
import numpy as np #Import numpy library

dim = 2             #Defines the dimensionality of the system
n = 25               #Number of BOIDS
tmax = 80             #Length of sim
dmax = 5            #Distance boids can "see", determines what other boids interact with them
o = np.zeros(dim) #Origin as vector
r = np.random.rand(n,dim) #Places BOIDs randomly with co-ordinates (x,y,z) from 0 to 1. Has dimensions n and dim
v = 2*np.random.rand(n,dim)-1#Sets initial velocity of each BOID from -1 to 1 in each cardinal direction
rt = np.zeros((tmax,n,dim)) #This array contains the whole system's positions at each point in time
x = np.empty(n)
y = np.empty(n)
d = np.zeros(n)
vk = np.zeros((n,2))
vksum = np.zeros((n,2))
pltx = np.zeros((tmax,n))
plty = np.zeros((tmax,n))
"""rt[a][b][0] is the x co-ordinate of boid n=b at t=a
   rt[a][b][1] is the y co-ordiante of boid n=b at t=a
   np.linalg.norm gives the modulus of an array, check documentation for arguments"""

fig, ax = plt.subplots(figsize=(14,9))
ax.grid(True,linestyle='-',color='0.75') #Sets up a grid on subplot
ax.set_xlim(-50,50)
ax.set_ylim(-50,50) #Set limits for x and y axes 

for t in range (0,tmax):
    for i in range (0,n):
        for k in range (0,n):
            if abs(k-n)>0:
                d[k] = ((r[i][0]-r[k][0])**2+(r[i][1]-r[k][1])**2)**(1/2) #Checks distance from ith boid to each other boid
            if (d[k]-dmax)<0:   #If they are within range of the ith boid
                vk[k] = (v[i] +v[k])/((np.linalg.norm(v[i]))*np.linalg.norm(v[k]))#Aligns the velocity of ith boid toward the velocity of the kth boid
        for l in range (0,n):
            vksum[i] = vksum[i] + vk[l] #Sums the boid's velocity contributions together
        v[i] = (3/4)*v[i] + (vksum[i]/np.linalg.norm(vksum[i])) #Sets the boid's new velocity 
        r[i] = r[i] + v[i]  #Sets the boid's new position
        rt[t][i] = r[i] #Logs the position of the boid in the time array
        pltx[t][i] = r[i][0]
        plty[t][i] = r[i][1]


def init():
    for i in range (0,n):
        x[i] = rt[0][i][0]
        y[i] = rt[0][i][1]
    return x,y,  

def update(j):
    for i in range (0,n):
        x[i] = rt[j][i][0]
        y[i] = rt[j][i][1]
    points = ax.scatter(x[:],y[:],c='r')
    return x,y

anim = animation.FuncAnimation(fig, update, frames=tmax, interval=50,blit=True)

Tags: oftheinfornpzerosrange动画
2条回答

使用ax.clear()删除以前的点(当您使用blit=False时)

def update(j):

    ax.clear()

    for i in range (0,n):
        x[i] = rt[j][i][0]
        y[i] = rt[j][i][1]
    points = ax.scatter(x[:], y[:], c='r')

    return x,y

我知道furas' answers为您的问题提供了一个修复方法,但是这里有关于您的问题的更多解释。在

首先,闪电战。如果您想使用bliting,您的update()函数needs to return a list of updated artists。返回的是两个numpy数组,但是应该return points,。在

关于绘制保留前一个时间点的点的第二个问题是由于在每次迭代中重复调用ax.scatter()。与正常的matplotlib行为类似,如果在同一个轴上执行两个scatter()调用,则会得到两组点。在

动画的一般建议是在初始化阶段创建一个艺术家(可以是使用plot()或{}(如果是scatter())的Line2D对象),然后在update函数中更新该艺术家的属性(颜色、位置等),而不创建新的艺术家。在

考虑到所有这些因素,您的代码最终会:

dim = 2             #Defines the dimensionality of the system
n = 25               #Number of BOIDS
tmax = 80             #Length of sim
dmax = 5            #Distance boids can "see", determines what other boids interact with them
o = np.zeros(dim) #Origin as vector
r = np.random.rand(n,dim) #Places BOIDs randomly with co-ordinates (x,y,z) from 0 to 1. Has dimensions n and dim
v = 2*np.random.rand(n,dim)-1#Sets initial velocity of each BOID from -1 to 1 in each cardinal direction
rt = np.zeros((tmax,n,dim)) #This array contains the whole system's positions at each point in time
x = np.empty(n)
y = np.empty(n)
d = np.zeros(n)
vk = np.zeros((n,2))
vksum = np.zeros((n,2))
pltx = np.zeros((tmax,n))
plty = np.zeros((tmax,n))
"""rt[a][b][0] is the x co-ordinate of boid n=b at t=a
   rt[a][b][1] is the y co-ordiante of boid n=b at t=a
   np.linalg.norm gives the modulus of an array, check documentation for arguments"""

fig, ax = plt.subplots(figsize=(14,9))
ax.grid(True,linestyle='-',color='0.75') #Sets up a grid on subplot
ax.set_xlim(-50,50)
ax.set_ylim(-50,50) #Set limits for x and y axes

# initialize an empty PathCollection artist, to be updated at each iteration
points = ax.scatter([],[],c='r')    

for t in range (0,tmax):
    for i in range (0,n):
        for k in range (0,n):
            if abs(k-n)>0:
                d[k] = ((r[i][0]-r[k][0])**2+(r[i][1]-r[k][1])**2)**(1/2) #Checks distance from ith boid to each other boid
            if (d[k]-dmax)<0:   #If they are within range of the ith boid
                vk[k] = (v[i] +v[k])/((np.linalg.norm(v[i]))*np.linalg.norm(v[k]))#Aligns the velocity of ith boid toward the velocity of the kth boid
        for l in range (0,n):
            vksum[i] = vksum[i] + vk[l] #Sums the boid's velocity contributions together
        v[i] = (3/4)*v[i] + (vksum[i]/np.linalg.norm(vksum[i])) #Sets the boid's new velocity 
        r[i] = r[i] + v[i]  #Sets the boid's new position
        rt[t][i] = r[i] #Logs the position of the boid in the time array
        pltx[t][i] = r[i][0]
        plty[t][i] = r[i][1]


def init():
    for i in range (0,n):
        x[i] = rt[0][i][0]
        y[i] = rt[0][i][1]
    return x,y,  

def update(j):
    for i in range (0,n):
        x[i] = rt[j][i][0]
        y[i] = rt[j][i][1]
    xy = np.hstack((x,y))
    points.set_offsets(xy) # update the coordinates of the PathCollection members
    return points, # return the updated artist(s) for blitting

anim = animation.FuncAnimation(fig, update, frames=tmax, interval=50,blit=True)

enter image description here

相关问题 更多 >