1

I would like to plot say 10 lines in 3D in matplotlib, but without having to use ax.plot(x,y,z) 10 times. This is the ridiculous code I've come up with b/c I can't envision how the zip and arrays actually work together.

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

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

x = np.array([0.,3.])
y = np.array([0.,0.])
z = np.array([0.,0.])

u = np.array([0.,3.])
v = np.array([.5,.5])
w = np.array([0.,0.])

a = np.array([0.,3.])
b = np.array([1.,1.])
c = np.array([0.,0.])

e = np.array([0.,3.])
d = np.array([1.5,1.5])
f = np.array([0.,0.])

r = np.array([0.,3.])
s = np.array([2.,2.])
t = np.array([0.,0.])

ax.set_xlabel("x axis")
ax.set_ylabel("y axis")
ax.set_zlabel("z axis")


ax.plot(x,y,z)
ax.plot(a,b,c)
ax.plot(r,s,t)
ax.plot(u,v,w)
ax.plot(e,d,f)


plt.show()

I'm guessing I'll use zip and/or a for loop. Thanks, and here's the figure.enter image description here

1 Answer 1

1

You could store all your data points in a large data array. This way you can loop over the array and do something like this:

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

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

# initialize array with size number of lines
data = np.full((2,3), None) 

# fill data array with data points [x,y,z]
data[0] = [[0,3],[0,0],[0,0]]
data[1] = [[0,3],[0.5,0.5],[0,0]]
# etc...

# loop over data array and plot lines
for line in data:
    ax.plot(line[0],line[1],line[2])

plt.show()

There are many different ways on how to store your data, you could also skip the initialization step by just creating the array in one take:

data = np.array([[[0,3],[0,0],[0,0]],
                 [[0,3],[0.5,0.5],[0,0]],
                 [[0,3],[0.5,0.5],[0,0]],
                 [...] ])

Or use numpy functions like numpy.concatenate to add new lines to the data array.

Sign up to request clarification or add additional context in comments.

Comments

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.