Search code examples
pythonmatplotlibmatplotlib-animation

Matplotlib how to move axis along data in a real-time animation


I'm trying to plot data that is generated in runtime. In order to do so I'm using matplotlib.animation.FuncAnimation.

While the data is displayed correctly, the axis values are not updating accordingly to the values that are being displayed:

graph animation

The x axis displays values from 0 to 10 eventhough I update them in every iteration in the update_line function (see code below).

DataSource contains the data vector and appends values at runtime, and also returns the indexes of the values being returned:

import numpy as np

class DataSource:
    data = []
    display = 10

    # Append one random number and return last 10 values
    def getData(self):
        self.data.append(np.random.rand(1)[0])
        if(len(self.data) <= self.display):
            return self.data
        else:
            return self.data[-self.display:]

    # Return the index of the last 10 values
    def getIndexVector(self):
        if(len(self.data) <= self.display):
            return list(range(len(self.data)))

        else:
            return list(range(len(self.data)))[-self.display:]

I've obtained the plot_animation function from the matplotlib docs.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from datasource import DataSource


def update_line(num, source, line):
    data = source.getData()
    indexs = source.getIndexVector()
    if indexs[0] != 0:
        plt.xlim(indexs[0], indexs[-1])
        dim=np.arange(indexs[0],indexs[-1],1)
        plt.xticks(dim)
    line.set_data(indexs,data)
    return line,

def plot_animation():
    fig1 = plt.figure()
    source = DataSource()

    l, = plt.plot([], [], 'r-')

    plt.xlim(0, 10)
    plt.ylim(0, 1)
    plt.xlabel('x')
    plt.title('test')
    line_ani = animation.FuncAnimation(fig1, update_line, fargs=(source, l),
                                    interval=150, blit=True)

    # To save the animation, use the command: line_ani.save('lines.mp4')


    plt.show()

if __name__ == "__main__":
    plot_animation()

How can I update the x axis values in every iteration of the animation?

(I appreciate suggestions to improve the code if you see any mistakes, eventhough they might not be related to the question).


Solution

  • Solution

    My problem was in the following line:

    line_ani = animation.FuncAnimation(fig1, update_line, fargs=(source, l),
                                        interval=150, blit=True)
    

    What I had to do is change the blit parameter to False and the x axis started to move as desired.