在3D绘图动画中更新线

时间:2020-06-02 15:28:01

标签: python python-3.x matplotlib animation plot

我正在尝试在3D动画中绘制一条线。我无法删除在update_line中创建的图。问题是我总是添加新行。我看到的最好的解决方案是在函数外部创建线并更新这些线的数据,但是我似乎无法找到在3D模式下进行绘图的方法

首次发布,仅几个小时的python。对帆布一无所知。请保持简单

import matplotlib; matplotlib.use("TkAgg")
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation
dotinline = 101
nframe = 7
fig = plt.figure(figsize=(16, 8))
ax = p3.Axes3D(fig)
ax.view_init(0, 90)


def init():
    ax.plot([-10, 10], [0, 0], [0, 0], "k")
    ax.plot([0, 0], [-10, 10], [0, 0], "k")
    ax.plot([0, 0], [0, 0], [-10, 10], "k")
    ax.plot([], [], [], "b")


def update_lines(index):
    seg = []
    x = np.linspace(-10, 10, dotinline)
    power = x**(-(nframe-1)/2+index)
    for i in range(len(x)-1):
        a = [x[i+1], x[i]]
        b = [0, 0]
        c = [power[i+1], power[i]]
        seg.append([a, b, c])
    for data in seg:
        ax.plot3D(data[0], data[1], data[2], "-b")


ax.set_xlim3d([-10, 10])
ax.set_xlabel('X')
ax.set_ylim3d([-10, 10])
ax.set_ylabel('Y')
ax.set_zlim3d([-10, 10])
ax.set_zlabel('Z')
ax.set_title('3D Test')


line_ani = animation.FuncAnimation(fig, update_lines, init_func=init, frames=nframe, interval=2000, blit=False)

plt.show()

1 个答案:

答案 0 :(得分:0)

检查此代码:

import matplotlib; matplotlib.use("TkAgg")
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation
dotinline = 101
nframe = 7
fig = plt.figure(figsize=(16, 8))
ax = p3.Axes3D(fig)
ax.view_init(0, 90)


def init():
    ax.plot([-10, 10], [0, 0], [0, 0], "k")
    ax.plot([0, 0], [-10, 10], [0, 0], "k")
    ax.plot([0, 0], [0, 0], [-10, 10], "k")
    ax.plot([], [], [], "b")


def update_lines(index):
    ax.cla()
    init()
    seg = []
    x = np.linspace(-10, 10, dotinline)
    power = x**(-(nframe-1)/2+index)
    for i in range(len(x)-1):
        a = [x[i+1], x[i]]
        b = [0, 0]
        c = [power[i+1], power[i]]
        seg.append([a, b, c])
    for data in seg:
        ax.plot3D(data[0], data[1], data[2], "-b")


    ax.set_xlim3d([-10, 10])
    ax.set_xlabel('X')
    ax.set_ylim3d([-10, 10])
    ax.set_ylabel('Y')
    ax.set_zlim3d([-10, 10])
    ax.set_zlabel('Z')
    ax.set_title('3D Test')


line_ani = animation.FuncAnimation(fig, update_lines, init_func=init, frames=nframe, interval=2000, blit=False)

plt.show()

要删除前几行,只需添加ax.cla()
但是,这也会擦除黑线轴。因此,在ax.cla()之后,我再次运行init(),以便重新绘制轴线。
最后,最好移动该块:

ax.set_xlim3d([-10, 10])
ax.set_xlabel('X')
ax.set_ylim3d([-10, 10])
ax.set_ylabel('Y')
ax.set_zlim3d([-10, 10])
ax.set_zlabel('Z')
ax.set_title('3D Test')

update_lines()函数内部,以便即使删除行也能保留这些选项。
使用此代码,我得到以下动画:

enter image description here