matplotlib 三维渐变曲线
时间: 2025-04-23 20:28:47 浏览: 25
### 使用 Matplotlib 绘制带颜色渐变效果的三维曲线
为了创建具有颜色渐变特性的三维曲线图表,mplot3d 模块提供了必要的工具来扩展常规绘图功能至第三维度[^1]。下面是一个具体的例子,展示了怎样利用 `LineCollection` 类结合自定义色彩映射方案实现这一目标。
```python
import numpy as np
from matplotlib.collections import LineCollection
from mpl_toolkits.mplot3d.art3d import Line3DCollection
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap, BoundaryNorm
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
# 创建数据集
t = np.linspace(0, 10 * np.pi, 500)
x = np.sin(t)
y = np.cos(t)
z = t / (2. * np.pi)
# 定义颜色变化范围并应用到线条上
points = np.array([x, y, z]).T.reshape(-1, 1, 3)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
cmap = ListedColormap(['r', 'g', 'b'])
norm = plt.Normalize(z.min(), z.max())
lc = Line3DCollection(segments, cmap=cmap, norm=norm)
lc.set_array(z)
lc.set_linewidth(2)
line = ax.add_collection(lc)
fig.colorbar(line, ax=ax, orientation='vertical')
ax.set_xlim(x.min()-0.1, x.max()+0.1)
ax.set_ylim(y.min()-0.1, y.max()+0.1)
ax.set_zlim(z.min(), z.max())
plt.show()
```
此段代码首先构建了一个螺旋形状的空间路径,并通过调整每一段线段的颜色实现了从红色过渡到蓝色的效果。这里采用了 `ListedColormap` 来指定离散的颜色序列,而连续的变化则由 `BoundaryNorm` 控制着色区间[^4]。
阅读全文
相关推荐

















