当前位置:网站首页>使用matplotlib实现GUI交互效果

使用matplotlib实现GUI交互效果

2022-06-22 04:48:00 爱打羽毛球的小怪兽

以下图像中主要包含以下内容:

横纵交叉坐标定位直线、选择框按钮、复选框按钮、绘制子图

 

 以下为上图的实现代码

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import RadioButtons,Cursor,CheckButtons#导入需要的包

x=np.linspace(0.0,2.0,1000)从0到2之间平均取1000个点
y1=1.5*np.cos(2*np.pi*x)
y2=1.0*np.cos(2*np.pi*x)
y3=0.5*np.cos(2*np.pi*x)#定义函数

fig=plt.subplots(subplot_kw={'aspect':'equal'})

line1,=ax.plot(x,y1,color='red',lw=2,visible=False,label='1.5cos(2Πx)')
line2,=ax.plot(x,y2,color='green',lw=2,label='1.0cos(2Πx)')
line3,=ax.plot(x,y3,color='orange',lw=2,label='0.5cos(2Πx)')#绘制函数

lineprops=dict(color='black',lw=1)
cursor=Cursor(ax_2,useblit=True,**lineprops,ls=':')#横纵交叉定位直线的实现



axesbgcolor='cornflowerblue'

cax=plt.axes([0.05,0.7,0.18,0.15],facecolor=axesbgcolor)#设置子图的背景颜色
lines=[line1,line2,line3]
labels=[str(line.get_label()) for line in lines]
visibility=[line.get_visible() for line in lines]#获取每一个函数图像是否显示

check=CheckButtons(cax,labels,visibility)#创建复选按钮框
cax.xaxis.set_ticks([])#消除子图的刻度线
def func(label):
    index=labels.index(label)
    lines[index].set_visible(not lines[index].get_visible())
    plt.draw()

check.on_clicked(func)#线条的显示与否按钮的设置

ax2=plt.axes([0.05,0.4,0.15,0.15],facecolor=axesbgcolor)
radio2=RadioButtons(ax2,('red','green','orange'))#创建选择按钮框
ax2.xaxis.set_ticks([])#消除子图的刻度线
def colorfunc(label):
    for line in lines:
    	line.set_color(label) 
    plt.draw()
radio2.on_clicked(colorfunc)#调用实例方法,点击标签的时候就调用指定的colorfunc函数


ax3=plt.axes([0.05,0.1,0.15,0.15],facecolor=axesbgcolor)
radio3=RadioButtons(ax3,('-','--','-.',':'))
ax3.xaxis.set_ticks([])
def linestylefunc(label):
    for line in lines:
    	line.set_linestyle(label) 
    plt.draw()
    
radio3.on_clicked(linestylefunc)
plt.tighr_layout()
plt.show()
原网站

版权声明
本文为[爱打羽毛球的小怪兽]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_57099024/article/details/122288893