0

I'm not quite getting how to create a class for animating data. Here is the gist:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

x = np.arange(100).reshape((100, 1))
y = np.random.randn(100, 1)
xy = np.hstack((x, y))


class PlotData:
    def __init__(self):
        fig, ax = plt.subplots()
        fig.set_size_inches((11, 9))
        self.fig = fig
        self.ax = ax
        self.ln0, = ax.plot([], [])

    def init(self):
        self.ln0.set_data([], [])
        return(self.ln0, )

    def update(self, frame_no):
        data = xy[0:frame_no + 1]
        self.ln0.set_data(data[:, 0], data[:, 1])
        return(self.ln0, )


if __name__ == '__main__':
    my_plot = PlotData()
    anim = animation.FuncAnimation(my_plot.fig, my_plot.update,
                                   init_func=my_plot.init, blit=True,
                                   frames=99, interval=50)
    plt.show()

This only produces the init method output but not the update, so ends up a blank plot with no animation. What is going on?

sluque
  • 495
  • 4
  • 12

1 Answers1

2

For me your code works perfectly fine. The only problem is that most of the data are outside of the plotting limits. If you adjust your plot limits like this:

class PlotData:
    def __init__(self):
        fig, ax = plt.subplots(figsize = (11,9))
        self.fig = fig
        self.ax = ax
        self.ax.set_xlim([0,100])
        self.ax.set_ylim([-3,3])
        self.ln0, = ax.plot([], [])

The line is animated just fine. If you want that the x- and y-limits are adjusted automatically, see this question on how to do it. However, if I recall correctly, this will only work properly with blit=False.

Thomas Kühn
  • 9,412
  • 3
  • 47
  • 63