【问题标题】:Need help on animating a 2-D trajectory using FuncAnimation在使用 FuncAnimation 制作 2-D 轨迹动画时需要帮助
【发布时间】:2022-01-23 19:29:01
【问题描述】:

我有一个形状为(50,3) 的数组x_trj,我想使用该数组的第一列和第二列(分别为x 和y 坐标)绘制二维轨迹。这个轨迹将在一个圆圈的顶部。到目前为止,这是我的代码:

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

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

# Plot circle
theta = np.linspace(0, 2*np.pi, 100)
plt.plot(r*np.cos(theta), r*np.sin(theta), linewidth=5)
ax = plt.gca()

def animate(n):
    # Plot resulting trajecotry of car
    for n in range(x_trj.shape[0]):
      line.set_xdata(x_trj[n,0])
      line.set_ydata(x_trj[n,1])
      
    return line,



anim = FuncAnimation(fig, animate,frames=200, interval=20)

但是,动画结果是一个静止的人物。我在文档页面上查看了 Matplotlib 动画示例,但我仍然无法弄清楚我的 animate(n) 函数在这种情况下应该是什么样子。有人可以给我一些提示吗?

【问题讨论】:

  • 我刚试过,但动画结果是一个静止的人物

标签: python matplotlib


【解决方案1】:

下面的代码做了如下改动:

  • 添加了一些测试数据
  • animate:
    • 删除for 循环
    • 只复制轨迹的一部分,直到给定n
  • 在对FuncAnimation的调用中:
    • `帧数应该等于给定的点数(200帧和50点效果不好)
    • interval= 设置为更大的数字,因为 20 毫秒对于仅 50 帧来说太快了
  • 添加了plt.show()(根据代码运行的环境,plt.show()会触发动画开始)
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np

# create some random test data
x_trj = np.random.randn(50, 3).cumsum(axis=0)
x_trj -= x_trj.min(axis=0, keepdims=True)
x_trj /= x_trj.max(axis=0, keepdims=True)
x_trj = x_trj * 8 - 4

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

# Plot circle
theta = np.linspace(0, 2 * np.pi, 100)
r = 4
ax.plot(r * np.cos(theta), r * np.sin(theta), linewidth=5)

def animate(n):
    line.set_xdata(x_trj[:n, 0])
    line.set_ydata(x_trj[:n, 1])
    return line,

anim = FuncAnimation(fig, animate, frames=x_trj.shape[0], interval=200)
# anim.save('test_trajectory_animation.gif')
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 2015-12-05
    • 2022-11-11
    • 1970-01-01
    相关资源
    最近更新 更多