Python 基于Matplotlib制作動態(tài)圖

背景

一圖勝千言,優(yōu)秀的可視化圖表不僅能以直觀、簡潔的方式呈現(xiàn)復(fù)雜的信息,還能夠通過圖形、顏色和布局的巧妙設(shè)計,引發(fā)觀眾的情感共鳴,增強(qiáng)數(shù)據(jù)背后故事的表達(dá)力與說服力。它們超越了單純的數(shù)據(jù)展示,更能幫助觀眾深入理解潛在的趨勢、關(guān)系和模式,從而更有效地支持決策和行動

小編環(huán)境

import sys
print('python 版本:',sys.version)
#python 版本: 3.11.11 | packaged by Anaconda, Inc. | 
#(main, Dec 11 2024, 16:34:19) [MSC v.1929 64 bit (AMD64)]

import matplotlib
print(matplotlib.__version__)
#3.10.0

import numpy
print(numpy.__version__)
#2.2.2

效果展示

plasma配色
viridis配色

完整代碼

#導(dǎo)入庫
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

#生成數(shù)據(jù)
num_points = 100
x,y = np.random.rand(2,num_points)*10

#生成顏色和大小數(shù)據(jù)
colors = np.random.rand(num_points)
sizes =np.random.rand(num_points)*1000

#創(chuàng)建圖形和散點圖
fig, ax = plt.subplots()
scat =ax.scatter(x,y,c=colors,s=sizes, alpha=0.7, cmap='plasma') #viridis
ax.set_xlim(0,10)
ax.set_ylim(0,10)

#創(chuàng)建動畫更新函數(shù)
def animate(i):
    new_x=x+np.random.randn(num_points)*0.1
    new_y=y+np.random.randn(num_points)*0.1
    scat.set_offsets(np.c_[new_x,new_y])  #更新散點圖中所有點的坐標(biāo)
    return scat,

ani = animation.FuncAnimation(fig,animate,frames=100,interval=150)
ani.save('plasma.gif', writer='pillow', fps=10) #viridis

這里重點是創(chuàng)建動畫更新函數(shù) animate,用于更新每一幀散點圖中的點的位置,傳入的參數(shù) i 代表幀編號參數(shù),是 FuncAnimation 每次調(diào)用更新函數(shù)時傳入的參數(shù),表示當(dāng)前動畫幀的索引

歷史相關(guān)文章


以上是自己實踐中遇到的一些問題,分享出來供大家參考學(xué)習(xí),歡迎關(guān)注微信公眾號:DataShare ,不定期分享干貨

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容