溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

怎么在Matplotlib中利用animation模塊實(shí)現(xiàn)一個(gè)動(dòng)態(tài)圖

發(fā)布時(shí)間:2021-02-25 16:33:19 來(lái)源:億速云 閱讀:185 作者:Leah 欄目:開(kāi)發(fā)技術(shù)

本篇文章為大家展示了怎么在Matplotlib中利用animation模塊實(shí)現(xiàn)一個(gè)動(dòng)態(tài)圖,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。

matplotlib 畫(huà)圖功能非常強(qiáng)大,目前也只能根據(jù)官網(wǎng) 提供的例子簡(jiǎn)單地畫(huà)幾張圖。最近學(xué)習(xí)了能畫(huà)動(dòng)態(tài)圖的animation模塊,作個(gè)簡(jiǎn)單地記錄。

在matplotlib作圖中,比較常用的是matplotlib.pyplot模塊,這個(gè)模塊有非常多的屬性和方法,簡(jiǎn)要列舉下這次用到的方法:
matplotlib.pyplot.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)
返回fig和ax對(duì)象!

例子1. 動(dòng)態(tài)畫(huà)出sin函數(shù)曲線(xiàn)

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

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()

怎么在Matplotlib中利用animation模塊實(shí)現(xiàn)一個(gè)動(dòng)態(tài)圖

畫(huà)這類(lèi)圖的關(guān)鍵是要給出不斷更新的函數(shù),這里就是update 函數(shù)了。注意, line, = ax.plot([], [], 'r-', animated=False) 中的, 表示創(chuàng)建tuple類(lèi)型。迭代更新的數(shù)據(jù)frame 取值從frames 取得。

例子2. 動(dòng)態(tài)顯示一個(gè)動(dòng)點(diǎn),它的軌跡是sin函數(shù)。

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()

這里我們把生成的動(dòng)態(tài)圖保存為gif圖片,前提要預(yù)先安裝imagemagic。

怎么在Matplotlib中利用animation模塊實(shí)現(xiàn)一個(gè)動(dòng)態(tài)圖

例子3. 單擺(沒(méi)阻尼&有阻尼)

無(wú)阻尼的單擺力學(xué)公式:

怎么在Matplotlib中利用animation模塊實(shí)現(xiàn)一個(gè)動(dòng)態(tài)圖

附加阻尼項(xiàng):

怎么在Matplotlib中利用animation模塊實(shí)現(xiàn)一個(gè)動(dòng)態(tài)圖

這里需要用到scipy.integrate的odeint模塊,具體用法找時(shí)間再專(zhuān)門(mén)寫(xiě)一篇blog吧,動(dòng)態(tài)圖代碼如下:

# -*- 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()
ax.grid()
line, = ax.plot([], [], 'o-', lw=2)
time_template = 'time = %.1fs'
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)

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()

怎么在Matplotlib中利用animation模塊實(shí)現(xiàn)一個(gè)動(dòng)態(tài)圖 

怎么在Matplotlib中利用animation模塊實(shí)現(xiàn)一個(gè)動(dòng)態(tài)圖

例子4. 滾動(dòng)的球

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

fig = plt.figure(figsize=(6, 6))
ax = plt.gca()
ax.grid()
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_out*np.cos(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_in*np.cos(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()

怎么在Matplotlib中利用animation模塊實(shí)現(xiàn)一個(gè)動(dòng)態(tài)圖

上述內(nèi)容就是怎么在Matplotlib中利用animation模塊實(shí)現(xiàn)一個(gè)動(dòng)態(tài)圖,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI