Matplotlib动画:从scipy数组设置圆位置动画

2024-10-01 09:24:49 发布

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

我正在尝试在matplotlib中设置圆的位置动画,但我不认为它是正确的

我的数据是二维矩阵大小((1000,4))每行包含4个圆的y位置,x总是1

import numpy as np
from matplotlib import pyplot
from matplotlib import animation

data = np.zeros((1000,4))

fig=pyplot.figure()
ax=pyplot.axes([0,40,0,40])
circle1=pyplot.Circle((data[0,0],1),0.2,fc='y')
circle2=pyplot.Circle((data[0,1],1),0.2,fc='g')
circle3=pyplot.Circle((data[0,2],1),0.2,fc='r')
circle4=pyplot.Circle((data[0,3],1),0.2,fc='b')

def init():
    circle1.center=(data[0,0],1)
    circle2.center=(data[0,1],1)
    circle3.center=(data[0,2],1)
    circle4.center=(data[0,3],1)
    ax.add_patch(circle1)
    ax.add_patch(circle2)
    ax.add_patch(circle3)
    ax.add_patch(circle4)
    return circle1, circle2, circle3, circle4

def animate(i):
    for state in data:
        circle1.center=(state[0],1)
        circle2.center=(state[1],1)
        circle3.center=(state[2],1)
        circle4.center=(state[3],1)
    return circle1, circle2, circle3, circle4
anim=animation.FuncAnimation(fig,animate,init_func=init,frames=1000,blit=True)

pyplot.show()

将引发以下错误:

^{pr2}$

Tags: importadddatamatplotlibaxpatchcenterstate
1条回答
网友
1楼 · 发布于 2024-10-01 09:24:49

我修复了你代码中的一些部分。在

  1. 我在data中添加了一些值,以便使圆具有动画效果。在
  2. 您可能希望在每个时间步将圆的中心放在data中,那么animate中的for循环是不必要的。在
  3. 如果您不使用Qt4Agg后端,在Mac上animation函数似乎不能与{}一起工作。如果你用Mac,你可能需要在下面加上前两行。在

import matplotlib
matplotlib.use('Qt4Agg')

import numpy as np
from matplotlib import pyplot
from matplotlib import animation
from math import sin

data = np.zeros((1000,4))

data[:,0] = [20*(1+sin(float(x)/200)) for x in range(1000)]
data[:,1] = [20*(1+sin(float(x)/100)) for x in range(1000)]
data[:,2] = [20*(1+sin(float(x)/50)) for x in range(1000)]
data[:,3] = [20*(1+sin(float(x)/25)) for x in range(1000)]

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

circle1=pyplot.Circle((data[0,0],1.0),0.2,fc='y')
circle2=pyplot.Circle((data[0,1],1.0),0.2,fc='g')
circle3=pyplot.Circle((data[0,2],1.0),0.2,fc='r')
circle4=pyplot.Circle((data[0,3],1.0),0.2,fc='b')

def init():
    circle1.center=(data[0,0],1)
    circle2.center=(data[0,1],1) 
    circle3.center=(data[0,2],1)
    circle4.center=(data[0,3],1)
    ax.add_patch(circle1)
    ax.add_patch(circle2)
    ax.add_patch(circle3)
    ax.add_patch(circle4)
    return circle1, circle2, circle3, circle4

def animate(i):
    # for state in data:
    circle1.center=(data[i,0],1)
    circle2.center=(data[i,1],1)
    circle3.center=(data[i,2],1)
    circle4.center=(data[i,3],1)
    return circle1, circle2, circle3, circle4


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

pyplot.show()

相关问题 更多 >