[Pyplot] 绘制3D曲面+自定义面片颜色

本文展示了如何使用Python的matplotlib库绘制3D曲面图,并提供了两种方法来设定面片颜色:一是根据面片的法向量自定义颜色,二是应用默认的jetcolormap。代码中通过生成曲面点并计算法向量,然后使用这些信息来设置每个面片的颜色,最后展示图形。

一、背景

使用python+matplotlib实现绘制3D曲面(由多个小面片组成),支持自定义面片颜色;
实现效果如图(a),(b)所示:

使用面片法向作为面片颜色
(a) . 使用面片法向作为面片颜色
使用默认jet类型colormap作为面片颜色
(b) . 使用默认jet类型colormap作为面片颜色

二、代码

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np

# 生成曲面各点 (x,y,z)
# 曲面点位置:(x=x, y=y, z=x*y)
# 曲面点法向: (y, x, 1.0)

x = np.linspace(-0.5, 0.5, 10)
y = np.linspace(-0.5, 0.5, 10)
z = np.zeros((len(x), len(y)))

nor = np.zeros((len(x), len(y),3))
nor_x_min = np.float64('inf')
nor_x_max = -1.0*np.float64('inf')
nor_y_min = np.float64('inf')
nor_y_max = -1.0*np.float64('inf')

for i in range(len(x)):
    for j in range(len(y)):
        z[i][j] = x[i]*y[j]
        nor[i][j] = (y[j], x[i], 1.0)
        nor_x_min = np.fmin(nor_x_min, nor[i][j][0])
        nor_x_max = np.fmax(nor_x_max, nor[i][j][0])
        
        nor_y_min = np.fmin(nor_y_min, nor[i][j][1])
        nor_y_max = np.fmax(nor_y_max, nor[i][j][1])

# 绘制曲面 
# 曲面由多个面片组成 各面片颜色根据法向确定
x, y = np.meshgrid(x, y)
fig = plt.figure()
ax = fig.add_subplot(
    111, projection='3d')

f = np.zeros((len(z), len(z[0])), tuple)
for i in range(len(f)):
    for j in range(len(f[i])):
        f[i][j] = ((nor[i][j][0]-nor_x_min)/(nor_x_max-nor_x_min), (nor[i][j][1]-nor_y_min)/(nor_y_max-nor_y_min), 1.0)
# 使用面片法向作为面片颜色
ax.plot_surface(x, y, z, facecolors=f)
# 使用默认jet类型colormap作为面片颜色
# ax.plot_surface(x, y, z, cmap=cm.jet)
plt.show()
import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D from matplotlib.colors import Normalize from scipy.interpolate import griddata # --------------------- 1. 原始数据与公共参数 --------------------- data = { "30min": { "temperatures": [ [0.00, 74.80, 80.08, 80.96, 78.32, 76.56, 0.00], [0.00, 64.33, 68.87, 69.63, 67.36, 65.84, 0.00], [0.00, 48.62, 52.05, 52.62, 50.91, 49.76, 0.00], [0.00, 28.42, 30.43, 30.76, 29.76, 29.09, 0.00], [0.00, 8.98, 9.61, 9.72, 9.40, 9.19, 0.00], [0.00, 1.50, 1.60, 1.62, 1.57, 1.53, 0.00] ] } } # 公共参数 depths = [0, 17, 34, 51, 68, 85] # 原始深度 (mm) horizontal_positions = [0, 50, 150, 250, 350, 450, 500] # 水平位置 (mm) heating_times = [10, 20, 30] # 加热时间 (min) profile_idx = horizontal_positions.index(250) # 250mm对应的列索引 mirror_depths = np.concatenate([-np.array(depths[1:])[::-1], depths]) # 镜像深度(对称于0mm) # --------------------- 2. 绘制2D镜像温度分布图 --------------------- def plot_2d_mirror(): fig_2d = plt.figure(figsize=(18, 12)) norm = Normalize(vmin=0, vmax=100) # 统一色标0-100℃ cmap = 'jet' for i, (time_key, time_data) in enumerate(data.items()): # 创建镜像温度矩阵 original_temps = np.array(time_data["temperatures"]) mirror_temps = np.vstack([original_temps[1:][::-1], original_temps]) # 创建网格 X, Y = np.meshgrid(horizontal_positions, mirror_depths) # 绘制二维温度分布图 ax = fig_2d.add_subplot(2, 3, i+1) contour = ax.contourf(X, Y, mirror_temps, levels=20, cmap=cmap, norm=norm) # 设置标题和坐标轴 ax.set_title(f'Heating Time: {time_key}', fontsize=14) ax.set_xlabel('Horizontal Position (mm)', fontsize=12) ax.set_ylabel('Depth (mm)', fontsize=12) ax.set_xlim(0, 500) ax.set_ylim(-85, 85) ax.grid(True, linestyle='--', alpha=0.5) # 添加色标 cbar = plt.colorbar(contour, ax=ax) cbar.set_label('Temperature (°C)', fontsize=12) # 添加250mm处的垂直线 ax.axvline(x=250, color='red', linestyle='--', linewidth=1.5, alpha=0.7) ax.text(255, 70, '250mm', color='red', fontsize=10, bbox=dict(facecolor='white', alpha=0.7)) # 添加对称轴标记 ax.axhline(y=0, color='black', linestyle='-', linewidth=1.0) ax.text(10, 5, 'Symmetry Plane (Depth=0)', color='black', fontsize=10, bbox=dict(facecolor='white', alpha=0.7)) fig_2d.suptitle('2D Temperature Distribution with Mirror Effect', fontsize=16, y=0.95) plt.tight_layout(rect=[0, 0, 1, 0.95]) return fig_2d fig_2d = plot_2d_mirror() plt.show() 将这个代码所绘制出来的二维平面数据沿Y=0这个轴旋转圈,就得到了维数据,再将>0的区域显示出来。就得到了被加热区域的范围示意图。图形的照片类似一个球形
07-29
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值