我一直在谷歌搜索一段时间没有成功......也许我的关键词只是糟糕。无论如何,假设我有三个相同长度的1D numpy.ndarray
,我想将它们绘制成3D轨迹。此外,我希望能够做以下任何一件事:
z
This demo有一个做出这样一条曲线的例子:
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z)
plt.show()
但我如何实现1
或2
?欢迎只有一个或另一个的解决方案!
提前谢谢。
答案 0 :(得分:15)
与普通的2d图一样,沿普通线不能有渐变色。但是,您可以使用scatter
:
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
#1 colored by value of `z`
ax.scatter(x, y, z, c = plt.cm.jet(z/max(z)))
#2 colored by index (same in this example since z is a linspace too)
N = len(z)
ax.scatter(x, y, z, c = plt.cm.jet(np.linspace(0,1,N)))
plt.show()
for i in xrange(N-1):
ax.plot(x[i:i+2], y[i:i+2], z[i:i+2], color=plt.cm.jet(255*i/N))
答案 1 :(得分:11)
您可以分别绘制每个线段,如下所示。这只是循环超过6种预定义颜色,因为@ askewchan的答案已经很好地展示了如何使用色彩映射。
cols = 'rgbcmy'
for i in range(len(x)-1):
ax.plot(x[i:i+2], y[i:i+2], z[i:i+2], color=cols[i%6])