Skip to content Skip to sidebar Skip to footer

Defining Multiple Plot Objects In An Array And Updating In Matplotlib Animation

I followed the answer to the following question Defining multiple plots to be animated with a for loop in matplotlib The answer defines and plots the lines, but I want to plot and

Solution 1:

The set_data() function needs a list of at least 2 elements as it draws a line.

For Example:

def animate(i):
    points[0].set_data([[0, 1],[i, i+1]])
    points[1].set_data([[1, 2],[i+1, i+2]])
    points[2].set_data([[2, 3],[i+2, i+3]])
    points[3].set_data([[3, 4],[i+3, i+4]])
    return points

It is only necessary to make the points visible, for that we place a marker:

points = ax.plot( *([[], []]*N), marker="o")

Complete Code:

fig = plt.figure()

ax = plt.axes(xlim=(-10, 10), ylim=(0, 100))

N = 4
points = ax.plot( *([[], []]*N), marker="o")

def init():    
    for line in points:
        line.set_data([], [])
    return points

def animate(i):
    points[0].set_data([0],[i])
    points[1].set_data([[1],[i+1]])
    points[2].set_data([[2],[i+2]])
    points[3].set_data([[3],[i+3]])
    return points

anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=100, interval=20, blit=True)

plt.show()

enter image description here

Post a Comment for "Defining Multiple Plot Objects In An Array And Updating In Matplotlib Animation"