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()