我现在有这个代码:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
x = np.arange(1,6)
y = np.arange(5,11)
z = np.arange(3,9)
for i in range(4):
ax.plot([x[i], x[i+1]], [y[i],y[i+1]],[z[i],z[i+1]])
plt.show()
我想展示曲线的进展情况(移动)。但这并不奏效。它显示第一行,没有办法移动到下一个绘图,当我关闭窗口时,程序刚刚结束,没有向我显示接下来的3行。
我最后还尝试添加plt.waitforbuttonpress()
,但它没有帮助。
我是python的新手,所以我可能会遗漏一些简单的东西。谢谢你的帮助!
答案 0 :(得分:1)
听起来你需要3D animation。希望这是你想要的:
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation
def move_curve(i, line, x, y, z):
line.set_data([[x[i], x[i+1]], [y[i],y[i+1]]])
line.set_3d_properties([z[i],z[i+1]])
fig = plt.figure()
ax = fig.gca(projection='3d')
x = np.arange(1,6)
y = np.arange(5,11)
z = np.arange(3,9)
i = 0
line = ax.plot([x[i], x[i+1]], [y[i],y[i+1]], [z[i],z[i+1]])[0]
ax.set_xlim3d([1, 5])
ax.set_ylim3d([5, 10])
ax.set_zlim3d([3, 8])
line_ani = animation.FuncAnimation(fig, move_curve, 4, fargs=(line, x, y, z))
基本思路是为每个帧循环添加一个点,而不是更改该行的起点和终点:
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation
def move_curve(i, line, x, y, z):
# Add points rather than changing start and end points.
line.set_data(x[:i+1], y[:i+1])
line.set_3d_properties(z[:i+1])
fig = plt.figure()
ax = fig.gca(projection='3d')
x = np.arange(1,6)
y = np.arange(5,11)
z = np.arange(3,9)
i = 0
line = ax.plot([x[i], x[i+1]], [y[i],y[i+1]], [z[i],z[i+1]])[0]
ax.set_xlim3d([1, 5])
ax.set_ylim3d([5, 10])
ax.set_zlim3d([3, 8])
line_ani = animation.FuncAnimation(fig, move_curve, 5, fargs=(line, x, y, z))
基本思路是:
ax
作为fargs
之一传递,以便您可以使用ax
更新轴限制。以下是一些代码。需要明确的是,以下代码不是最好的设计,可能适合您的需求,也可能不适合您。但我认为这是一个很好的起点。
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation
def move_curve(num, ax, lines, x, y, z):
for i in range(num+1):
if i % 2 == 1:
continue
lines[i].set_data([[x[i], x[i+1]], [y[i],y[i+1]]])
lines[i].set_3d_properties([z[i],z[i+1]])
ax.set_xlim3d([1, x[i+1]])
ax.set_ylim3d([5, y[i+1]])
ax.set_zlim3d([3, z[i+1]])
return lines
fig = plt.figure()
ax = fig.gca(projection='3d')
x = np.arange(1,6)
y = np.arange(5,11)
z = np.arange(3,9)
lines = [ax.plot([], [], [])[0] for i in range(4)]
line_ani = animation.FuncAnimation(fig, move_curve, 4, fargs=(ax, lines, x, y, z), repeat=False)