A.Loc - 24 days ago 17
Python Question

# Animation of a polar circle in python

Here is my python file to simulate oscillatory dynamics for a circle, which expands and shrinks, permanently:

``````import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

def init():
line.set_data([], [])
return line,

def animate(i):
theta = np.linspace(0, 2 * np.pi, 100)
r = np.sqrt(np.abs(np.sin(0.1 * i)))
x = r * np.cos(theta) + 1
y = r * np.sin(theta)
line.set_data(x, y)
return line,

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

plt.show()
``````

But the parametric definition is flawed, such that the result isn't an animated circle, but an ellipsis.

How can I fix the thing?

Try adding `plt.gca().set_aspect('equal', adjustable='box')` and also modifying your `ylim` as follows:

``````import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-1, 1))
line, = ax.plot([], [], lw=2)

def init():
line.set_data([], [])
return line,

def animate(i):
theta = np.linspace(0, 2 * np.pi, 100)
r = np.sqrt(np.abs(np.sin(0.1 * i)))
x = r * np.cos(theta) + 1
y = r * np.sin(theta)
line.set_data(x, y)
return line,

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