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实现的多线程端口扫描工具分享

Python实现的多线程端口扫描工具分享

昨晚今晚写了两晚,总算把Py Port Scanner 写完了,姑且称之为0.1版本,算是一个Python多线程端口扫描工具。 水平有限,实话中间有一些困惑和不解的地方,代码可能也写的比...

机器学习经典算法-logistic回归代码详解

机器学习经典算法-logistic回归代码详解

一、算法简要 我们希望有这么一种函数:接受输入然后预测出类别,这样用于分类。这里,用到了数学中的sigmoid函数,sigmoid函数的具体表达式和函数图象如下: 可以较为清楚的看到,...

深入探究Django中的Session与Cookie

前言 Cookie和Session相信对大家来说并不陌生,简单来说,Cookie和Session都是为了记录用户相关信息的方式,最大的区别就是Cookie在客户端记录而Session在服...

TensorFLow 不同大小图片的TFrecords存取实例

全部存入一个TFrecords文件,然后读取并显示第一张。 不多写了,直接贴代码。 from PIL import Image import numpy as np import m...

在Python中画图(基于Jupyter notebook的魔法函数)

这篇文章主要介绍了在Python中画图(基于Jupyter notebook的魔法函数),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...