教你用Python matplotlib庫制作簡單的動畫
發(fā)布日期:2022-03-13 12:57 | 文章來源:CSDN
matplotlib制作簡單的動畫
動畫即是在一段時間內快速連續(xù)的重新繪制圖像的過程.
matplotlib提供了方法用于處理簡單動畫的繪制:
import matplotlib.animation as ma def update(number): pass # 每隔30毫秒,執(zhí)行一次update ma.FuncAnimation( mp.gcf(),# 作用域當前窗體 update, # 更新函數(shù)的函數(shù)名 interval=30 # 每隔30毫秒,執(zhí)行一次update )
案例1:
隨機生成各種顏色的100個氣泡, 讓他們不斷增大.
1.隨機生成100個氣泡.
2.每個氣泡擁有四個屬性: position, size, growth, color
3.把每個氣泡繪制到窗口中.
4.開啟動畫,在update函數(shù)中更新每個氣泡的屬性并重新繪制
""" 簡單動畫 1. 隨機生成100個氣泡. 2. 每個氣泡擁有四個屬性: position, size, growth, color 3. 把每個氣泡繪制到窗口中. 4. 開啟動畫,在update函數(shù)中更新每個氣泡的屬性并重新繪制 """ import numpy as np import matplotlib.pyplot as mp import matplotlib.animation as ma n = 100 balls = np.zeros(n, dtype=[ ('position', float, 2), # 位置屬性 ('size', float, 1), # 大小屬性 ('growth', float, 1),# 生長速度 ('color', float, 4)])# 顏色屬性 # 初始化每個泡泡 # uniform: 從0到1取隨機數(shù),填充n行2列的數(shù)組 balls['position']=np.random.uniform(0,1,(n,2)) balls['size']=np.random.uniform(50,70,n) balls['growth']=np.random.uniform(10,20,n) balls['color']=np.random.uniform(0,1,(n,4)) # 繪制100個泡泡 mp.figure('Bubble', facecolor='lightgray') mp.title('Bubble', fontsize=18) mp.xticks([]) mp.yticks([]) sc = mp.scatter(balls['position'][:,0], balls['position'][:,1], balls['size'], color=balls['color']) # 啟動動畫 def update(number): balls['size'] += balls['growth'] # 讓某個泡泡破裂,從頭開始執(zhí)行 boom_i = number % n balls[boom_i]['size'] = 60 balls[boom_i]['position']= \ np.random.uniform(0, 1, (1, 2)) # 重新設置屬性 sc.set_sizes(balls['size']) sc.set_offsets(balls['position']) anim = ma.FuncAnimation( mp.gcf(), update, interval=30) mp.show()
案例2
""" 模擬心電圖 """ import numpy as np import matplotlib.pyplot as mp import matplotlib.animation as ma mp.figure('Signal', facecolor='lightgray') mp.title('Signal', fontsize=16) mp.xlim(0, 10) mp.ylim(-3, 3) mp.grid(linestyle=':') pl = mp.plot([],[], color='dodgerblue', label='Signal')[0] # 啟動動畫 def update(data): t, v = data x, y = pl.get_data() #x y: ndarray數(shù)組 x = np.append(x, t) y = np.append(y, v) # 重新繪制圖像 pl.set_data(x, y) # 移動坐標軸 if x[-1]>5: mp.xlim(x[-1]-5, x[-1]+5) x = 0 def generator(): global x y = np.sin(2 * np.pi * x) * \ np.exp(np.sin(0.2 * np.pi * x)) yield (x, y) x += 0.05 anim = ma.FuncAnimation(mp.gcf(), update, generator, interval=30) mp.show()
到此這篇關于教你用Python matplotlib制作簡單的動畫的文章就介紹到這了,更多相關matplotlib制作動畫內容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持本站!
版權聲明:本站文章來源標注為YINGSOO的內容版權均為本站所有,歡迎引用、轉載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內容涉嫌侵權,請聯(lián)系alex-e#qq.com處理。
相關文章