「繪圖,讓科學生動起來」:Python-matplotlib繪圖(示波器及動態函數模擬專題)
作者簡介:85後一名分析化學工作者及科學愛好者,深愛著北京的老北京人,愛好運動,科學,旅行,本文作者的個人微信公眾號《科學是什麼東東》,歡迎關注!
在這一專題中,我們將更貼近實際應用:函數的動態圖形化,我們可以將其應用在示波器中,在軟體上就可以模擬示波器的電壓隨時間變化的波形圖(效果如下):
y=sinx的示波器模擬
我們需要著手設計程序,可實現的功能為:
允許用戶輸入x,y軸的正負半軸的長度值,x,y,z軸和主標題的標籤名稱(英文)。
同時我們需要構建需要圖形化的函數,為了使其變為動畫,我們將使用matplotlib中的animation功能(動畫)
最終效果:生成動態視圖,顯示x,y軸名稱及主標題。
在圖形顯示窗口,我們可以通過滑鼠操作改變視角,縮放圖形,也可保存視圖。
主程序代碼如下:
主要步驟解析為#後面的部分
#分別導入numpy函數模塊,matplotlib庫模塊,animation動畫模塊以及time模塊
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
#以下為輸入部分,主要輸入部分為x,y正負半軸長度
主函數y=n1*sin(n2*(x-n3*i)^n4)中各個係數的值
print("Welcome to use animation graphic fitting generator, the formula model is y=n1*sin(n2*(x-n3*i)^n4).
")
print("n1,n2 are coefficient. n3 is X-axis transformation coefficient,the range is 0 ~ 1, the larger of the coefficient, the faster of animation will be.")
print("n4 is the power number.
")
a1=input("please enter x negative axis length value(absolute value):
")
a1=float(a1)
a2=input("please enter x postive axis length value:
")
a2=float(a2)
print("The x axis actual display range is from - "+str(a1)+" to "+str(a2)+":
")
a3=input("please enter y negative axis length value(absolute value):
")
a3=float(a3)
a4=input("please enter y postive axis length value:
")
a4=float(a4)
print("The y axis actual display range is from - "+str(a3)+" to "+str(a4)+":
")
a5=input("please enter n1 value:
")
a5=float(a5)
a6=input("please enter n2 value:
")
a6=float(a6)
a7=input("please enter n3 value:
")
a7=float(a7)
a8=input("please enter n4 value:
")
a8=float(a8)
print("The n1,n2,n3,n4 values are "+str(a5)+" , "+str(a6)+" , "+str(a7)+" , "+str(a8)+".
")
#構建圖形,x,y軸的坐標範圍以剛輸入的值為準
其中lw是圖形的線寬,color代表顏色
fig = plt.figure()
ax = plt.axes(xlim=(-a1, a2), ylim=(-a3, a4))
line, = ax.plot([], [], lw=4,color=red)
#這裡定義2個函數,分別獲取數據,以及定義x,y的顯示,在輸入y時,我們將需要擬合的函數加入,其中:
a5,a6分別為係數,a7為x軸的位移,是按照x-a7*i計算的,因此a7設定越大,函數在x軸的位移越快,一般建議設定1以下
a8為次方數
注意冒號後一定要首行縮進
def init():
line.set_data([], [])
return line,
def animate(i):
x = np.linspace(-a1, a2, 1000)
y= a5*(np.sin(a6* ((x - a7 * i)**a8)))
line.set_data(x, y)
return line,
#這裡大家應該比較熟悉了,允許輸入x,y軸標題及主標題,以及定義字型大小大小
x1=input("please enter x label name:
")
x2=input("please enter y label name:
")
x3=input("please enter title label name:
")
ax.set_xlabel(x1,fontsize=20)
ax.set_ylabel(x2,fontsize=20)
ax.set_title(x3,fontsize=25)
#最後一步,生成動畫視圖,定義幀數,間隔等
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True)
plt.show()
同理,對於函數主體,我們也可以加入重複繪圖的命令:
在導入各種庫的命令之後,加入(這裡不需要首行縮進)
while True:
結尾處加入(注意全部需要首行縮進,break在if語句後進行首行縮進)
keep_testing=input("continuepainting?")
if keep_testing==n:
break
中間的全部命令也要首行縮進
這樣就可以在圖形關閉後,系統會自動提示是否再次畫圖,按n後結束程序
動態函數,不光可以應用在示波器模擬中,也可以在數學或教學領域中得到很好的拓展和應用:我們來比較幾種函數的動態圖形: