2017-10-16 105 views
0

我認爲這是一個有趣的問題。我想從服務器讀取數據,以便我可以使用matplotlib實時繪製數據。目前我的測試,將通過使用random模擬讀入的值,我發現,我得到這個錯誤:python xdata和ydata的長度必須相同

File "/usr/lib/python2.7/dist-packages/matplotlib/lines.py", line 632, in recache 
    raise RuntimeError('xdata and ydata must be the same length') 
RuntimeError: xdata and ydata must be the same length 

什麼我不明白是怎麼xdataydata大小如果我使用互斥鎖來保護數據不被同時讀取和更新,可能會出現不匹配。你可以看看的認真簡單下面的代碼:

import matplotlib.pyplot as plt 
import time 
from threading import Thread, Lock 
import random 

data = [] 
mutex = Lock() 

# This just simulates reading from a socket. 
def data_listener(): 
    while True: 
     with mutex: 
      data.append(random.random()) 

if __name__ == '__main__': 
    t = Thread(target=data_listener) 
    t.daemon = True 
    t.start() 

    # initialize figure 
    plt.figure() 
    ln, = plt.plot([]) 
    plt.ion() 
    plt.show() 
    plt.axis([0, 100, 0, 1]) 
    while True: 
     plt.pause(0.1) 
     with mutex: 
      ln.set_xdata(range(len(data))) 
      ln.set_ydata(data) 
     plt.draw() 

正如你所看到的,我保證是附加到數據或將數據添加到更新的情節時,你必須獲得互斥體,其意味着len(xdata)==len(ydata)。任何有關我做出假設的想法都會有所幫助。

您可以自己複製並運行代碼。

回答

1

第一條評論:如果您使用plt.pause(),則不需要plt.draw(),因爲後者稱之爲前者。

現在,如果我修改如下所示的腳本,「錯誤」從不打印,所以它似乎運行良好。

import matplotlib.pyplot as plt 
from threading import Thread, Lock 
import random 

data = [] 
mutex = Lock() 

# This just simulates reading from a socket. 
def data_listener(): 
    while True: 
     with mutex: 
      data.append(random.random()) 

if __name__ == '__main__': 
    t = Thread(target=data_listener) 
    t.daemon = True 
    t.start() 

    # initialize figure 
    plt.figure() 
    ln, = plt.plot([]) 
    plt.ion() 
    plt.show() 
    plt.axis([0, 100, 0, 1]) 
    while True: 
     with mutex: 
      try: 
       ln.set_xdata(range(len(data))) 
       ln.set_ydata(data) 
       plt.gca().set_xlim(len(data)-60,len(data)) 
       plt.pause(0.1) 
      except: 
       print ("error") 
+0

我該如何更新繪圖的x軸和y軸以全面瞭解所有數據?我嘗試過'plt.gca().set_xlim(data [:, 0] .min() - 0.5,data [:,0] .max()+ 0.5)'但是這導致我運行錯誤 – Max

+0

由於x軸顯示連續的整數,我猜你需要'plt.gca().set_xlim(0,len(data))''。 – ImportanceOfBeingErnest

+0

我試過這個,奇怪的是你得到一個完全填滿藍色的屏幕,標記爲 – Max

相關問題