matplotlib之簡單動畫實現


import matplotlib.pyplot as mp
import matplotlib.animation as ma
import numpy as np

'''
1.隨機生成100個氣泡,放入ndarray數組中
2.每個氣泡包含4個屬性:color,position,size,growth
3.繪制這些氣泡
4.編寫動畫,讓氣泡不斷變大。
'''

n = 100
balls = np.zeros(n, dtype=[
    ('position', 'float32', 2),
    ('size', 'float32', 1),
    ('growth', 'float32', 1),
    ('color', 'float32', 4)
])
# 隨機生成100個泡泡,初始化
balls['position'] = np.random.uniform(0, 1, (n, 2))  # uniform平均分布,可以得到n行2列二維數組數組
balls['size'] = np.random.uniform(40, 70, n)  # uniform平均分布,可以得到n行2列二維數組數組
balls['growth'] = np.random.uniform(10, 20, n)  # uniform平均分布,可以得到n行2列二維數組數組
balls['color'] = np.random.uniform(0, 1, (n, 4))  # uniform平均分布,可以得到n行2列二維數組數組

mp.figure('Animation', facecolor='lightgray')
mp.title('Animation', fontsize=18)
sc = mp.scatter(balls['position'][:, 0], balls['position'][:, 1], balls['size'], color=balls['color'])


# 每隔30ms,更新每個泡泡的大小

def update(number):
    balls['size'] += balls['growth']
    # 每次都選中一個泡泡重新隨機屬性
    index = number % n
    balls[index]['size'] = np.random.uniform(40, 70, 1)
    balls[index]['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=1)

mp.show()

   


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM