Matplotlib Animate with dynamic interval

I’ve been searching an answer for this for hours now and cannot find what I’m looking for. I’m trying to animate data from a .csv file using matplotlib. The first column is time, starting at 0. The problem is, that the interval between time steps changes.

enter image description here

I’m trying to animate columns 2,3,4 and 5 vs time (column 1). Since the .csv is very large, I’m using a generator function to yield the rows. The relevant code is:

  def update(self, args):
    level = args[5]

    self.t = args[0]
    self.tdata.append(self.t)

    self.level_title.set_position((self.tdata[0], 3.5))
    self.time_title.set_position((self.tdata[0], 700000))
    if self.count % 10 == 0:
        self.level_title.set_text("  Level: {:.2f}ml".format(level))
        self.time_title.set_text("  Time: {:.2f}s".format(self.t))
    self.count += 1
    self.ax.set_xlim(self.tdata[0], self.tdata[-1])
    self.ydata.append(args[4] - CALIBRATED_EMPTY_LEVEL)
    self.ydata1.append(args[3] - CALIBRATED_EMPTY_LIQUID)
    self.ydata2.append(args[2] - CALIBRATED_EMPTY_ENVIRONMENT)
    self.y2data.append(level)
    self.line.set_data(self.tdata, self.ydata)
    self.line1.set_data(self.tdata, self.ydata1)
    self.line2.set_data(self.tdata, self.ydata2)
    self.line2ax.set_data(self.tdata, self.y2data)

    return self.line, self.line1, self.line2, self.line2ax, self.level_title, self.time_title


def getData():
    with open("data.csv", "r") as f:
        reader = csv.reader(f)
        for row in reader:
            yield np.array(row, dtype=np.float)


def main():
    fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
    ax1.plot(Animated=True)
    ax2.plot(Animated=True)
    scope = Scope(ax1, ax2)

ani = animation.FuncAnimation(fig, scope.update, getData, interval=10,
                              blit=True, repeat=False, save_count=110271)

#plt.show()
mywriter = animation.FFMpegWriter(fps=100)
ani.save('dataplot.mp4', writer=mywriter)

This works fine, for generating an animation and saving it as an mp4. Yet, since the interval is set to 10, the timing isn’t right. The values were logged from a sensor. I have a video of the sensor to be able to reproduce what happened. But for this the time axis has to be the same.

Any help with this would be greatly appreciated!

Regards Lisa

Answer

As Paul Brodersen proposed in the comments, I ended up interpolating my data with a fixed time step.

Leave a Reply

Your email address will not be published. Required fields are marked *