Ошибка ввода с использованием анимации matplotlib

#python #matplotlib #animation

#python #matplotlib #Анимация

Вопрос:

У меня возникли проблемы с созданием анимации движения частиц. Данные о местоположении частиц (среди прочих свойств) хранятся в заголовке словаря «история». Обычно это animationstation.py-файл импортирует «историю» из MAIN.py досье. Однако для удобства я включил короткий пример в history.txt файл, из которого этот анимационный файл считывает словарь «история». Содержимое текстового файла:

 [{'m': [6.28e-16, 6.28e-16, 6.28e-16, 6.28e-16], 'q': [3.14e-15, 3.14e-15, 3.14e-15, 3.14e-15], 'rad': [5e-07, 5e-07, 5e-07, 5e-07], 'x': [0, 0.0, 0.0, 0.0], 'y': [0, 9.600000000000001e-08, 1.9200000000000003e-07, 2.8800000000000004e-07], 'z': [0.020094615, 0.020094615002866825, 0.020094615011467296, 0.020094615025801416], 'vx': [0, 0.0, 0.0, 0.0], 'vy': [96, 96.0, 96.0, 96.0], 'vz': [0, 0.00573364787230897, 0.01146729574461794, 0.017200943616926912], 'ax': [0, 0.0, 0.0, 0.0], 'ay': [0, 0, 0, 0], 'az': [0, 5733647.87230897, 5733647.87230897, 5733647.87230897], 'F_Ex': [0, 0.0, 0.0, 0.0], 'F_Ey': [0, 0.0, 0.0, 0.0], 'F_Ez': [0, 3.6007370244900336e-09, 3.6007370244900336e-09, 3.6007370244900336e-09], 'F_Cx': [0, 0.0, 0.0, 0.0], 'F_Cy': [0, 0.0, 0.0, 0.0], 'F_Cz': [0, 0.0, 0.0, 0.0], 'F_Gx': [0, 0, 0, 0], 'F_Gy': [0, 0, 0, 0], 'F_Gz': [0, 0, 0, 0], 'F_Dx': [0, 0, 0, 0], 'F_Dy': [0, 0, 0, 0], 'F_Dz': [0, 0, 0, 0], 'parent_index': 0, 'number': 0}]
  

Кажется, что код проходит гладко через makeFigure() и init() fn.s, но никогда не попадает в animate() fn .

 #Built-in Packages
import matplotlib
matplotlib.use("TkAgg")
from matplotlib import pyplot as plt
from matplotlib import animation

#Custom Modules
#from MAIN import history  #this is how the file usually runs
    
#read in history from text file (.txt content given above for minimum reproducible example)
hist = open("history.txt", "r")
history = eval(hist.read())
hist.close()
    
#settings to save animation:
Writer = animation.writers['ffmpeg']
writer = Writer(fps=40, metadata=dict(artist='Me'), codec='mpeg4', bitrate=1000000)

def makeFigure(history):

    fig = plt.figure(1)
    ax = plt.axes()
    line, = ax.plot([], [], lw=2, marker='o', markersize=2)

    #Create list of particle location data
    xdata, zdata = [], []
    for i in range(len(history)):
        xdata.append([history[i]["x"]])
        zdata.append([history[i]["z"]])

    #Create shells (no data yet) of individual plots for each particle
    Current = []
    for i, p in enumerate(history):
        p = ax.plot([], [], 'o', lw=2, markersize=2, color="blue")[0]
        Current.append(p)

    return xdata, zdata, [fig, ax, line], Current

def init():  #Create shells for each particle to fill with data

    for p in Current:
        p.set_data([], [])

    return Current

def animate(step):  #Update particle location

    for i, p in enumerate(Current):
        p.set_data(xdata[i][step], zdata[i][step])

    return Current


xdata, zdata, [fig, ax, line], Current = makeFigure(history) #Creat figure for animation

anim = animation.FuncAnimation(fig, animate, init_func=init(), frames=len(history[0]["x"]), interval=100, blit=True, repeat=False)
anim.save('basic_animation.mp4', writer=writer)
  

Вот сообщение об ошибке, которое я получаю при запуске:

 /Users/mckennadavis/.virtualenvs/gitdeli/bin/python/Users/mckennadavis/PycharmProjects/gitdeli/SimpleAnim.py
Traceback (most recent call last):
  File "/Users/mckennadavis/PycharmProjects/gitdeli/SimpleAnim.py", line 56, in <module>
    anim.save('basic_animation.mp4', writer=writer)
  File "/Users/mckennadavis/.virtualenvs/gitdeli/lib/python3.7/site-packages/matplotlib/animation.py", line 1128, in save
    anim._init_draw()  # Clear the initial frame
  File "/Users/mckennadavis/.virtualenvs/gitdeli/lib/python3.7/site-packages/matplotlib/animation.py", line 1706, in _init_draw
    self._drawn_artists = self._init_func()
TypeError: 'list' object is not callable

Process finished with exit code 1
  

Ответ №1:

вам нужно передать функцию init init_func= , а не возвращаемое значение функции init()

 animation.FuncAnimation(fig, animate, init_func=init, ...)
  

обратите внимание на отсутствие () после init