2013-09-13 7 views
10

मैं एक थ्रेड में एक सॉकेट से डेटा पढ़ रहा हूं और साजिश को प्लॉट करना और अपडेट करना चाहता हूं क्योंकि नया डेटा आता है। मैं एक छोटे से प्रोटोटाइप अप कोडित बातें अनुकरण करने के लिए, लेकिन यह काम नहीं करता है:क्या आप matplotlib में लाइव डेटा प्लॉट कर सकते हैं?

import pylab 
import time 
import threading 
import random 

data = [] 

# This just simulates reading from a socket. 
def data_listener(): 
    while True: 
     time.sleep(1) 
     data.append(random.random()) 

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

    pylab.figure() 

    while True: 
     time.sleep(1) 
     pylab.plot(data) 
     pylab.show() # This blocks :(
+0

http://stackoverflow.com/questions/14665636/time-sleep-required-to-keep-qthread-responsive – tacaswell

+0

http://stackoverflow.com/questions/8955869/why-is-plotting-with-matplotlib -सो-धीमी/8956211 # 8956211 – tacaswell

+0

http://stackoverflow.com/questions/11874767/real-time-plotting-in-while-loop-with-matplotlib/15724978#15724978 – tacaswell

उत्तर

9
import matplotlib.pyplot as plt 
import time 
import threading 
import random 

data = [] 

# This just simulates reading from a socket. 
def data_listener(): 
    while True: 
     time.sleep(1) 
     data.append(random.random()) 

if __name__ == '__main__': 
    thread = threading.Thread(target=data_listener) 
    thread.daemon = True 
    thread.start() 
    # 
    # initialize figure 
    plt.figure() 
    ln, = plt.plot([]) 
    plt.ion() 
    plt.show() 
    while True: 
     plt.pause(1) 
     ln.set_xdata(range(len(data))) 
     ln.set_ydata(data) 
     plt.draw() 

तुम सच में तेजी से जाने के लिए चाहते हैं, आप blitting ध्यान देना चाहिए।

+0

पर है, तो मैं स्ट्रीमिंग ग्राफ़ प्रदर्शित करने का एक तरीका भी ढूंढ रहा हूं। मैंने कोड के इस टुकड़े को आजमाया और "AttributeError: 'मॉड्यूल' ऑब्जेक्ट में कोई विशेषता 'आकृति' नहीं है। फिर मैंने पिलैब के बजाय "plpl के रूप में matplotlib.pylab आयात करने" की कोशिश की और "RuntimeError: xdata और ydata एक ही लंबाई होना चाहिए"। मेरे पर्यावरण में कुछ गड़बड़ है? मैं पायथन 2.7 –

+0

@GregDan संपादन देख रहा हूँ। – tacaswell

+0

धन्यवाद। यह बेहतर है ... ln.set_xdata (रेंज (लेन) (डेटा)) पर रेंज (लेन) (0) " –

-1

f.show() ब्लॉक नहीं करता है, और आप draw उपयोग कर सकते हैं आंकड़ा अद्यतन करने के लिए।

f = pylab.figure() 
f.show() 
while True: 
    time.sleep(1) 
    pylab.plot(data) 
    pylab.draw() 
+2

'शो' केवल गैर-अवरुद्ध है यदि इंटरैक्टिव मोड – tacaswell

संबंधित मुद्दे