2个动画子图垂直堆叠.
我想根据鼠标位置显示黑色垂直线.
到目前为止,我只能在移动鼠标时完全搞乱这个数字……
如何清除更新之间的旧垂直线?
(只是出于好奇:自从鼠标移动控制以来,即使不移动鼠标,我的PC风扇也会在执行代码时发疯.鼠标是否“计算成本”?!?)
import numpy as npimport matplotlib.pyplot as pltimport matplotlib.animation as animationfrom time import sleepval1 = np.zeros(100) val2 = np.zeros(100) level1 = 0.2level2 = 0.5fig,ax = plt.subplots()ax1 = plt.subplot2grID((2,1),(0,0))lineVal1,= ax1.plot(np.zeros(100))ax1.set_ylim(-0.5,1.5) ax2 = plt.subplot2grID((2,(1,0))lineVal2,= ax2.plot(np.zeros(100),color = "r")ax2.set_ylim(-0.5,1.5) def onMouseMove(event): ax1.axvline(x=event.xdata,color="k") ax2.axvline(x=event.xdata,color="k")def updateData(): global level1,val1 global level2,val2 clamp = lambda n,minn,maxn: max(min(maxn,n),minn) level1 = clamp(level1 + (np.random.random()-.5)/20.0,0.0,1.0) level2 = clamp(level2 + (np.random.random()-.5)/10.0,1.0) # values are appended to the respective arrays which keep the last 100 readings val1 = np.append(val1,level1)[-100:] val2 = np.append(val2,level2)[-100:] yIEld 1 # FuncAnimation expects an iteratordef visualize(i): lineVal1.set_ydata(val1) lineVal2.set_ydata(val2) return lineVal1,lineVal2fig.canvas.mpl_connect('motion_notify_event',onMouseMove)ani = animation.FuncAnimation(fig,visualize,updateData,interval=50)plt.show()
EDIT1
由Ophir解决:
def onMouseMove(event): ax1.lines = [ax1.lines[0]] ax2.lines = [ax2.lines[0]] ax1.axvline(x=event.xdata,color="k") ax2.axvline(x=event.xdata,color="k")
EDIT2
如果同一图中有更多数据集,例如:
ax1 = plt.subplot2grID((2,= ax1.plot(np.zeros(100))lineVal2,color = "r")ax1.set_ylim(-0.5,1.5)
每个数据集的行都存储在ax1.lines []中:
> ax1.lines [0]是lineVal1
> ax1.lines [1]是lineVal2
> ax1.lines [2]是垂直线,如果你已经绘制它.
这意味着onMouseMove必须更改为:
def onMouseMove(event): ax1.lines = ax1.lines[:2] # keep the first two lines ax1.axvline(x=event.xdata,color="k") # then draw the vertical line解决方法 用以下内容替换你的onMouseMove:
(我用了How to remove lines in a Matplotlib plot)
def onMouseMove(event): ax1.lines = [ax1.lines[0]] ax2.lines = [ax2.lines[0]] ax1.axvline(x=event.xdata,color="k")总结
以上是内存溢出为你收集整理的python – Matplotlib动画:通过子图的垂直光标线全部内容,希望文章能够帮你解决python – Matplotlib动画:通过子图的垂直光标线所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)