2016-08-22 142 views
2

[解决方法已被添加到编辑部分在这篇文章]Matplotlib动画:通过副区

2动画副区被垂直堆叠垂直光标线。

我想根据鼠标位置显示一条黑色垂直线。

到现在为止,我只能完全混乱移动鼠标时的身影......

如何清除更新之间的旧垂直线?

(只是出于好奇:?!?因为鼠标移动控制,无需移动鼠标,甚至执行代码时,我的PC风扇将进入疯狂的是鼠标使“计算昂贵”)

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 
from time import sleep 

val1 = np.zeros(100)   
val2 = np.zeros(100)  

level1 = 0.2 
level2 = 0.5 

fig, 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),(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, 0.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 iterator 

def visualize(i): 

    lineVal1.set_ydata(val1) 
    lineVal2.set_ydata(val2) 

    return lineVal1,lineVal2 

fig.canvas.mpl_connect('motion_notify_event', onMouseMove) 
ani = animation.FuncAnimation(fig, visualize, updateData, interval=50) 
plt.show() 

EDIT1

由于解决了俄斐:

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,1),(0,0)) 
lineVal1, = ax1.plot(np.zeros(100)) 
lineVal2, = ax2.plot(np.zeros(100), 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 

回答

1

取代你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") 
    ax2.axvline(x=event.xdata, color="k") 
+0

谢谢阿斐。没有你的帮助,我永远无法找到它。 现在它完全是逻辑。 –

+0

不客气。 –