首页 > 解决方案 > 粒子碰撞动画Python

问题描述

我正在尝试在一个轴对象中为粒子碰撞动画制作动画,同时在另一个轴对象中绘制一些数据(使用 matplotlib.gridspec)。我使用测试数据设置了一个测试环境,将碰撞简化为仅在轴 1 中出现的圆圈(matplotlib.patches.Circle 对象)并在轴 2 中绘制正弦函数(matplotlib.lines.Line2D 对象)。动画一次只适用于一个轴,但我不能同时运行两个轴动画。

我认为问题与 init() 和 animate(i) 函数中的返回对象有关。“matplotlib.patches”和“matplotlib.lines”对象结合动画有问题,但我不知道为什么。这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.animation import FuncAnimation
from matplotlib.gridspec import GridSpec

#%% setup test data
xy = (0.5, 0.5)
r = 0.02
i = np.arange(10,110)

#%% setup figure

fig = plt.figure(figsize = (8,8))
gs = GridSpec(6,4, figure=fig, wspace=0, hspace=0) 

ax0 = fig.add_subplot(gs[0:4,0:4])

ax1 = fig.add_subplot(gs[5:6,0:4])
ax1.set_xlim(0,100)
# assigning labels
circles = []
ln1, = ax1.plot([],[], 'r')

def init():
    ln1.set_data([],[])
    circles = []
    return circles, ln1

def animate(i):

    xy = (np.random.random(), np.random.random())

    circles.append(ax0.add_patch(Circle(xy,r)))
    x = np.linspace(0,100,100)
    y = np.sin(x)

    mask1 = x < i
    x1 = x[mask1]
    y1 = y[mask1]

    ln1.set_data(x1, y1)

    return circles, ln1

ani = FuncAnimation(fig, animate, init_func=init, frames = i, blit=True, interval = 1)

plt.show()

那是我收到的错误消息:

Traceback (most recent call last):
  File "C:\Users\flofr\anaconda3\lib\site-packages\matplotlib\cbook\__init__.py", line 216, in process
    func(*args, **kwargs)
  File "C:\Users\flofr\anaconda3\lib\site-packages\matplotlib\animation.py", line 953, in _start
    self._init_draw()
  File "C:\Users\flofr\anaconda3\lib\site-packages\matplotlib\animation.py", line 1741, in _init_draw
    a.set_animated(self._blit)
AttributeError: 'list' object has no attribute 'set_animated'
Traceback (most recent call last):
  File "C:\Users\flofr\anaconda3\lib\site-packages\matplotlib\cbook\__init__.py", line 216, in process
    func(*args, **kwargs)
  File "C:\Users\flofr\anaconda3\lib\site-packages\matplotlib\animation.py", line 1269, in _handle_resize
    self._init_draw()
  File "C:\Users\flofr\anaconda3\lib\site-packages\matplotlib\animation.py", line 1741, in _init_draw
    a.set_animated(self._blit)
AttributeError: 'list' object has no attribute 'set_animated'

我试图测试 init() 的返回值是否正确,似乎是这样。

输入:


def init():
    ln1.set_data([],[])
    circles = []
    circles.append(ax0.add_patch(Circle(xy,r)))

    return ln1, circles

a, b = init()
print(a)
print(b)

输出:

Line2D(_line0)
[<matplotlib.patches.Circle object at 0x000001E7DE16F548>]

以下是模拟的三种状态。图一显示了布局,图二是轴 1 模拟(圆形),图三是轴 2 模拟(正弦)。

标签: pythonmatplotlibanimation

解决方案


推荐阅读