【问题标题】:How to generate an animated curve using animation?如何使用动画生成动画曲线?
【发布时间】:2021-11-01 22:50:56
【问题描述】:

我想使用某些点生成动画曲线。但是,当我使用下面的代码时,没有显示动画,并且图片的 x 坐标和 y 坐标不断变化。我使用FuncAnimation函数,我传递给这个函数的参数是plot_gesture,这个函数绘制了所有的点。

我的轨迹是一个列表,它的元素都是列表(长度为2),就像[[2.5,2], [4,3.5], [2,6]....] 我的位置是一个ndarray,它的元素都是元组(长度为2),就像((3,5),(6,7)......) 轨迹的长度远大于位置的长度,因为位置是轨迹的采样点的所有点。轨迹是整个轨迹的所有点。所以,我需要把轨迹上的所有点都画出来,把位置的点分散一下

def plot_gesture(i = int):
X = []
Y = []
X_point = []
Y_point = []

for x in trajectory[:i]:
    X.append(x[0])
    Y.append(x[1])
for x in position[:i]:
    X_point.append(x[0])
    Y_point.append(x[1])
 plt.plot(X, Y)
for x, y in zip(X_point, Y_point):
    plt.scatter(x, y)



if __name__ == "__main__":
trajectory = point_list
position = np.array(sampled_all_points)
ani=animation.FuncAnimation(fig= fig,func= plot_gesture, interval= 20)
plt.show();

【问题讨论】:

  • 请提供trajectoryposition的数据
  • 我的轨迹是一个列表,它的元素都是列表(长度为2),就像[[2.5,2], [4,3.5], [2,6]....]我的位置是一个ndarray,它的元素都是元组(长度为2),就像((3,5),(6,7)......)轨迹的长度比位置的长得多,因为position 是轨迹的采样点的所有点。轨迹是整个轨迹的所有点。所以,我需要把轨迹上的所有点都画出来,把位置的点分散开@Zephyr

标签: python matplotlib animation data-visualization visualization


【解决方案1】:

您应该始终将您的数据包含在您的问题中。
由于您尚未指定 positiontrajectory 是什么,我想您需要一个具有 N 行和 2 列的 position 数组,其中包含移动点的 xy 坐标。我生成了一个这样的数组:

N = 200
time = np.linspace(0, 30, N)
position = np.array([1/3*time*np.cos(time), 1/3*time*np.sin(time)]).T
[[ 0.00000000e+00  0.00000000e+00]
 [ 4.96813143e-02  7.54690426e-03]
 [ 9.59688338e-02  2.98452338e-02]
 [ 1.35597167e-01  6.58794885e-02]
 [ 1.65553654e-01  1.13995649e-01]
 [ 1.83194645e-01  1.71957672e-01]
 [ 1.86350032e-01  2.37024178e-01]
 [ 1.73412613e-01  3.06042995e-01]
 [ 1.43409393e-01  3.75560683e-01]
 [ 9.60523732e-02  4.41943697e-01]
 [ 3.17670638e-02  5.01507457e-01]
...

您需要定义一个要传递给FuncAnimation 的图形和一个animation 函数。在此函数中,您需要:

  • 删除上一个情节
  • 绘制当前状态
  • 修复轴以避免在动画过程中不愉快的轴修改

所以你可以这样设置代码:

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


def animate(i):
    # erase previous plot
    ax.cla()

    # draw point's trajectory
    ax.plot(position[:i + 1, 0], position[:i + 1, 1], linestyle = '-', color = 'blue')

    # draw point's current position
    ax.plot(position[i, 0], position[i, 1], marker = 'o', markerfacecolor = 'red', markeredgecolor = 'red')

    # fix axes limits
    ax.set_xlim(-10, 10)
    ax.set_ylim(-10, 10)


if __name__ == "__main__":
    # position array generation
    N = 200
    time = np.linspace(0, 30, N)
    position = np.array([1/3*time*np.cos(time), 1/3*time*np.sin(time)]).T

    # generate figure and axis
    fig, ax = plt.subplots(figsize = (5, 5))

    # define the animation
    ani = FuncAnimation(fig = fig, func = animate, interval = 20, frames = N)

    # show the animation
    plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多