2016-08-22 147 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

不客氣。 –