Matplotlib画动态图:animation模块的使⽤
matplotlib 画图功能⾮常强⼤,⽬前也只能根据 提供的例⼦简单地画⼏张图。最近学习了能画动态图的animation模块,作个简单地记录。
在matplotlib作图中,⽐较常⽤的是matplotlib.pyplot模块,这个模块有⾮常多的属性和⽅法,简要列举下这次⽤到的⽅法: matplotlib.pyplot.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None,
gridspec_kw=None, **fig_kw)
返回fig和ax对象!
例⼦1. 动态画出sin函数曲线
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
matplotlib中subplot
fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = ax.plot([], [], 'r-', animated=False)
def init():
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)
return ln,
def update(frame):
xdata.append(frame)
ydata.append(np.sin(frame))
ln.set_data(xdata, ydata)
return ln,
ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
init_func=init, blit=True)
plt.show()
画这类图的关键是要给出不断更新的函数,这⾥就是update 函数了。注意, line, = ax.plot([], [], 'r-', animated=False) 中的, 表⽰创建tuple类型。迭代更新的数据frame 取值从frames 取得。
例⼦2. 动态显⽰⼀个动点,它的轨迹是sin函数。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
"""
animation example 2
author: Kiterun
"""
fig, ax = plt.subplots()
x = np.linspace(0, 2*np.pi, 200)
y = np.sin(x)
l = ax.plot(x, y)
dot, = ax.plot([], [], 'ro')
def init():
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)
return l
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()
这⾥我们把⽣成的动态图保存为gif图⽚,前提要预先安装imagemagic。
例⼦3. 单摆(没阻尼&有阻尼)
⽆阻尼的单摆⼒学公式:
附加阻尼项:
这⾥需要⽤到scipy.integrate的odeint模块,具体⽤法时间再专门写⼀篇blog吧,动态图代码如下:# -*- coding: utf-8 -*-
from math import sin, cos
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import matplotlib.animation as animation
g = 9.8
leng = 1.0
b_const = 0.2
# no decay case:
def pendulum_equations1(w, t, l):
th, v = w
dth = v
dv  = - g/l * sin(th)
return dth, dv
# the decay exist case:
def pendulum_equations2(w, t, l, b):
th, v = w
dth = v
dv = -b/l * v - g/l * sin(th)
return dth, dv
t = np.arange(0, 20, 0.1)
track = odeint(pendulum_equations1, (1.0, 0), t, args=(leng,))
#track = odeint(pendulum_equations2, (1.0, 0), t, args=(leng, b_const))
xdata = [leng*sin(track[i, 0]) for i in range(len(track))]
ydata = [-leng*cos(track[i, 0]) for i in range(len(track))]
fig, ax = plt.subplots()
line, = ax.plot([], [], 'o-', lw=2)
time_template = 'time = %.1fs'
time_text = ax.text(0.05, 0.9, '', ansAxes)
def init():
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
time_text.set_text('')
return line, time_text
def update(i):
newx = [0, xdata[i]]
newy = [0, ydata[i]]
line.set_data(newx, newy)
time_text.set_text(time_template %(0.1*i))
return line, time_text
ani = animation.FuncAnimation(fig, update, range(1, len(xdata)), init_func=init, interval=50)
#ani.save('single_pendulum_decay.gif', writer='imagemagick', fps=100)
ani.save('single_pendulum_nodecay.gif', writer='imagemagick', fps=100)
plt.show()
例⼦4. 滚动的球
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure(figsize=(6, 6))
ax = a()
ln1, = ax.plot([], [], '-', lw=2)
ln2, = ax.plot([], [], '-', color='r', lw=2)
theta = np.linspace(0, 2*np.pi, 100)
r_out = 1
r_in = 0.5
def init():
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
x_out = [r_s(theta[i]) for i in range(len(theta))]
y_out = [r_out*np.sin(theta[i]) for i in range(len(theta))]
ln1.set_data(x_out, y_out)
return ln1,
def update(i):
x_in = [(r_out-r_in)*np.cos(theta[i])+r_s(theta[j]) for j in range(len(theta))]
y_in = [(r_out-r_in)*np.sin(theta[i])+r_in*np.sin(theta[j]) for j in range(len(theta))]
ln2.set_data(x_in, y_in)
return ln2,
ani = animation.FuncAnimation(fig, update, range(len(theta)), init_func=init, interval=30) ani.save('roll.gif', writer='imagemagick', fps=100)
plt.show()

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。