[英]Updating line in 3D plot Animation
我正在尝试 plot 中的一行 3D animation。 我无法擦除我在 update_line 中创建的图。 问题是我总是添加新行。 我看到的最佳解决方案是在 function 之外创建行并更新这些行的数据,但我似乎无法在 3D 中找到 plot 的方法
第一次发帖,仅仅几个小时的 python。 对 canvas 一无所知。 请保持简单
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()
检查此代码:
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()
function 中,以便在删除行时保留这些选项。
使用此代码,我得到以下 animation:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.