Dynamically updating plot in matplotlib

前端 未结 4 565
难免孤独
难免孤独 2020-11-22 08:31

I am making an application in Python which collects data from a serial port and plots a graph of the collected data against arrival time. The time of arrival for the data is

4条回答
  •  -上瘾入骨i
    2020-11-22 09:13

    I know I'm late to answer this question, but for your issue you could look into the "joystick" package. I designed it for plotting a stream of data from the serial port, but it works for any stream. It also allows for interactive text logging or image plotting (in addition to graph plotting). No need to do your own loops in a separate thread, the package takes care of it, just give the update frequency you wish. Plus the terminal remains available for monitoring commands while plotting. See http://www.github.com/ceyzeriat/joystick/ or https://pypi.python.org/pypi/joystick (use pip install joystick to install)

    Just replace np.random.random() by your real data point read from the serial port in the code below:

    import joystick as jk
    import numpy as np
    import time
    
    class test(jk.Joystick):
        # initialize the infinite loop decorator
        _infinite_loop = jk.deco_infinite_loop()
    
        def _init(self, *args, **kwargs):
            """
            Function called at initialization, see the doc
            """
            self._t0 = time.time()  # initialize time
            self.xdata = np.array([self._t0])  # time x-axis
            self.ydata = np.array([0.0])  # fake data y-axis
            # create a graph frame
            self.mygraph = self.add_frame(jk.Graph(name="test", size=(500, 500), pos=(50, 50), fmt="go-", xnpts=10000, xnptsmax=10000, xylim=(None, None, 0, 1)))
    
        @_infinite_loop(wait_time=0.2)
        def _generate_data(self):  # function looped every 0.2 second to read or produce data
            """
            Loop starting with the simulation start, getting data and
        pushing it to the graph every 0.2 seconds
            """
            # concatenate data on the time x-axis
            self.xdata = jk.core.add_datapoint(self.xdata, time.time(), xnptsmax=self.mygraph.xnptsmax)
            # concatenate data on the fake data y-axis
            self.ydata = jk.core.add_datapoint(self.ydata, np.random.random(), xnptsmax=self.mygraph.xnptsmax)
            self.mygraph.set_xydata(t, self.ydata)
    
    t = test()
    t.start()
    t.stop()
    

提交回复
热议问题