0

我想使用matplotlib(python)以3D形式绘制,这些数据是实时添加的(x,y,z)。

在下面的代码中,数据成功附加在 x 轴和 y 轴上,但在 z 轴上我遇到了问题。虽然我在 matplotlib 的文档中搜索过,但我找不到任何解决方案。

应该在此代码中添加/更改什么以使其在 z 轴中附加数据?

什么工作正常:

return plt.plot(x, y, color='g') 

问题:

return plt.plot(x, y, z, color='g')

代码:

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

np.set_printoptions(threshold=np.inf)
fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')


x = []
y = []
z = []
def animate(i):
    x.append(random.randint(0,5))
    y.append(random.randint(0,5))
    z.append(random.randint(0,5))

    return plt.plot(x, y, color='g')
    #return plt.plot(x, y, z, color='g') => error


ani = animation.FuncAnimation(fig, animate, interval=1000)
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_zlabel('z')
plt.show()

如何正确完成这项工作?

4

1 回答 1

0

您要用于 3D 绘图的绘图方法是Axes3D. 因此你需要绘制

ax1.plot(x, y, z)

但是,您似乎想要更新数据而不是重新绘制它(使线条看起来以某种方式栅格化,因为它包含所有图)。

因此,您可以将set_dataand 用于第三维set_3d_properties。更新情节将如下所示:

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

fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')

x = []
y = []
z = []

line, = ax1.plot(x,y,z)

def animate(i):
    x.append(np.random.randint(0,5))
    y.append(np.random.randint(0,5))
    z.append(np.random.randint(0,5))
    line.set_data(x, y)
    line.set_3d_properties(z)


ani = animation.FuncAnimation(fig, animate, interval=1000)
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_zlabel('z')
ax1.set_xlim(0,5)
ax1.set_ylim(0,5)
ax1.set_zlim(0,5)
plt.show()
于 2017-12-16T11:50:44.727 回答