目录
一:介绍
二:创建线动画
一:介绍
matplotlib.animation 是 Matplotlib 库中的一个模块,用于创建动画。它提供了多种工具和函数,使您能够轻松地创建各种类型的动画。
二:创建线动画
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = ax.plot([], [], 'r-', animated=True)
def init():
ax.set_xlim(0, 2 * np.pi)
ax.set_ylim(-1, 1)
return ln,
def update(frame):
xdata.append(frame)
ydata.append(np.sin(frame))
ln.set_data(xdata, ydata)
return ln,
ani = animation.FuncAnimation(fig, update, frames=np.linspace(0, 2 * np.pi, 128),
init_func=init, blit=True)
plt.show()
三:绘制散点图
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
plt.close("all")
N_times = 10
N_tracks = 3
x = np.arange(N_times)
y = np.ones((N_tracks, N_times))*np.arange(N_tracks)[:, None]
data = {"Track": sorted(["Track 1", "Track 2", "Track 3"]*N_times),
"Timeline": x.tolist()*3,
"Positions": y.ravel()}
df = pd.DataFrame(data)
colors = {"Track 1": "tab:blue",
"Track 2": "tab:orange",
"Track 3": "tab:green"}
fig, ax = plt.subplots()
ax.set_yticks(np.arange(N_tracks), labels=df["Track"].unique())
ax.set_xticks(df["Timeline"].unique())
ax.set_xlim(df["Timeline"].min()-0.5, df["Timeline"].max()+0.5)
scatters = []
for track, group in df.groupby("Track"):
scatters.append(ax.scatter(group["Timeline"].iloc[0],
group["Positions"].iloc[0],
s=45, c=colors[track]))
def animate(i):
for scatter, (_, group) in zip(scatters, df.groupby("Track")):
scatter.set_offsets((group["Timeline"].iloc[i],
group["Positions"].iloc[i]))
anim = FuncAnimation(fig, animate, frames=N_times, interval=200)
anim.save("test.gif", writer="pillow")