【问题标题】:Matplotlib append to z axisMatplotlib 附加到 z 轴
【发布时间】:2017-12-16 19:50:44
【问题描述】:

我想使用 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】:

    您要用于 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-09
      • 1970-01-01
      • 2016-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-09
      相关资源
      最近更新 更多