简体   繁体   中英

Matplotlib line color in 3D

I like plots like this, which show trends along lines in space:

高度依赖的轨迹

you can generate them with matplotlib using code such as the following:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
from mpl_toolkits.mplot3d.art3d import Line3DCollection

x = np.linspace(0,1,10)
y = np.random.random((10,))
t = np.linspace(0,1,10)

# set up a list of (x,y) points
points = np.array([x,y]).transpose().reshape(-1,1,2)
print(points.shape)  # Out: (len(x),1,2)

# set up a list of segments
segs = np.concatenate([points[:-1],points[1:]],axis=1)
print(segs.shape)  # Out: ( len(x)-1, 2, 2 )
                  # see what we've done here -- we've mapped our (x,y)
                  # points to an array of segment start/end coordinates.
                  # segs[i,0,:] == segs[i-1,1,:]

# make the collection of segments
lc = LineCollection(segs, cmap=plt.get_cmap('jet'))
lc.set_array(t) # color the segments by our parameter

# plot the collection
plt.gca().add_collection(lc) # add the collection to the plot
plt.xlim(x.min(), x.max()) # line collections don't auto-scale the plot
plt.ylim(y.min(), y.max())

plt.show()

Result:

带彩色线的2d图

But how can we go to three dimensions (3D)?

3d线图

The following works:

import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d.art3d import Line3DCollection

x = np.linspace(0,1,10)
y = np.random.random((10,))
z = np.linspace(0,1,10)
t = np.linspace(0,1,10)

# generate a list of (x,y,z) points
points = np.array([x,y,z]).transpose().reshape(-1,1,3)
print(points.shape)  # Out: (len(x),1,3)

# set up a list of segments
segs = np.concatenate([points[:-1],points[1:]],axis=1)
print(segs.shape)  # Out: ( len(x)-1, 2, 3 )
                  # see what we've done here -- we've mapped our (x,y,z)
                  # points to an array of segment start/end coordinates.
                  # segs[i,0,:] == segs[i-1,1,:]

# make the collection of segments
lc = Line3DCollection(segs, cmap=plt.get_cmap('jet'))
lc.set_array(t) # color the segments by our parameter

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

with the result:

3D彩色线

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM