python的matplotlib的4種方法制作動態sin函數代碼詳解

1.說明:

1.1 推薦指數:★★★

1.2 python的基礎知識複習,通過生動的sin函數製作來複習return和yield,列表、函數定義等知識。

1.3 熟悉matplotlib作圖相關知識。

1.4 加深理解sin函數,為以後圓的理解打下堅實基礎,cos重複不解釋了,將sin適當修改即可。


python的matplotlib的4種方法制作動態sin函數代碼詳解

2.return法,基本方法,代碼:

<code>#---導出模塊---
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

#定義畫布,默認值,這個fig需要,雖然默認大小設置,fig需要掛在動畫上
fig = plt.figure()

#座標軸刻度
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))

#color='blue'=藍色,否則默認為清淡藍色
line, = ax.plot([], [], lw=2,color='blue')

# 因為動畫,所以初始化列表線條
def init():
line.set_data([], [])
return line, #注意逗號

#定義動畫
def animate(i):
#x取值範圍從0~2,等差數列,分成1000,越大線條越平滑
x = np.linspace(0, 2, 1000)
#動畫x和y的值與i的從0~i的取值有關,才動起來
y = np.sin(2 * np.pi * (x - 0.01 * i))

line.set_data(x, y)
return line, #注意逗號

#將fig掛在動畫上面
anim = animation.FuncAnimation(fig, animate, init_func=init,frames=200, interval=20, blit=True)
#如果需要保存動畫,就這樣

#anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
#標題名稱
plt.title('Sin-a-subplot')
plt.show()/<code>

圖1


python的matplotlib的4種方法制作動態sin函數代碼詳解

3.np.nan法,代碼:

<code>#---導出模塊---
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

#---定義畫布---重點講到區別和含義---
fig, ax = plt.subplots()

#---函數定義法---講的很清楚了,很多遍---
#複習一下
#x的座標取值範圍,arange法一般是-2π到2π,這裡是從0取,0.01,數值越小曲線越平滑
#注意與linspace取等差數列的區別
x = np.arange(0, 2*np.pi, 0.01)
#這是一步並2步了,相當於y=np.sin(x)
line, = ax.plot(x, np.sin(x))

#---初始化---注意np.nan(NaN)知識複習---
def init():
line.set_ydata([np.nan] * len(x))
#等同於下面
#line.set_ydata([] * len(x))
return line,
'''
有兩種丟失數據:
None
np.nan(NaN)
None是Python自帶的,其類型為python object。因此,None不能參與到任何計算中。
np.nan(NaN)
np.nan是浮點類型,能參與到計算中。但計算的結果總是NaN。
但可以使用np.nan*()函數來計算nan,此時視nan為0。

'''

#---定義動畫---
def animate(i):
#line.set_ydata(np.sin(x + i / 100))
#與上面一樣效果
line.set_ydata(np.sin(x + 0.01 * i))
return line,

#fig的掛在動畫上面
ani = animation.FuncAnimation(fig, animate, init_func=init, interval=2, blit=True, save_count=50)

# ani.save("movie.mp4")

plt.show()
/<code>

圖2


python的matplotlib的4種方法制作動態sin函數代碼詳解

4.帶紅色小圓點的yield法,代碼:

<code>#---導出模塊---
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation

#---定義畫布和ax軸---
fig, ax = plt.subplots()
'''
等價於:fig, ax = plt.subplots(11)=fig, ax = plt.subplots(1,1)
=fig, ax1 = plt.subplot()
或者:
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
'''

#---x和y的函數關係---
x = np.linspace(0, 2*np.pi, 200)
y = np.sin(x)
#畫正弦函數線
l = ax.plot(x, y)
#運動的圓球,ro=就是red的o=紅色的圓球,如果是o,就是默認顏色的圓球
#掛在正弦函數線上的球,初始化座標為空
dot, = ax.plot([], [], 'ro')

#---初始化定義紅色圓球的ax座標取值範圍---
def init():
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)
return l

#---產生圓球的座標取值範圍,符合正弦函數---
def gen_dot():
#i類似x座標,np.sin(i)類似y座標

for i in np.linspace(0, 2*np.pi, 200):
newdot = [i, np.sin(i)]
#通過yield函數產生
yield newdot

'''
首先比較下return 與 yield的區別:
return:在程序函數中返回某個值,返回之後函數不在繼續執行,徹底結束。
yield: 帶有yield的函數是一個迭代器,函數返回某個值時,會停留在某個位置,返回函數值後,會在前面停留的位置繼續執行,直到程序結束
帶有 yield 的函數不再是一個普通函數,而是一個生成器generator,可用於迭代。
'''
#---更新小圓球的位置---
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()/<code>

圖3


python的matplotlib的4種方法制作動態sin函數代碼詳解

5 timer法:最新matplotlib好像淘汰了,可以運行,但是報錯,可以不用管它,學習技術而已。代碼如下:

<code>#---導出模塊---
import matplotlib.pyplot as plt
import numpy as np

#---fig和ax放在一起
fig, ax = plt.subplots()

#---初始化定義---
points_dot = 100
#複習一下列表知識,一個列表裡有100個相同的0的列表
sin_list = [0] * points_dot
indx = 0

#---畫正弦函數線---初始化---
line_sin, = ax.plot(range(points_dot), sin_list, label='sin-d', color='blue')

#---定義sin輸出函數---
def sin_output(ax):
global indx, sin_list, line_sin
if indx == 20:
indx = 0
indx += 1
#更新sin列表,初始化全是100個0,更新後就是正弦函數的y座標
sin_list = sin_list[1:] + [np.sin((indx / 10) * np.pi)]
#看看ydata就是y座標的意思
line_sin.set_ydata(sin_list)
#從新畫正弦函數動態曲線
ax.draw_artist(line_sin)
ax.figure.canvas.draw()

#計時器在新版的matplotlib中已經刪除,目前能顯示,但是報錯,可以不管,暫時學學技術,瞭解一下

timer = fig.canvas.new_timer(interval=100)
timer.add_callback(sin_output, ax)
timer.start()

#x和y軸的刻度定義
ax.set_xlim([0, points_dot])
ax.set_ylim([-2, 2])
#ax.set_autoscale_on(False) #默認False
#0~100,每隔10取刻度值
ax.set_xticks(range(0, points_dot, 10))
ax.set_yticks(range(-2, 3, 1))
#顯示網格
ax.grid(True)
#顯示圖例,固定位置=中心上面
ax.legend(loc='upper center', ncol=4)

plt.show()

'''
報錯:
RuntimeError: wrapped C/C++ object of type QTimer has been deleted
提示新版的matplotlib已經刪除timer了
'''/<code>

圖4


python的matplotlib的4種方法制作動態sin函數代碼詳解

希望喜歡,收藏之後好好複習,生動的圖像,加深對python的基礎知識的理解,熟悉matplotlib作圖,以後拿來就用,通俗易懂。


分享到:


相關文章: