Skip to content Skip to sidebar Skip to footer

Python Update Matplotlib From Threads

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 Currently I'm tryi

Solution 1:

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

classMyDataClass():

    def__init__(self):

        self.XData = [0]
        self.YData = [0]


classMyPlotClass():

    def__init__(self, dataClass):

        self._dataClass = dataClass

        self.hLine, = plt.plot(0, 0)

        self.ani = FuncAnimation(plt.gcf(), self.run, interval = 1000, repeat=True)


    defrun(self, i):  
        print("plotting data")
        self.hLine.set_data(self._dataClass.XData, self._dataClass.YData)
        self.hLine.axes.relim()
        self.hLine.axes.autoscale_view()


classMyDataFetchClass(threading.Thread):

    def__init__(self, dataClass):

        threading.Thread.__init__(self)

        self._dataClass = dataClass
        self._period = 0.25
        self._nextCall = time.time()


    defrun(self):

        whileTrue:
            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()

Post a Comment for "Python Update Matplotlib From Threads"