matplotlib 范围选区(SpanSelector)的使用
范围选区概述
范围选区是一种常见的对象选择方式,在一个子图中,可以在某一个轴方向上用鼠标选择起始范围的数据,这个特性可用来实现数据缩放(datazoom)。在matplotlib中的范围选区属于部件(widgets),matplotlib中的部件都是中性(neutral)的,即与具体后端实现无关。
范围选区具体实现定义为matplotlib.widgets.SpanSelector类,继承关系为:Widget->AxesWidget->_SelectorWidget->SpanSelector。
SpanSelector类的签名为classmatplotlib.widgets.SpanSelector(ax,onselect,direction,minspan=None,useblit=False,rectprops=None,onmove_callback=None,span_stays=False,button=None)。
SpanSelector类构造函数的参数为:
- ax:范围选区生效的子图,类型为matplotlib.axes.Axes的实例。
- onselect:范围选区完成后执行的回调函数,函数签名为deffunc(min,max),min、max的数据类型均为浮点数,表示选区在某个坐标轴方向上的最小值和最大值。
- direction:范围选区的坐标轴方向,取值范围为{"horizontal","vertical"},类型为字符串。
- minspan:选区的最小范围,选区范围小于minspan将不会触发onselect。rectprops:范围选区的外观的属性,默认值为None。
- span_stays:布尔值,是否在鼠标释放后仍然保留选区,默认值为False。
- onmove_callback:当选区确定后移动鼠标触发的回调函数,函数签名为deffunc(min,max),min、max的数据类型均为浮点数,默认值为None。
SpanSelector类中的state_modifier_keys公有变量state_modifier_keys定义了操作快捷键,类型为字典。
案例:范围选取基本实现
官方案例一,范围选区基本实现。
案例说明
控制台输出:
1.5697580645161292.0044354838709677
案例代码
importmatplotlib.pyplotasplt importmatplotlib.widgetsasmwidgets fig,ax=plt.subplots() ax.plot([1,2,3],[10,50,100]) defonselect(vmin,vmax): print(vmin,vmax) rectprops=dict(facecolor='blue',alpha=0.5) span=mwidgets.SpanSelector(ax,onselect,'horizontal',span_stays=True, rectprops=rectprops) plt.show()
案例:数据缩放功能
官方案例,https://matplotlib.org/gallery/widgets/span_selector.html
案例说明
案例代码
importnumpyasnp importmatplotlib.pyplotasplt frommatplotlib.widgetsimportSpanSelector #Fixingrandomstateforreproducibility np.random.seed(19680801) fig,(ax1,ax2)=plt.subplots(2,figsize=(8,6)) ax1.set(facecolor='#FFFFCC') x=np.arange(0.0,5.0,0.01) y=np.sin(2*np.pi*x)+0.5*np.random.randn(len(x)) ax1.plot(x,y,'-') ax1.set_ylim(-2,2) ax1.set_title('Pressleftmousebuttonanddragtotest') ax2.set(facecolor='#FFFFCC') line2,=ax2.plot(x,y,'-') defonselect(xmin,xmax): indmin,indmax=np.searchsorted(x,(xmin,xmax)) indmax=min(len(x)-1,indmax) thisx=x[indmin:indmax] thisy=y[indmin:indmax] line2.set_data(thisx,thisy) ax2.set_xlim(thisx[0],thisx[-1]) ax2.set_ylim(thisy.min(),thisy.max()) fig.canvas.draw() span=SpanSelector(ax1,onselect,'horizontal',useblit=True,span_stays=True, rectprops=dict(alpha=0.5,facecolor='red')) #Setuseblit=Trueonmostbackendsforenhancedperformance. plt.show()
到此这篇关于matplotlib范围选区(SpanSelector)的使用的文章就介绍到这了,更多相关matplotlib范围选区内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。