You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为3D非结构化网格三角曲面及投影曲线添加渐变颜色

非结构化网格3D曲面及投影曲线的渐变颜色实现方案

核心实现思路

  • 用scipy.spatial.Delaunay完成非结构化网格的三角剖分
  • 3D曲面通过matplotlib.tri.Triangulation关联剖分结果,结合plot_trisurf与颜色映射实现渐变效果
  • 投影曲线复用曲面的颜色映射规则,通过LineCollection实现渐变线条,保证与曲面颜色对应一致

完整实现代码

import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import Delaunay
from matplotlib.tri import Triangulation
from matplotlib.collections import LineCollection

# 生成非结构化(x,y)点集
np.random.seed(42)
n_points = 100
x = np.random.uniform(-2, 2, n_points)
y = np.random.uniform(-2, 2, n_points)
points = np.vstack((x, y)).T

# Delaunay三角剖分
tri = Delaunay(points)
triang = Triangulation(x, y, tri.simplices)

# 定义z值计算函数(可替换为业务逻辑)
def z_func(x, y):
    return np.sin(np.sqrt(x**2 + y**2)) * np.exp(-0.1*(x**2 + y**2))

z = z_func(x, y)

# 创建3D绘图对象
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111, projection='3d')

# 绘制带渐变颜色的3D三角曲面
surf = ax.plot_trisurf(triang, z, cmap='viridis', edgecolor='none', alpha=0.8)

# 绘制xz平面(y=0)的渐变投影曲线
xz_sort_idx = np.argsort(x)
x_sorted = x[xz_sort_idx]
z_xz_sorted = z[xz_sort_idx]
# 复用曲面的颜色映射规则
colors_xz = surf.cmap(surf.norm(z_xz_sorted))
# 拆分曲线为线段,用LineCollection实现渐变
points_xz = np.array([x_sorted, np.zeros_like(x_sorted), z_xz_sorted]).T.reshape(-1, 1, 3)
segments_xz = np.concatenate([points_xz[:-1], points_xz[1:]], axis=1)
lc_xz = LineCollection(segments_xz, colors=colors_xz, linewidth=2)
ax.add_collection3d(lc_xz, zs=0, zdir='y')

# 绘制yz平面(x=0)的渐变投影曲线
yz_sort_idx = np.argsort(y)
y_sorted = y[yz_sort_idx]
z_yz_sorted = z[yz_sort_idx]
colors_yz = surf.cmap(surf.norm(z_yz_sorted))
points_yz = np.array([np.zeros_like(y_sorted), y_sorted, z_yz_sorted]).T.reshape(-1, 1, 3)
segments_yz = np.concatenate([points_yz[:-1], points_yz[1:]], axis=1)
lc_yz = LineCollection(segments_yz, colors=colors_yz, linewidth=2)
ax.add_collection3d(lc_yz, zs=0, zdir='x')

# 调整显示设置
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('3D Triangulated Surface with Gradient Projections')
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.tight_layout()
plt.show()

关键细节说明

  • 颜色映射同步:曲面的颜色由z值通过cmap和norm转换得到,投影曲线直接复用这套规则,确保曲线颜色与曲面对应点完全匹配
  • 渐变曲线实现:原生plot无法生成渐变线条,因此将曲线拆分为连续线段,用LineCollection为每个线段分配对应颜色,再通过add_collection3d添加到指定投影平面
  • 非结构化网格适配:Triangulation将Delaunay剖分结果与(x,y,z)数据绑定,确保曲面正确渲染非规则分布的点集

内容的提问来源于stack exchange,提问作者user24353751

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 19:12:26