Search code examples
pythonmatplotlib3dz-axis

Matplotlib append to z axis


I want to plot in 3D using matplotlib (python), which data is added in real time(x,y,z).

In the below code, data appends on x-axis and y-axis successfully, but on z-axis I've encountered problems.although I've searched in matplotlib's docs, I could not find any solutions.

what should be added/changed to this code to make it append data in z-axis?

what works correctly:

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

problem:

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

Code:

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()

How to get this done correctly?


Solution

  • The plotting method you want to use for 3D plots is the one from the Axes3D. Hence you need to plot

    ax1.plot(x, y, z)
    

    However, it seems you want to update the data instead of plotting it all over again (making the line look somehow rasterized, as it would consists of all the plots).

    So you can use set_data and for the third dimension set_3d_properties. Updating the plot would look like this:

    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()