2

I've been researching for a bit and haven't found the solution I'm looking for.

Is there a method to creating a dynamic x-axis with matplotlib? I have a graph with a data stream being plotted, and I would like to have the x-axis display elapsed time (currently is static 0-100, while the rest of the graph updating to my data stream).

Each tick would ideally be .5 seconds apart, with the latest 10s displaying. The program will be running 24/7, so I could have it set to actual time instead of stopwatch time. I've only been finding static datetime axis in my research.

I can provide code if necessary, but doesn't seem necessary for this question.

  • 1
    E.g., [updating from hardware](http://stackoverflow.com/questions/21532457/matplotlib-understanding-and-changing-axis-labels-for-a-scatter-plot-updated-in)? I expect you can reset the x-axis label on each redraw to state the elapsed time (or reset the x-limits to be `(max(x)-100, max(x))`). – cphlewis Apr 16 '15 at 02:55
  • possible duplicate of [Updating the xaxis values using matplotlib animation](http://stackoverflow.com/questions/17895698/updating-the-xaxis-values-using-matplotlib-animation) – ali_m Apr 16 '15 at 15:12

1 Answers1

2

Since I don't know what you are streaming, I wrote a generic example and it may help you solving your problem.

from pylab import *
import matplotlib.animation as animation

class Monitor(object):
    """  This is supposed to be the class that will capture the data from
        whatever you are doing.
    """    
    def __init__(self,N):
        self._t    = linspace(0,100,N)
        self._data = self._t*0

    def captureNewDataPoint(self):
        """  The function that should be modified to capture the data
            according to your needs
        """ 
        return 2.0*rand()-1.0


    def updataData(self):
        while True:
            self._data[:]  = roll(self._data,-1)
            self._data[-1] = self.captureNewDataPoint()
            yield self._data

class StreamingDisplay(object):

    def __init__(self):
        self._fig = figure()
        self._ax  = self._fig.add_subplot(111)

    def set_labels(self,xlabel,ylabel):
        self._ax.set_xlabel(xlabel)
        self._ax.set_ylabel(ylabel)

    def set_lims(self,xlim,ylim):
        self._ax.set_xlim(xlim)
        self._ax.set_ylim(ylim)

    def plot(self,monitor):
        self._line, = (self._ax.plot(monitor._t,monitor._data))

    def update(self,data):
        self._line.set_ydata(data)
        return self._line

# Main
if __name__ == '__main__':
    m = Monitor(100)
    sd = StreamingDisplay()
    sd.plot(m)
    sd.set_lims((0,100),(-1,1))

    ani = animation.FuncAnimation(sd._fig, sd.update, m.updataData, interval=500) # interval is in ms
    plt.show()

Hope it helps

mrcl
  • 2,130
  • 14
  • 29