首页 > 编程 > Python > 正文

Python使用matplotlib实现交换式图形显示功能示例

2019-11-25 11:45:44
字体:
来源:转载
供稿:网友

本文实例讲述了Python使用matplotlib实现交换式图形显示功能。分享给大家供大家参考,具体如下:

一 代码

from random import choiceimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import RadioButtons,Buttont = np.arange(0.0,2.0,0.01)s0 = np.sin(2*np.pi*t)s1 = np.sin(4*np.pi*t)s2 = np.sin(8*np.pi*t)fig, ax = plt.subplots()l,= ax.plot(t, s0, lw=2, color='red')plt.subplots_adjust(left=0.3)#定义允许的几种频率,并创建单选钮组件#其中[0.05, 0.7, 0.15, 0.15]表示组件在窗口上的归一化位置axcolor ='lightgoldenrodyellow'rax = plt.axes([0.05,0.7,0.15,0.15], axisbg=axcolor)radio =RadioButtons(rax,('2 Hz','4 Hz','8 Hz'))hzdict ={'2 Hz': s0,'4 Hz': s1,'8 Hz': s2}def hzfunc(label):ydata = hzdict[label]l.set_ydata(ydata)plt.draw()radio.on_clicked(hzfunc)#定义允许的几种颜色,并创建单选钮组件rax = plt.axes([0.05,0.4,0.15,0.15], axisbg=axcolor)colors =('red','blue','green')radio2 =RadioButtons(rax, colors)def colorfunc(label):l.set_color(label)plt.draw()radio2.on_clicked(colorfunc)#定义允许的几种线型,并创建单选钮组件rax = plt.axes([0.05,0.1,0.15,0.15], axisbg=axcolor)styles =('-','--','-.','steps',':')radio3 =RadioButtons(rax, styles)def stylefunc(label):l.set_linestyle(label)plt.draw()radio3.on_clicked(stylefunc)#定义按钮单击事件处理函数,并在窗口上创建按钮def randomFig(event):#随机选择一个频率,同时设置单选钮的选中项hz = choice(tuple(hzdict.keys()))hzLabels =[label.get_text()for label in radio.labels]radio.set_active(hzLabels.index(hz))l.set_ydata(hzdict[hz])#随机选择一个颜色,同时设置单选钮的选中项c = choice(colors)radio2.set_active(colors.index(c))l.set_color(c)#随机选择一个线型,同时设置单选钮的选中项style = choice(styles)radio3.set_active(styles.index(style))l.set_linestyle(style)#根据设置的属性绘制图形plt.draw()axRnd = plt.axes([0.5,0.015,0.2,0.045])buttonRnd =Button(axRnd,'Random Figure')buttonRnd.on_clicked(randomFig)#显示图形plt.show()

二 运行结果

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表