python - 3D 曲线切线动画

标签 python numpy matplotlib animation

我正在编写一个 Python 程序来为沿 3D 曲线的切线设置动画。但是,我的切线没有移动。我认为问题是
line.set_data(np.array(Tangent[:,0]).T,np.array(Tangent[:,1]).T)
animate(i)但我想不通。任何帮助将不胜感激。以下是代码。

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

matplotlib.use( 'tkagg' )
plt.style.use('seaborn-pastel')

fig = plt.figure()
ax = plt.axes(projection='3d')
ax = plt.axes(projection='3d')

# Data for a three-dimensional line
zline = np.linspace(0, 15, 1000)
xline = np.sin(zline)
yline = np.cos(zline)
ax.plot3D(xline, yline, zline, 'red')

def curve(t):
    return [np.sin(t),np.cos(t),t]

def vector_T(t):
    T = [np.cos(t),-np.sin(t),1]
    return T/np.linalg.norm(T)

len = 2
def tangent_line(t):
    P = np.add(curve(t),len*vector_T(t))
    Q = np.subtract(curve(t),len*vector_T(t))
    return np.array([P, Q]).T

t0 = 0
Tangent=tangent_line(t0)
line, = ax.plot3D(Tangent[0], Tangent[1], Tangent[2], 'green')


def init():
    line.set_data([], [])
    return line,

def animate(i):
    t0 = 15* (i/200)
    Tangent=tangent_line(t0)
    #print(Tangent)
    line.set_data(np.array(Tangent[:,0]).T,np.array(Tangent[:,1]).T)
    return line,

anim = FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

plt.show()

最佳答案

你在 animate 中调用了错误的函数:
替换 line.set_data(...)line.set_data_3d(Tangent[0], Tangent[1], Tangent[2])它会起作用。

代码中仍然存在一些小问题(例如,不要使用 len 作为变量名)。
我建议使用以下内容:

#!/usr/bin/env python3

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

matplotlib.use('tkagg')
plt.style.use('seaborn-pastel')

fig = plt.figure()
ax = plt.axes(projection='3d')

# Data for a three-dimensional line
zline = np.linspace(0, 15, 1000)
xline = np.sin(zline)
yline = np.cos(zline)
ax.plot3D(xline, yline, zline, 'red')

def curve(t):
    return [ np.sin(t), np.cos(t), t ]

def tangent(t):
    t = [ np.cos(t), -np.sin(t), 1.0 ]
    return t/np.linalg.norm(t)

def tangent_line(t):
    length = 2.0
    offset = length * tangent(t)
    pos = curve(t)
    return np.array([ pos-offset, pos+offset ]).T

line = ax.plot3D(*tangent_line(0), 'green')[0]

def animate(i):
    line.set_data_3d(*tangent_line(15* (i/200)))
    return [ line ]

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

plt.show()

关于python - 3D 曲线切线动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60241138/

相关文章:

python - tcl-tk (tkinter) 不通过 Homebrew pyenv 在 MacOS Mojave 上安装

python - pymysql无法连接到mysql

python - 任何好的 pdf417 条码库用于 Python?

python - 将新值添加到过滤后的 pandas DataFrame

python - 列表和元组的行为不同

matplotlib - 控制图例中的行数

python - 在 Python 中从文件夹中读取 HTML 文件

pandas - 将 pandas 数据帧转换为稀疏矩阵

pandas - Seaborn:在热图上注释缺失值

python - 多个字幕