Skip to main content
 首页 » 编程设计

python之将 map 坐标转换为纬度/经度

2025年05月04日26emanlee

收到了一个非常有用的解决方案,解决了我的轮廓不规则数据问题,Contours with map overlay on irregular grid in python ,在这里我仍然有将等高线与 basemap 结合的问题。为此,我知道我必须这样做: x,y = m(lon,lat)。 我看到的SO帖子没有一个符合我的需求。我的问题是我从哪里得到(从我的各种可用参数中)lon, lat 在上面的公式中使用的 x,y? 这是我的 map 对象:

m = Basemap(projection = 'merc',llcrnrlon = 21, llcrnrlat = -18, urcrnrlon = 34, urcrnrlat = -8, resolution='h') 

这里是等高线和网格化的数据:

data = pd.read_csv('meansr.txt', delim_whitespace=True) 
numcols, numrows = 300, 300 
xi = np.linspace(data.Lon.min(), data.Lon.max(), numcols) 
yi = np.linspace(data.Lat.min(), data.Lat.max(), numrows) 
xi, yi = np.meshgrid(xi, yi) 
 
x, y, z = data.Lon.values, data.Lat.values, data.Z.values 
zi = griddata(x, y, z, xi, yi) 

下面是绘图命令

plt.figure() 
plt.contourf(xi, yi, zi) 
plt.scatter(data.Lon, data.Lat, c=data.Z, s=100, 
vmin=zi.min(), vmax=zi.max()) 
plt.colorbar() 
plt.show() 

这给了我两个图,一个 basemap 和并排的等高线,我认为这是由于两个坐标的差异。指向等值线内部表示正确的纬度和经度,而在 map 上显示的 x, y 非常大,数量级为 2000 及以上。 请提供任何帮助。

请您参考如下方法:

稍微更改了我的回复,以便我在回复您的问题的更改版本时输入:https://stackoverflow.com/a/20950887/2393569使用与您在此处提供的代码中相同的名称/...工作:

data = pd.read_csv('meansr.txt', delim_whitespace=True)  
numcols, numrows = 30, 30  
xi = np.linspace(data.Lon.min(), data.Lon.max(), numrows) 
yi = np.linspace(data.Lat.min(), data.Lat.max(), numcols) 
xi, yi = np.meshgrid(xi, yi) 
x, y, z = data.Lon, data.Lat, data.Z 
 
# NOTE: from here on it changes 
points = np.vstack((x,y)).T  
values = z 
wanted = (xi, yi) 
zi = griddata(points, values, wanted) # for more info on griddata: http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.griddata.html 
 
# from here its the same code again as you had 
plt.figure() 
plt.contourf(xi, yi, zi) 
plt.scatter(data.Lon, data.Lat, c=data.Z, s=100, vmin=zi.min(), vmax=zi.max()) 
plt.colorbar() 
plt.show() 

所以您实际遇到的问题是没有完全理解 scipy.interpolate.griddata,而不是真正与 matplotlib 相关的问题。

所以正确的用法是

scipy.interpolate.griddata(points, values, xi, method='linear', fill_value=nan) 
# 'points' has to contain what you named  x and y 
# 'values' has to contain what you named z 
# 'xi' has to contain what you named xi,yi 

你改了之后,画图还麻烦吗?

注意:我假设您的导入是:

import numpy as np 
from scipy.interpolate import griddata 
import pylab as plt 
# i guess the pd.read_csv is something pandas (heard of it, but never used it before, but since the only thing you do is read_csv i guess that wont cause problems) 

如果你在这里提问,最好也提供你的导入,因为我刚刚发现 from matplotlib.mlab import griddata 也存在,并且语法与你使用的相似, 在 Contours with map overlay on irregular grid in python您使用 scipy 中的 griddata,但是您似乎基于后续问题(这个)的答案包含 matplotlib.mlab 导入的 griddata(工作方式不同)。这能解决你的困惑吗?