Python实现2D转3D网格时z值与x、y坐标映射错误问题排查
问题根因
你的坐标映射错误核心来自网格维度顺序不匹配,同时存在冗余的手动构造网格操作:
np.meshgrid(xi, yi)默认采用indexing='xy'模式,生成的x、y数组形状为(375, 625):行维度对应yi的索引,列维度对应xi的索引- 你后续手动构造
xy数组时,外层循环遍历xi、内层循环遍历yi,生成的数组形状为(625, 375, 2),和meshgrid输出的维度顺序完全相反,最终导致z值和x/y坐标配对错误
修正方案
不需要手动构造xy数组,直接对meshgrid生成的x、y做拼接即可,修正后代码如下:
import pandas as pd import math import numpy as np import matplotlib.mlab as mlab import matplotlib.tri as tri import matplotlib.pyplot as plt from matplotlib import rcParams #define the flow potential equation where X,Y is the injection well locations and x,y is the point of interest, Q is flow rate def func(X, Y, x, y, Q): return (Q / (2 * np.pi)) * np.arctan((y-Y)/(x-X)) # necessary data X1=2318743.658 Y1=797346.704 Q1=5 X2=2318690.718 Y2=797343.693 Q2=5 X3=2318715.221 Y3=797309.685 Q3=5 #initiate the XY grid - this will be a standard that will encompass all IW and MW xi = np.linspace(2318675,2318800,625) yi = np.linspace(797300,797375,375) #mesh the grid in to x,y space x,y = np.meshgrid(xi,yi) #calculate the valus over the grid at every x,y using the defined function above zi = (func(X1,Y1,x,y,Q1)+func(X2,Y2,x,y,Q2)+func(X3,Y3,x,y,Q3)) # 直接拼接xyz,无需手动构造网格 # 先将x、y、zi扩展为最后一维为1的数组,再沿最后一维拼接 xyz = np.concatenate([x[..., np.newaxis], y[..., np.newaxis], zi[..., np.newaxis]], axis=-1)
验证方法
你可以随机取一个坐标点验证配对正确性:
比如取xi的第10个值、yi的第20个值,单独计算函数值,再和xyz[20,10,:]的结果对比,两者完全一致即说明配对正确。
内容的提问来源于stack exchange,提问作者Melanie
相关产品推荐
相关产品推荐

