Python使用Slider组件实现调整曲线参数功能示例

yipeiwu_com6年前Python基础

本文实例讲述了Python使用Slider组件实现调整曲线参数功能。分享给大家供大家参考,具体如下:

一 代码

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'
#创建两个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组件设置事件处理函数
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)
#创建按钮组件,用来恢复初始值
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数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python和JavaScript间代码转换的4个工具

Python和JavaScript间代码转换的4个工具

选 Python 还是 JavaScript?虽然不少朋友还在争论二者目前谁更强势、谁又拥有着更为光明的发展前景,但毫无疑问,二者的竞争在 Web 前端领域已经拥有明确的答案。立足于浏览...

Python三种遍历文件目录的方法实例代码

本文实例代码主要实现的是python遍历文件目录的操作,有三种方法,具体代码如下。 #coding:utf-8 # 方法1:递归遍历目录 import os def v...

使用Python实现BT种子和磁力链接的相互转换

bt种子文件转换为磁力链接 BT种子文件相对磁力链来说存储不方便,而且在网站上存放BT文件容易引起版权纠纷,而磁力链相对来说则风险小一些。而且很多论坛或者网站限制了文件上传的类型,分享一...

python获取中文字符串长度的方法

如下所示: print len('哈哈'.decode('utf-8')) #unicode格式 print len('哈哈') #utf-8格式 以上这篇python获取中文字符...

django的分页器Paginator 从django中导入类

django的分页器Paginator 从django中导入类

先创建表,然后生成批量数据。 在models文件里 from django.db import models # Create your models here. class...