如何在Matplotlib等值线内计算面积与变量总和求解速度场体积及输运量
解决Matplotlib等值线多区域的面积计算与变量求和问题
需求是编写Python脚本,计算Matplotlib等值线(contour)内的面积,并对区域内的变量求和,以此求解速度场中的体积和输运量。当前代码使用Matplotlib原生方法和鞋带公式,但无法处理等值线图中两个分离区域的情况,存在两个核心问题:
- 仅提取了每个等值线集合的第一个路径,忽略了多区域的子路径
- 变量求和用矩形范围筛选,会包含等值线外的点,结果不准确

修正后的代码
import numpy as np import matplotlib.pyplot as plt from matplotlib.path import Path from matplotlib.patches import Polygon # 假设X、Y、CC_vel、CC_percentage已提前定义 cc_cont = ax1.contour(X, Y, CC_vel, levels=[int(np.nanmax(CC_vel)*CC_percentage)], colors='k') plt.clabel(cc_cont, inline=True, fontsize=15) total_area = 0.0 total_variable_sum = 0.0 # 遍历每个等值线集合 for c in cc_cont.collections: # 遍历集合内的所有路径(对应所有分离区域) for path in c.get_paths(): vertices = path.vertices # 用鞋带公式计算单个区域的面积 area = 0.5 * np.abs(np.dot(vertices[:, 0], np.roll(vertices[:, 1], 1)) - np.dot(vertices[:, 1], np.roll(vertices[:, 0], 1))) total_area += area ax1.add_patch(Polygon(vertices, color='red', alpha=0.6)) # 将网格点转换为Nx2的点数组 points = np.vstack([X.ravel(), Y.ravel()]).T # 判断每个点是否在当前等值线区域内 inside = Path(vertices).contains_points(points) # 筛选区域内的变量值并求和 variable_sum = np.sum(CC_vel.ravel()[inside]) total_variable_sum += variable_sum print(f'等值线内总面积: {total_area}') print(f'等值线内变量总和: {total_variable_sum}')
关键改进点
- 遍历每个等值线集合的所有路径,确保覆盖所有分离的等值线区域
- 使用
Path.contains_points()精确判断网格点是否在等值线内,替代原有的矩形范围筛选,避免包含区域外的点 - 新增总面积和总变量求和的累加逻辑,得到所有区域的总和
内容的提问来源于stack exchange,提问作者J Knight
相关产品推荐
相关产品推荐

