Python update Matplotlib from threads

后端 未结 1 1728
清酒与你
清酒与你 2020-12-17 05:31

I\'m pretty new to the python world and unfortunately I could not find any solution to this yet.

I\'m running python 3.6 with matplotlib==1.3.1 on Mac OS X 10.13.2

相关标签:
1条回答
  • 2020-12-17 06:05

    I don't think you can run matplotlib GUI outside the main thread. So keeping the plotting in the main thread and using a FuncAnimation to steer the plotting, the following seems to work fine.

    Due to the while True loop it will run forever, even after closing the window, so for any real world application this should still be adjusted.

    import matplotlib.pyplot as plt
    from matplotlib.animation import FuncAnimation
    import numpy as np
    import threading
    import random
    import time
    
    class MyDataClass():
    
        def __init__(self):
    
            self.XData = [0]
            self.YData = [0]
    
    
    class MyPlotClass():
    
        def __init__(self, dataClass):
    
            self._dataClass = dataClass
    
            self.hLine, = plt.plot(0, 0)
    
            self.ani = FuncAnimation(plt.gcf(), self.run, interval = 1000, repeat=True)
    
    
        def run(self, i):  
            print("plotting data")
            self.hLine.set_data(self._dataClass.XData, self._dataClass.YData)
            self.hLine.axes.relim()
            self.hLine.axes.autoscale_view()
    
    
    class MyDataFetchClass(threading.Thread):
    
        def __init__(self, dataClass):
    
            threading.Thread.__init__(self)
    
            self._dataClass = dataClass
            self._period = 0.25
            self._nextCall = time.time()
    
    
        def run(self):
    
            while True:
                print("updating data")
                # add data to data class
                self._dataClass.XData.append(self._dataClass.XData[-1] + 1)
                self._dataClass.YData.append(random.randint(0, 256))
                # sleep until next execution
                self._nextCall = self._nextCall + self._period;
                time.sleep(self._nextCall - time.time())
    
    
    data = MyDataClass()
    plotter = MyPlotClass(data)
    fetcher = MyDataFetchClass(data)
    
    fetcher.start()
    plt.show()
    #fetcher.join()
    
    0 讨论(0)
提交回复
热议问题