2

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''.

2
  • are you sure that it has to be set_XY = temp - not set_XY(temp) Commented Jan 12, 2017 at 9:50
  • put link to examples. And always put in question full error message (Traceback) - not only last part. There are other usefull information. ie. which line makes problem. Commented Jan 12, 2017 at 9:54

2 Answers 2

1

You have to use

 RB[i].set_xy(temp)

instead of set_XY = temp

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

1 Comment

That worked, thanks. It is animating now. Though it looks like it isn't all moving at once. but I might be with the frames, interval I have set.
0

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

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.