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使用marshal模块序列化实例

本文实例讲述了python使用marshal模块序列化的方法,分享给大家供大家参考。具体方法如下: 先来看看下面这段代码: import marshal data1 = ['abc'...

python生成器/yield协程/gevent写简单的图片下载器功能示例

本文实例讲述了python生成器/yield协程/gevent写简单的图片下载器功能。分享给大家供大家参考,具体如下: 1、生成器: '''第二种生成器''' # 函数只有有yiel...

python对日志进行处理的实例代码

平时做数据处理基本离不了日志记录功能。每次都配置一堆挺烦人,索性封装个模块,这里记录一下,与大家共享。 说明 本日志模块目前只有一个方法getLogger,其他配置项通过参数传递,包括日...

python实现大战外星人小游戏实例代码

主程序 import pygame from pygame.sprite import Group from settings import Settings from game_...

TensorFlow2.0:张量的合并与分割实例

** 一 tf.concat( ) 函数–合并 ** In [2]: a = tf.ones([4,35,8]) In [3]:...