从几何坐标获取投影坐标

时间:2019-05-06 03:12:40

标签: matplotlib cartopy

我有一个用Cartopy和Matplotlib渲染的地图。我有一个特定的几何坐标(以纬度/经度为单位),我想知道最接近该几何坐标的投影(如果可见)的像素坐标,例如在地图上的坐标上绘制图形。

(请注意,我不想使用Matplotlib绘制;我要将图形导出为位图图像并在管道的其他部分进行绘制。)

This documentation建议可能是这样的:

import cartopy, matplotlib.pyplot

fig = matplotlib.pyplot.figure()
ax = fig.add_axes([0, 0, 1, 1], projection=cartopy.crs.Orthographic())
ax.add_feature(cartopy.feature.LAND, facecolor='black')

# Print the location of New York City in display coordinates
lon, lat = -74.0060, 40.7128
trans = cartopy.crs.Geodetic()._as_mpl_transform(ax)
x, y = trans.transform((lon, lat))
print(x, y)

# Or this way
projx, projy = ax.projection.transform_point(lon, lat, cartopy.crs.Geodetic())
x, y = ax.transData.transform((projx, projy))
print(x, y)

尽管有趣的是,如果我绘制此点,图形将居中并放大到曼哈顿,然后输出显示坐标的确在图形的中心(640,480)。

matplotlib.pyplot.plot(lon, lat, marker='o', color='red', markersize=12,
    alpha=0.7, transform=cartopy.crs.Geodetic())

2 个答案:

答案 0 :(得分:1)

我刚刚发现,在图形处于最终状态之前,转换设置不正确。因此,关键是首先绘制图形

fig.canvas.draw()

或至少正确应用方面。

ax.apply_aspect()

然后您将获得正确的像素坐标,

import matplotlib.pyplot as plt
import cartopy
import cartopy.crs as ccrs

fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1], projection=ccrs.PlateCarree())
ax.add_feature(cartopy.feature.LAND, facecolor='black')
ax.set_global()

# before being able to call any of the transforms, the figure needs to be drawn
fig.canvas.draw()
# or
# ax.apply_aspect()

# Print the location of New York City in display coordinates
lon, lat = -74.0060, 40.7128
trans = ccrs.PlateCarree()._as_mpl_transform(ax)
x, y = trans.transform_point((lon, lat))
print(x,y)

plt.show()

此打印:

188.43377777777778 312.3783111111111

请注意,这些坐标是指左下角的像素。

答案 1 :(得分:0)

在我的示例代码中,我未能指定地图的范围。如果我添加

ax.set_global()

然后变换的坐标才有意义。

我提出了两种方法来计算转换后的坐标,但是当看不见纽约市时,使用_as_mpl_transform()的方法似乎返回了中心点。 ax.projection.transform_point()的方式在屏幕外时会返回NaN。