Зависимый от времени сюжет matplotlib - PullRequest
0 голосов
/ 11 мая 2018

Я бы хотел построить точечную синусоидальную волну в Python через Matplotlib, для которой каждая точка добавляется каждые x миллисекунд, чтобы получить плавную анимацию чертежа.

Это моя попытка:

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

fig, ax = plt.subplots()

x = [0]
line, = ax.plot(x, np.asarray(0))


def animate(i):
    x.append(x[-1]+0.04)
    line.set_xdata(np.asarray(x)*2*np.pi/5)
    line.set_ydata(np.sin(np.asarray(x)*2*np.pi/5))
    plt.draw()

def init():
    line.set_ydata(np.ma.array(x, mask=True))
    return line,

ani = animation.FuncAnimation(fig, animate, 10, init_func=init, interval=40, blit=True)

plt.show()

Что поднимает:

RuntimeError: The animation function must return a sequence of Artist objects.

Что я ошибся?Какой, по вашему мнению, наиболее эффективный способ получить этот эффект?

PS Ось времени должна оставаться фиксированной и не двигаться, поэтому она должна быть шире графика

Ответы [ 2 ]

0 голосов
/ 11 мая 2018

Animate должно возвращать последовательность объектов художника:

Вы должны добавить:

return line, до конца функции анимации

def animate(i):
    x.append(x[-1]+0.04)
    line.set_xdata(np.asarray(x)*2*np.pi/5)
    line.set_ydata(np.sin(np.asarray(x)*2*np.pi/5))
    return line,

Источник:

Другой ответ

Простой пример

0 голосов
/ 11 мая 2018

Во-первых, вы получаете ошибку, потому что ваш animate(i) ничего не возвращает. Вам необходимо вернуть line,. Во-вторых, вы не используете i в animate(i).

Вот простая анимация синусоиды от https://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/:

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

# First set up the figure, the axis, and the plot element we want to 
animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have 
changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                           frames=200, interval=20, blit=True)

plt.show()

В ссылке есть дополнительное вдохновение, которое может помочь вам в дальнейшем.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...