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

yipeiwu_com5年前Python基础

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

一 代码

from random import choice
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import RadioButtons,Button
t = 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程序设计有所帮助。

相关文章

python中使用print输出中文的方法

python中使用print输出中文的方法

看Python简明教程,学习使用print打印字符串,试了下打印中文,不行。 编辑环境:IDLE 上网搜了下解决办法,各种说法,试了两种: print u"学习" print (un...

python求众数问题实例

本文实例讲述了python求众数问题的方法,是一个比较典型的应用。分享给大家供大家参考。具体如下: 问题描述: 多重集中重数最大的元素称为众数...就是一个可以有重复元素的集合,在这个集...

简单谈谈Python流程控制语句

人们常说人生就是一个不断做选择题的过程:有的人没得选,只有一条路能走;有的人好一点,可以二选一;有些能力好或者家境好的人,可以有更多的选择;还有一些人在人生的迷茫期会在原地打转,找不到方...

Django中redis的使用方法(包括安装、配置、启动)

Django中redis的使用方法(包括安装、配置、启动)

一、安装redis: 1.下载: wget http://download.redis.io/releases/redis-3.2.8.tar.gz 2.解压 tar -zxv...

Python交互环境下实现输入代码

Python交互环境下实现输入代码

Iamlaosong文 Python交互环境的提示符是“>>>”,命令行模式下输入python命令就可以进入这个交互环境进行交互会话。 在windows中,除了在she...