1

I want to plot several 3D points with matplotlib. My coordinates are stored in 2D arrays because i got multiple cases and so i would like to plot all the cases in a same 3D plot with a "for loop" but when i do that, the results appeared on different plots...

As example :

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

X = np.array([[3,2,1],[4,5,6]])
Y = np.array([[1,2,1],[2,3,4]])
Z = np.array([[10,11,12],[13,12,16]])

for i in range(0,X.shape[0]):

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    ax.scatter(X[i,:], Y[i,:], Z[i,:], c='r', marker='o')

    ax.set_xlabel('Z')
    ax.set_ylabel('X')
    ax.set_zlabel('Y')

    plt.show()

1 Answer 1

2

You create a new figure each iteration and plot it each iteration. Also you always create the first suplot of a 1x1 subplot-grid.

You probably want a x.shape[0] x 1 grid or 1 x x.shape[0] grid:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

X = np.array([[3,2,1],[4,5,6]])
Y = np.array([[1,2,1],[2,3,4]])
Z = np.array([[10,11,12],[13,12,16]])

# Create figure outside the loop
fig = plt.figure()

for i in range(0,X.shape[0]):
    
    # Add the i+1 subplot of the x.shape[0] x 1 grid
    ax = fig.add_subplot(X.shape[0], 1, i+1, projection='3d')

    ax.scatter(X[i,:], Y[i,:], Z[i,:], c='r', marker='o')

    ax.set_xlabel('Z')
    ax.set_ylabel('X')
    ax.set_zlabel('Y')
# Show it outside the loop
plt.show()

EDIT:

If you want to plot them all into the same plot use:

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
ax.set_xlabel('Z')
ax.set_ylabel('X')
ax.set_zlabel('Y')

for i in range(0,X.shape[0]):
    # Only do the scatter inside the loop
    ax.scatter(X[i,:], Y[i,:], Z[i,:], c='r', marker='o')

plt.show()
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your help but i m trying to plot all the couples on a same grid.
@user3601754 - I've appended it at the end of the answer, check it out if that solves your problem.
and is it possible to use different markers or colors for each couple?
yes. The solution would be to define colors=['r', 'g', 'b'] and then change c=colors[i % 3]. For the markers the same applies.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.