How to draw real-time moving circle in Python matplotlib

Viewed 980

I'm trying to make 2D collision simulation in Python.

I made a circle on the figure to use as an object, and I wanted to move it in real-time without the figure window closed.

I found this code:

import matplotlib.pyplot as plt
import numpy as np 

x = np.linspace(0, 10, 100)
y = np.cos(x)

fig = plt.figure()

for p in range(50):
    p=3
    updated_x=x+p
    updated_y=np.cos(x)
    plt.plot(updated_x,updated_y)
    plt.draw()  
    x=updated_x
    y=updated_y
    plt.pause(0.2)
    fig.clear()

and I tried this:

import matplotlib.pyplot as plt
import numpy as np 

fig = plt.figure()
board = plt.axes(xlim = (0, 200), ylim = (0, 100))

x = 10
y = 10
r = 10

for p in range(10):
    circle = plt.Circle((x, y), body.r, fc='w', ec='b')
    board.add_patch(circle)

    plt.annotate("", xytext=(x, y), xy=(x+10, y+10), arrowprops=dict(facecolor='r', edgecolor='r', headwidth=6, headlength=6, width=0.1))

    plt.draw()  
    plt.pause(0.2)
    fig.clear()

    x += 10
    y += 10

I wanted to draw only the present circle and delete the previous one.

But it didn't worked, and I can't understand why fig.clear() in the first code didn't really clear it.

Please help me...

1 Answers

Your problem was with fig.clear(). If you just remove the circle and the annotation from the plot you get an animation.

from matplotlib import pyplot as plt, animation as an
import numpy as np

fig = plt.figure()
board = plt.axes(xlim=(0, 200), ylim=(0, 100))

x = 10
y = 10
r = 10

for p in range(10):
    circle = plt.Circle((x, y), r, fc='w', ec='b')
    board.add_patch(circle)

    annotation = plt.annotate("", xytext=(x, y), xy=(x+10, y+10), arrowprops=dict(facecolor='r', edgecolor='r', headwidth=6, headlength=6, width=0.1))

    plt.draw()
    plt.pause(0.2)
    circle.remove()
    annotation.remove()
    x += 10
    y += 10

plt.show()
Related