Matplotlib 绘制动图(1)

animation.FuncAnimation(fig,func,frames,init_func,interval)

1. 绘制 sin 曲线

fig:fig, ax = plt.subplots()

func:即 update ,每一帧都被调用,函数的第一个参数就是下一个参数 frames 里的values

frames:iterable,可以是整数,整数的话等同于传递range(frames),或者 frames = np.linspace()

init_func:初始化函数,就是fig的最初设置,如图的界限 set_xlim / set_ylim

interval:Delay between frames in milliseconds. Defaults to 200.

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

fig, ax = plt.subplots()
xdata, ydata = [], []
line, = ax.plot([], [], 'r-', animated=False)

#逗号不能去掉,下同
def init():
    ax.set_xlim(0, 2*np.pi)
    ax.set_ylim(-1, 1)
    return line,

def update(frame):
    xdata.append(frame)
    ydata.append(np.sin(frame))
    line.set_data(xdata, ydata)
    return line,

ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128), 
					interval=30,init_func=init, blit=True)
ani.save('sin.gif', writer='imagemagick', fps=30)
plt.show()

2. 绘制 sin 轨迹动点

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

fig, ax = plt.subplots()
x = np.linspace(0, 2*np.pi, 200)
y = np.sin(x)
line = ax.plot(x, y)
dot, = ax.plot([], [], 'ro')

def init():
    ax.set_xlim(0, 2*np.pi)
    ax.set_ylim(-1, 1)
    return line

def gen_dot():
    for i in np.linspace(0, 2*np.pi, 200):
        newdot = [i, np.sin(i)]
        yield newdot

def update_dot(newd):
    dot.set_data(newd[0], newd[1])
    return dot,

ani = animation.FuncAnimation(fig, update_dot, frames = gen_dot, interval = 100, init_func=init)
ani.save('sin_dot.gif', writer='imagemagick', fps=30)
plt.show()

你可能感兴趣的:(Python)