生活随笔
收集整理的這篇文章主要介紹了
matplotlib之简单动画制作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
簡單動畫
動畫即是在一段時間內快速連續的重新繪制圖像的過程.
matplotlib提供了方法用于處理簡單動畫的繪制:
import matplotlib
. animation
as ma
def update ( number
) : pass
ma
. FuncAnimation
( mp
. gcf
( ) , update
, interval
= 30
)
案例: 隨機生成各種顏色的100個氣泡, 讓他們不斷增大.
隨機生成100個氣泡. 每個氣泡擁有四個屬性: position, size, growth, color 把每個氣泡繪制到窗口中. 開啟動畫,在update函數中更新每個氣泡的屬性并重新繪制
"""
簡單動畫
1. 隨機生成100個氣泡.
2. 每個氣泡擁有四個屬性: position, size, growth, color
3. 把每個氣泡繪制到窗口中.
4. 開啟動畫,在update函數中更新每個氣泡的屬性并重新繪制
"""
import numpy
as np
import matplotlib
. pyplot
as mp
import matplotlib
. animation
as man
= 100
balls
= np
. zeros
( n
, dtype
= [ ( 'position' , float , 2 ) , ( 'size' , float , 1 ) , ( 'growth' , float , 1 ) , ( 'color' , float , 4 ) ] )
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 ) )
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' ] boom_i
= number
% nballs
[ 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
( )
"""
模擬心電圖
"""
import numpy
as np
import matplotlib
. pyplot
as mp
import matplotlib
. animation
as mamp
. 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
= datax
, y
= pl
. get_data
( ) 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 xy
= 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
( )
總結
以上是生活随笔 為你收集整理的matplotlib之简单动画制作 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。