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?
The plotting method you want to use for 3D plots is the one from the
Axes3D
. Hence you need to plotHowever, 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 dimensionset_3d_properties
. Updating the plot would look like this: