【问题标题】:How do I update 3D quiver FuncAnimation from a data in csv file?如何从 csv 文件中的数据更新 3D quiver FuncAnimation?
【发布时间】:2021-01-10 06:13:27
【问题描述】:

我需要有关如何从 csv 更新 3D 箭筒头值的帮助 目前,我有一个 csv 文件,其中包含 3 列 x、y、z 轴,我想在我的 python 代码中更新为 u、v、w 变量。

我面临的问题是结果动画没有正确设置动画。下图是静态图片。

https://i.stack.imgur.com/Os8FX.png

我确定我一定搞砸了如何迭代/读取 csv 数据文件。

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

fig, ax = plt.subplots(subplot_kw=dict(projection="3d"))

# Reading the data from a CSV file using pandas
repo = pd.read_csv('test.csv',sep=',',header=0)
data = np.array((repo['x'].values, repo['y'].values, repo['z'].values))

def get_arrow():
    x = 0
    y = 0
    z = 0
    u = data[0][:]
    v = data[1][:]
    w = data[2][:]
    return x,y,z,u,v,w

quiver = ax.quiver(0,0,0,0,0,0)

ax.set_xlim(-.5, .5)
ax.set_ylim(-.5, .5)
ax.set_zlim(-.5, .5)

def update(theta):
    global quiver
    quiver.remove()
    quiver = ax.quiver(*get_arrow())


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

【问题讨论】:

    标签: python pandas matplotlib-animation


    【解决方案1】:

    我不确定箭头会如何表现,因为数据未知,但我尝试使用示例数据创建它们。我还包含一个用于 GIF 图像和 jupytert 的库,因此您可以对其进行修改以适应您的环境。

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D
    from matplotlib.animation import FuncAnimation
    import random
    from IPython.display import HTML
    from matplotlib.animation import PillowWriter
    
    random.seed(20210110)
    
    repo = (pd.DataFrame({'x':np.random.randint(0,5, size=50),
                         'y':np.random.randint(0,5, size=50),
                         'z':np.random.randint(0,5, size=50)}))
    data = np.array((repo['x'].values, repo['y'].values, repo['z'].values))
    
    fig, ax = plt.subplots(subplot_kw=dict(projection="3d"))
    
    quiver = ax.quiver([],[],[],[],[],[])
    
    ax.set_xlim(-5, 5)
    ax.set_ylim(-5, 5)
    ax.set_zlim(-5, 5)
    
    def update(i):
        global quiver
        quiver.remove()
        quiver = ax.quiver(0,0,0,data[0][i],data[1][i],data[2][i])
    
    ani = FuncAnimation(fig, update, frames=50, interval=50)
    # plt.show()
    ani.save('./quiver_test_ani.gif', writer='pillow')
    plt.close()
    # jupyter lab
    # HTML(ani.to_html5_video())
    

    【讨论】:

    • 动画是否按预期工作?修复是函数化的get_arrow 现在包含在动画函数中。我更改了frames=50 以匹配默认设置和数据数量。请接受这个答案。
    • 是的,动画现在按预期工作。很抱歉没有早点接受答案。我还是新手。
    猜你喜欢
    • 2017-03-30
    • 2023-03-18
    • 2021-07-08
    • 2023-03-29
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多