Search code examples
pythonmatplotlibconways-game-of-life

Animating moving square in python


I'm new to python's matplotlib, and i want to animate a 1x1 square that moves diagonally across a grid space. I have written this bit of code that almost does what i want it to do, but the previous positions of the rectangle are still visible.

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

from matplotlib.patches import Rectangle


moving_block = [[0,0],[1,1],[2,2],[3,3],[4,4],[5,5]]

fig, ax = plt.subplots()

#set gridlines and lines every one unit
ax.grid(which='both')
ax.axis([0,5,0,5])


rectangle = Rectangle(moving_block[0], 1,1)
ax.add_patch(rectangle)

def animate(i):
    ax.add_patch(Rectangle(moving_block[i], 1,1))

ani = matplotlib.animation.FuncAnimation(fig, animate, 
                frames=len(moving_block), interval=300, repeat=True) 

plt.show()

How can i make only the current rectangle visible? Should i be using something other than this ax.add_patch(Rectangle) function?


Solution

  • Added cleaning "ax", at each iteration in the function "animate". If you are satisfied with the answer, do not forget to vote for it :-)

    import matplotlib.pyplot as plt
    import matplotlib.animation
    from matplotlib.patches import Rectangle
    
    moving_block = [[0,0],[1,1],[2,2],[3,3],[4,4],[5,5]]
    
    fig, ax = plt.subplots()
    #set gridlines and lines every one unit
    ax.grid(which='both')
    ax.axis([0, 5, 0, 5])
    
    rectangle = Rectangle(moving_block[0], 1,1)
    ax.add_patch(rectangle)
    
    def animate(i):
        ax.clear()
        ax.axis([0, 5, 0, 5])
        ax.grid(which='both')
        ax.add_patch(Rectangle(moving_block[i], 1,1))
    
    
    ani = matplotlib.animation.FuncAnimation(fig, animate,
                    frames=len(moving_block), interval=300, repeat=True)
    
    plt.show()