将我的输出轨迹设置为移动线的动画

2024-09-29 02:21:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个新手,但在硕士论文中使用python

我有一个.csv的x和y坐标,按“frame”分组。我想动画它,所以它是一个不断增长的线,因为它移动帧帧,但我不知道如何

数据点是通过无人机视频跟踪单个海豚的鼠标移动。因此,每个x,y代表海豚在视频帧中的位置

这就是我到目前为止所做的:

df = pd.read_csv('/content/drive/My Drive/Thesis_Data/2016-07-17-1542_2A.csv', 
                 usecols=['x', 'y','frame'])
df.head(10)

这就是我的数据。我有几千分

  frame   x     y
0   61  1057    487
1   61  1057    487
2   61  1057    487
3   61  1057    487
4   61  1057    487
5   61  1057    487
6   61  1057    487
7   61  1057    487
8   61  1057    487
9   61  1057    487
gr = df.groupby('frame')
mean_pos = gr.mean()
ax= df.plot("x", "y", color="r")
ax.set_title('mean trajectory')

output trajectory

我想给它设置动画,使它像移动的线一样逐帧移动


Tags: csv数据df视频动画代表鼠标ax
1条回答
网友
1楼 · 发布于 2024-09-29 02:21:24

您可以尝试以下方法:

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

# a sample dataframe  with coordinates of random movement
xy = np.random.normal(0, 1, (100, 2)).cumsum(axis=0)
df = pd.DataFrame(xy, columns=["x", "y"])

# plot setup
fig, ax = plt.subplots(figsize=(4, 4))
ax.set_xlim(df["x"].min() - 2, df["x"].max() + 2)
ax.set_ylim(df["y"].min() - 2, df["y"].max() + 2)
xdata, ydata = [], []
ln, = plt.plot([], [], 'r-')

def update(i):
    """
    updates the plot for each animation frame
    """
    ln.set_data(df.iloc[0:i, 0], df.iloc[0:i, 1])
    return ln,

# animate the plot
ani = FuncAnimation(fig, 
                    update, 
                    frames=len(df), 
                    interval=100, # delay of each frame in miliseconds
                    blit=True)
plt.show()

结果是:

enter image description here

注意:如果您想在Jupyter笔记本中运行此功能,请首先执行%matplotlib notebook魔术

相关问题 更多 >