I’m trying to plot a 3d curve that has different colors depending on one of its parameters. I tried this method similar to this question, but it doesn’t work. Can anyone point me in the right direction?
JavaScript
x
14
14
1
import matplotlib.pyplot as plt
2
from matplotlib import cm
3
4
T=100
5
N=5*T
6
x=np.linspace(0,T,num=N)
7
y=np.cos(np.linspace(0,T,num=N))
8
z=np.sin(np.linspace(0,T,num=N))
9
10
fig = plt.figure()
11
ax = fig.gca(projection='3d')
12
ax.plot(x,y,z,cmap = cm.get_cmap("Spectral"),c=z)
13
plt.show()
14
Advertisement
Answer
To extend the approach in this tutorial to 3D, use x,y,z instead of x,y.
The desired shape
for the segments is (number of segments, 2 points, 3 coordinates per point)
, so N-1,2,3
. First the array of points is created with shape N, 3
. Then start (xyz[:-1, :]
) and end points (xyz[1:, :]
) are stacked together.
JavaScript
1
23
23
1
import matplotlib.pyplot as plt
2
from mpl_toolkits.mplot3d.art3d import Line3DCollection
3
4
T = 100
5
N = 5 * T
6
x = np.linspace(0, T, num=N)
7
y = np.cos(np.linspace(0, T, num=N))
8
z = np.sin(np.linspace(0, T, num=N))
9
10
xyz = np.array([x, y, z]).T
11
segments = np.stack([xyz[:-1, :], xyz[1:, :]], axis=1) # shape is 499,2,3
12
cmap = plt.cm.get_cmap("Spectral")
13
norm = plt.Normalize(z.min(), z.max())
14
lc = Line3DCollection(segments, linewidths=2, colors=cmap(norm(z[:-1])))
15
16
fig = plt.figure()
17
ax = fig.gca(projection='3d')
18
ax.add_collection(lc)
19
ax.set_xlim(-10, 110)
20
ax.set_ylim(-1.1, 1.1)
21
ax.set_zlim(-1.1, 1.1)
22
plt.show()
23