Search code examples
pythonmatplotlibreal-timesensors

Changing the time scale of a matplotlib graph in a real-time fashion


I'm making a real-time application that graphs sensor data in a real-time fashion.

The data is saved to a .csv file and graphed using matplotlib in the following fashion:

class Scope:
    def __init__(self, ax, ax2, f, maxt=2000, dt=0.02): 
      self.ax = ax
      self.ax2 = ax2
      self.maxt = maxt
      self.f = f
      self.tdata = []
      self.ydata = []
      self.humdata = []
      self.tempdata = []
      self.TVOCdata = []
      self.ax.set_ylim(0, 1023)
      self.ax.set_xlim(0, self.maxt)
      self.ax2.set_ylim(0, 100)
      self.ax2.set_xlim(0, self.maxt) 

      self.line, = ax.plot(self.tdata, self.ydata)
      self.line2, = ax2.plot(self.tdata, self.humdata)
      self.line3, = ax2.plot(self.tdata, self.tempdata, 'g-')
      self.line4, = ax.plot(self.tdata, self.TVOCdata)

    def animate(self, y):
      if path.exists(self.f):
        data = pd.read_csv(self.f)
        self.tdata.append(data['dur'].iloc[-1])
        self.ydata.append(data['CO2'].iloc[-1])
        self.line.set_data(self.tdata, self.ydata)                                                                                                                                                      
        self.line.set_label('CO2')

I'd like to change the representation of the time axis from seconds to hours since the measurements that i'm doing might last for days at a time. Is there a handy way of doing this? Truly thankful for any kind of help.


Solution

  • Found a solution to this problem. The key is to use the ticker FuncFormatter-subclass to customize the ticks in the x-axis in the following way:

    formatter = matplotlib.ticker.FuncFormatter(lambda s, x: time.strftime('%H:%M',time.gmtime(s // 60)))
       
    self.ax.xaxis.set_major_formatter(mticker.FuncFormatter(formatter))