Matplotlib imshow(): как оживить?
Я нашел этот замечательный короткий учебник по анимации:
http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/
однако я не могу создать анимированный график imshow() такого же способа.
Я попытался заменить некоторые строки:
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 10), ylim=(0, 10))
#line, = ax.plot([], [], lw=2)
a=np.random.random((5,5))
im=plt.imshow(a,interpolation='none')
# initialization function: plot the background of each frame
def init():
im.set_data(np.random.random((5,5)))
return im
# animation function. This is called sequentially
def animate(i):
a=im.get_array()
a=a*np.exp(-0.001*i) # exponential decay of the values
im.set_array(a)
return im
но я сталкиваюсь с ошибками
вы можете помочь мне запустить это?
заранее спасибо.
лучше,
Ответы
Ответ 1
Вы очень близки, но одна ошибка - init
и animate
должна возвращать iterables, содержащие анимированные художники. Поэтому в версии Jake они возвращают line,
(на самом деле кортеж), а не line
(который является единственным строковым объектом). К сожалению, документы не ясны на этом!
Вы можете исправить свою версию следующим образом:
# initialization function: plot the background of each frame
def init():
im.set_data(np.random.random((5,5)))
return [im]
# animation function. This is called sequentially
def animate(i):
a=im.get_array()
a=a*np.exp(-0.001*i) # exponential decay of the values
im.set_array(a)
return [im]
Ответ 2
Вот полный пример:
# Usually we use '%matplotlib inline'. However we need 'notebook' for the anim to render in the notebook.
%matplotlib notebook
import random
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fps = 30
nSeconds = 5
snapshots = [ np.random.rand(5,5) for _ in range( nSeconds * fps ) ]
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure( figsize=(8,8) )
a = snapshots[0]
im = plt.imshow(a, interpolation='none', aspect='auto', vmin=0, vmax=1)
def animate_func(i):
if i % fps == 0:
print( '.', end ='' )
im.set_array(snapshots[i])
return [im]
anim = animation.FuncAnimation(
fig,
animate_func,
frames = nSeconds * fps,
interval = 1000 / fps, # in ms
)
anim.save('test_anim.mp4', fps=fps, extra_args=['-vcodec', 'libx264'])
print('Done!')
# plt.show() # Not required, it seems!