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

Hojo.Timberwolf
  • 985
  • 1
  • 11
  • 32
  • are you sure that it has to be `set_XY = temp` - not `set_XY(temp)` – furas Jan 12 '17 at 09: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. – furas Jan 12 '17 at 09:54

2 Answers2

1

You have to use

 RB[i].set_xy(temp)

instead of set_XY = temp

furas
  • 134,197
  • 12
  • 106
  • 148
  • 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. – Hojo.Timberwolf Jan 12 '17 at 10:20
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
ccerhan
  • 642
  • 6
  • 7