Python动画图

Tas*_*sos 8 python animation graph

我有一个项目来创建几个图形动画.我将有一个有向加权图,在每一步,我将改变一些事情.我想用动画做出这些改变.所以,我的问题是:

是否可以使用python制作动画,如果是这样,你将如何制作一个简单的动画?

jim*_*ist 12

Matplotlib是python的标准图形库,它带有一个相当不错的动画包.Jake Vanderplas在这里有一个很好的教程.

从此链接中获取,如果要为正弦波设置动画,则可以使用以下方法:

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()
Run Code Online (Sandbox Code Playgroud)

动画库每隔一个间隔调用一次"animate"函数(在本例中指定为20).该函数应该适当地更新图.在这种情况下,它使用set_data方法更新"line",这是正弦波数据的数组.