Python - 3D 参数曲线的线条颜色

1 投票
1 回答
1979 浏览
提问于 2025-04-18 07:50

我有两个列表tab_x(里面是x的值)和tab_z(里面是z的值),它们的长度是一样的,还有一个y的值

我想画一个3D曲线,用z的值来给曲线上色。我知道可以画成2D图,但我想画几个不同y值的图来比较,所以我需要是3D的。

我的tab_z里面还有负值。

我在这个问题中找到了用时间(索引)给曲线上色的代码,但我不知道怎么把这个代码改成适合我的情况。

谢谢你的帮助。

我加上我的代码以便更具体:

fig8 = plt.figure()
ax8 = fig8.gca(projection = '3d')
tab_y=[]
for i in range (0,len(tab_x)):
  tab_y.append(y)
ax8.plot(tab_x, tab_y, tab_z)

现在我有这个

enter image description here

我试过这个代码

for i in range (0,len(tab_t)):
    ax8.plot(tab_x[i:i+2], tab_y[i:i+2], tab_z[i:i+2],color=plt.cm.rainbow(255*tab_z[i]/max(tab_z)))

完全失败了:

enter image description here

1 个回答

5

你第二次尝试得很接近了。唯一需要改动的是,传给 colormap 的 cm.jet() 输入值需要在0到1的范围内。你可以用 Normalize 来调整你的 z 值,使它们适应这个范围。

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

fig = plt.figure()
ax = fig.gca(projection='3d')

N = 100
y = np.ones((N,1))
x = np.arange(1,N + 1)
z = 5*np.sin(x/5.)

cn = colors.Normalize(min(z), max(z)) # creates a Normalize object for these z values
for i in xrange(N-1):
    ax.plot(x[i:i+2], y[i:i+2], z[i:i+2], color=plt.cm.jet(cn(z[i])))

plt.show()

缩放 z 值的 3D 图

撰写回答