Python使用Slider組件實現(xiàn)調整曲線參數(shù)功能示例
本文實例講述了Python使用Slider組件實現(xiàn)調整曲線參數(shù)功能。分享給大家供大家參考,具體如下:
一 代碼
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider,Button,RadioButtons
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.1, bottom=0.25)
t = np.arange(0.0,1.0,0.001)
#初始振幅與頻率,并繪制初始圖形
a0, f0=5,3
s = a0*np.sin(2*np.pi*f0*t)
l,= plt.plot(t, s, lw=2, color='red')
#設置坐標軸刻度范圍
plt.axis([0,1,-10,10])
axColor ='lightgoldenrodyellow'
#創(chuàng)建兩個Slider組件,分別設置位置/尺寸、背景色和初始值
axfreq = plt.axes([0.1,0.1,0.75,0.03], axisbg=axColor)
sfreq =Slider(axfreq,'Freq',0.1,30.0, valinit=f0)
axamp = plt.axes([0.1,0.15,0.75,0.03], axisbg=axColor)
samp =Slider(axamp,'Amp',0.1,10.0, valinit=a0)
#為Slider組件設置事件處理函數(shù)
def update(event):
#獲取Slider組件的當前值,并以此來更新圖形
amp = samp.val
freq = sfreq.val
l.set_ydata(amp*np.sin(2*np.pi*freq*t))
plt.draw()
#fig.canvas.draw_idle()
sfreq.on_changed(update)
samp.on_changed(update)
def adjustSliderValue(event):
ampValue = samp.val +0.05
if ampValue >10:
ampValue =0.1
samp.set_val(ampValue)
freqValue = sfreq.val +0.05
if freqValue >30:
freqValue =0.1
sfreq.set_val(freqValue)
update(event)
axAdjust = plt.axes([0.6,0.025,0.1,0.04])
buttonAdjust =Button(axAdjust,'Adjust', color=axColor, hovercolor='red')
buttonAdjust.on_clicked(adjustSliderValue)
#創(chuàng)建按鈕組件,用來恢復初始值
resetax = plt.axes([0.8,0.025,0.1,0.04])
button =Button(resetax,'Reset', color=axColor, hovercolor='yellow')
def reset(event):
sfreq.reset()
samp.reset()
button.on_clicked(reset)
###用來控制圖形顏色的
##rax = plt.axes([0.025, 0.5, 0.15, 0.15], axisbg=axColor)
##radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)
##def colorfunc(label):
## l.set_color(label)
## fig.canvas.draw_idle()
##radio.on_clicked(colorfunc)
plt.show()
二 運行結果

更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數(shù)學運算技巧總結》、《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
Python3字符串的常用操作方法之修改方法與大小寫字母轉化
這篇文章主要介紹了Python3字符串的常用操作方法之修改方法與大小寫字母轉化,文章圍繞主題展開詳細的內容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-09-09
Python編程入門之Hello World的三種實現(xiàn)方式
這篇文章主要介紹了Python編程入門之Hello World的三種實現(xiàn)方式,實例分析了print輸出函數(shù)的使用及控制臺輸出的相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-11-11
Pandas中datetime數(shù)據(jù)類型的使用
本文主要介紹了Pandas中datetime數(shù)據(jù)類型的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-12-12
Python求兩點之間的直線距離(2種實現(xiàn)方法)
今天小編就為大家分享一篇Python求兩點之間的直線距離(2種實現(xiàn)方法),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07

