박시현
박시현

Reputation: 1

How to animate dot over already calculated graph

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

fig, ax = plt.subplots()
ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)

x, y = [], []
line, = plt.plot([], [], 'bo')
circle = plt.Circle((0,0), 1, color = 'g', fill = False,)

def update(frame):
    x.append(np.cos(frame))
    y.append(np.sin(frame))
    line.set_data(x, y)
    return circle, line,


ani = FuncAnimation(fig, update, frames= np.linspace(0, 2*np.pi, 128), interval = 0.1)
plt.show()

what I want to animate

I tried to animate uniform circular motion through the code above, but what I can see was only dot moving, not the circle under the dot. How can I plot circle while animating dot?

Upvotes: 0

Views: 210

Answers (1)

コリン
コリン

Reputation: 940

You can add the circle to the artist with ax.add_artist(circle).

Also, I rewrite the update function so that it only tracks the current dot.

Reference: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.add_artist.html

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

fig, ax = plt.subplots(figsize=(5, 5))

radius = 2

ax.set_xlim(-radius * 1.05, radius * 1.05)
ax.set_ylim(-radius * 1.05, radius * 1.05)

line, = plt.plot([], [], 'bo')
circle = plt.Circle((0, 0), radius, color='k', fill=False)
red_dot = plt.plot(0, 0, 'ro')

ax.set_aspect('equal')
ax.add_artist(circle)
ax.set_axis_off()


def update(i):
    theta = np.deg2rad(i)
    x = [0, radius * np.cos(theta)]
    y = [0, radius * np.sin(theta)]
    line.set_data(x, y)


ani = FuncAnimation(fig, update, frames=360, interval=30)
ani.save('fig_1.gif', writer='pillow', fps=45)

plt.show()

enter image description here

Upvotes: 1

Related Questions