在 matplotlib 中修补动画

问题描述 投票:0回答:1

我正在尝试使用 matplotlib 创建一个简单的粒子动画,如下所示:

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

fig = plt.figure()
fig.set_dpi(100)
fig.set_size_inches(7, 6.5)

ax = plt.axes(xlim=(0, 10), ylim=(0, 10))
patch = plt.Circle((5, -5), 0.75, fc='y')

def init():
    patch.center = (5, 5)
    ax.add_patch(patch)
    return patch,

def animate(i):
    x, y = patch.center
    x = 5 + 3 * np.sin(np.radians(i))
    y = 5 + 3 * np.cos(np.radians(i))
    patch.center = (x, y)
    return patch,

anim = animation.FuncAnimation(fig, animate, 
                               init_func=init, 
                               frames=36, 
                               interval=20,
                               blit=True)

HTML(anim.to_jshtml())

现在,我想将 plt.Circle 对象包装在“Particle”类中,以便我可以添加其他功能(例如赋予它速度等)。这是我尝试过的:

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

fig = plt.figure()
fig.set_dpi(100)
fig.set_size_inches(7, 6.5)

ax = plt.axes(xlim=(0, 10), ylim=(0, 10))

class Particle:
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def show(self):
        return plt.Circle((self.x, self.y), 0.75, fc='y')

p = Particle(5, -5)

def init():
    ax.add_patch(p.show())
    return p.show(),

def animate(i):
    p.x = 5 + 3 * np.sin(np.radians(i))
    p.y = 5 + 3 * np.cos(np.radians(i))
    return p.show(),

anim = animation.FuncAnimation(fig, animate, 
                               init_func=init, 
                               frames=36, 
                               interval=20,
                               blit=True)

HTML(anim.to_jshtml())

为什么这不起作用?

我希望它的行为与第一个代码相同,因为 p.show() 返回一个 plt.Circle 对象。

python matplotlib animation
1个回答
0
投票

您应该更新现有 Circle 对象的位置。

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from IPython.display import HTML

fig = plt.figure()
fig.set_dpi(100)
fig.set_size_inches(7, 6.5)

ax = plt.axes(xlim=(0, 10), ylim=(0, 10))

class Particle:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.circle = plt.Circle((self.x, self.y), 0.75, fc='y')

    def show(self):
        self.circle.set_center((self.x, self.y))
        return self.circle

p = Particle(5, 5)
ax.add_patch(p.show())

def init():
    p.show()
    return p.show(),

def animate(i):
    p.x = 5 + 3 * np.sin(np.radians(i * 10))
    p.y = 5 + 3 * np.cos(np.radians(i * 10))
    p.show()
    return p.show(),

anim = animation.FuncAnimation(fig, animate, 
                               init_func=init, 
                               frames=36, 
                               interval=100,
                               blit=True)

HTML(anim.to_jshtml())
© www.soinside.com 2019 - 2024. All rights reserved.