Animate multiple shapes in python3 using matplotli

2019-07-21 14:19发布

问题:

Trying to animate multiple objects at once in python3 while using matplotlib animation function.

code written below is where I am thus far. I am able to create the multiple objects and display them in the figure. I did this by using a for loop containing a patches function for a rectangle. From here I was hoping to move all the individual rectangles over by a set amount by using the animation function.

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

fig = plt.figure()
ax = fig.add_subplot(111)

plt.xlim(-100, 100)
plt.ylim(-100, 100)

width = 5
bars = 25

RB = [] # Establish RB as a Python list
for a in range(bars):
    RB.append(patches.Rectangle((a*15-140,-100), width, 200, 
          color="blue", alpha=0.50))

def init():
    for a in range(bars):
        ax.add_patch(RB[a])
    return RB

def animate(i):
    for a in range(bars):
        temp = np.array(RB[i].get_xy())   
        temp[0] = temp[0] + 3;
        RB[i].set_XY = temp
    return RB

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

plt.show()

Currently, nothing moves or happens once I run the code. I have tried to follow the examples found on the python website; but it usually results in a 'AttributeError: 'list' object has no attribute 'set_animated''.

回答1:

You have to use

 RB[i].set_xy(temp)

instead of set_XY = temp



回答2:

The indexes in RB is wrong actually. You should change the animate function as:

def animate(i):
    for a in range(bars):
        temp = RB[a].get_x() + 3
        RB[a].set_x(temp)
    return RB