Matplotlib附加到z轴

问题描述 投票:0回答:1

我想使用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()

如何正确完成这项工作?

python matplotlib 3d z-axis
1个回答
0
投票

您想要用于3D绘图的绘图方法是来自Axes3D的绘图方法。因此你需要绘图

ax1.plot(x, y, z)

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

所以你可以使用set_data和第三维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()
© www.soinside.com 2019 - 2024. All rights reserved.