1

I have multiple datasets that I want to plot at the same time in a matplotlib animation. Is this possible? Each dataset is an array of (x,y) co-ordinates, so I want to be to animation to cycle through (x,y) co-ordinates, and continuously update until the end of the array. It's straight forward for a single dataset, but I'm having trouble doing it more than one. Any help would be much appreciated.

Here is my problem;

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

def update_line(num, data, line):
    line.set_data(data[...,:num])
    return line,

fig1 = plt.figure()

data1 = np.random.rand(2, 25)
data2 = np.random.rand(2, 25)
l, = plt.plot([], [], 'r-')
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xlabel('x')
plt.title('test')
line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l),interval=50, blit=False)

plt.show()

This works fine for plotting just the first dataset, however I don't know how to plot both data1 and data2 together (and in the future I would like to have 10 datasets on the same animation). I just don't really understand update_line function in doing, if somebody could give me a answer to this it would clear up a lot of things in my mind.

0

1 Answer 1

2

the animation function is only called once per frame, so you have to make sure you're updating both of your plots in that one single call.

For example:

def update_lines(num, data1, data2, line1, line2):
    line1.set_data(data1[...,:num])
    line2.set_data(data2[...,:num])
    return line1,line2

data1 = np.random.rand(2, 25)
data2 = np.random.rand(2, 25)

fig1 = plt.figure()
ax1 = fig1.add_subplot(121)
ax2 = fig1.add_subplot(122)
l1, = ax1.plot([], [], 'r-')
l2, = ax2.plot([], [], 'g-')
for ax in (ax1, ax2):
    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)
    ax.set_xlabel('x')
    ax.set_title('test')
line_ani = animation.FuncAnimation(fig1, update_lines, 25, fargs=(data1, data2, l1, l2),interval=50, blit=False)

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.