Python二维数组绘制不规则多边形:代码问题排查与修正
问题分析与修正方案
错误原因
你的代码核心问题是坐标体系不匹配:
- 定义的
polygon_vertices用的是网格索引值(比如(10,10)对应第10行第10列的网格点),但判断点是否在多边形内时,传入的是X[i,j]和Y[i,j]——这两个是0到1.7之间的物理坐标值,两者数值范围完全不重叠,导致polygon_path.contains_point()始终返回False,数组s自然不会被修改。 - 额外问题:嵌套双层循环遍历整个数组,效率较低,numpy场景下更适合用向量化操作优化。
修正方案(两种可选)
方案1:将多边形顶点转换为物理坐标
如果你的polygon_vertices原本想表示网格索引,先把它转换成对应的物理坐标,再进行判断:
import numpy as np import matplotlib.path as mpath import pandas as pd # variable declarations Lx = 1.7 Ly = 1.7 Nx = 170 Ny = 170 x = np.linspace(0, Lx, Nx+1) # x方向空间网格 y = np.linspace(0, Ly, Ny+1) # y方向空间网格 X, Y = np.meshgrid(x, y) # s array s = np.zeros((Ny+1, Nx+1)) # 将网格索引顶点转换为物理坐标 polygon_indices = [(10, 10), (50, 10), (50, 70), (10, 70)] polygon_vertices = [(x[j], y[i]) for i, j in polygon_indices] polygon_path = mpath.Path(polygon_vertices) # 向量化判断,替代双层循环 points = np.column_stack((X.flatten(), Y.flatten())) mask = polygon_path.contains_points(points).reshape(s.shape) s[mask] = 100 df = pd.DataFrame(s) df.to_excel('s.xlsx', index=False)
方案2:直接用网格索引进行判断
如果你的多边形顶点本身就是网格索引,直接用i,j(网格行列号)作为判断点:
import numpy as np import matplotlib.path as mpath import pandas as pd # variable declarations Lx = 1.7 Ly = 1.7 Nx = 170 Ny = 170 x = np.linspace(0, Lx, Nx+1) # x方向空间网格 y = np.linspace(0, Ly, Ny+1) # y方向空间网格 X, Y = np.meshgrid(x, y) # s array s = np.zeros((Ny+1, Nx+1)) polygon_vertices = [(10, 10), (50, 10), (50, 70), (10, 70)] polygon_path = mpath.Path(polygon_vertices) # 向量化生成网格索引点 i_indices, j_indices = np.meshgrid(np.arange(Ny+1), np.arange(Nx+1), indexing='ij') points = np.column_stack((i_indices.flatten(), j_indices.flatten())) mask = polygon_path.contains_points(points).reshape(s.shape) s[mask] = 100 df = pd.DataFrame(s) df.to_excel('s.xlsx', index=False)
内容的提问来源于stack exchange,提问作者shoutong wang
相关产品推荐
相关产品推荐

