How to make a 3D scatter plot in Python?
-
22-09-2019 - |
문제
I am currently have a nx3 matrix array. I want plot the three columns as three axis's. How can I do that?
I have googled and people suggested using Matlab, but I am really having a hard time with understanding it. I also need it be a scatter plot.
Can someone teach me?
해결책
You can use matplotlib for this. matplotlib has a mplot3d module that will do exactly what you want.
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
import random
fig = pyplot.figure()
ax = Axes3D(fig)
sequence_containing_x_vals = list(range(0, 100))
sequence_containing_y_vals = list(range(0, 100))
sequence_containing_z_vals = list(range(0, 100))
random.shuffle(sequence_containing_x_vals)
random.shuffle(sequence_containing_y_vals)
random.shuffle(sequence_containing_z_vals)
ax.scatter(sequence_containing_x_vals, sequence_containing_y_vals, sequence_containing_z_vals)
pyplot.show()
The code above generates a figure like:
다른 팁
Use the following code it worked for me:
# Create the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Generate the values
x_vals = X_iso[:, 0:1]
y_vals = X_iso[:, 1:2]
z_vals = X_iso[:, 2:3]
# Plot the values
ax.scatter(x_vals, y_vals, z_vals, c = 'b', marker='o')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
plt.show()
while X_iso is my 3-D array and for X_vals, Y_vals, Z_vals I copied/used 1 column/axis from that array and assigned to those variables/arrays respectively.
Use asymptote instead!
This is what it can look like:
http://asymptote.sourceforge.net/gallery/3D%20graphs/helix.pdf
This is the code: http://asymptote.sourceforge.net/gallery/3D%20graphs/helix.asy
Asymptote can also read in data files.
And the full gallery: http://asymptote.sourceforge.net/gallery/
To use asymptote from within Python:
http://www.tex.ac.uk/tex-archive/graphics/asymptote/base/asymptote.py