python+matplotlib实现交互式图形显示

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)

#定义自选频率
axcorlor = 'lightgoldenrodyellow'
rax = plt.axes([0.05,0.7,0.15,0.15],facecolor=axcorlor)
radio = RadioButtons(rax,('2HZ','4HZ','8HZ'))
hzdict = {'2HZ':s0,'4HZ':s1,'8HZ':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],facecolor=axcorlor)
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],facecolor=axcorlor)
styles = ('-','--','step',':')
radio3 = RadioButtons(rax,styles)
def stylesfunc(label):
    l.set_linestyle(label)
    plt.draw()
radio3.on_clicked(stylesfunc)

#定义按钮单击处理函数
def randomFig(event):
    hz = choice(tuple(hzdict))
    hzlabel = [label.get_text() for label in radio.labels]
    radio.set_active(hzlabel.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])
button = Button(axRnd,'Random Figure')
button.on_clicked(randomFig)
plt.show()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值