简体   繁体   中英

How to convert display coordinates to geographoc coordinates (lat, lon) using cartopy?

I would like to get the latitude and longitude of a data point, given its pixel coordinates. I am quite confused with matplotlib transformations, but I guess that the key for solving the issue is here.

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

MIN_LAT = 5
MAX_LAT = 70
MIN_LON = -100
MAX_LON = 23

# Map

fig = plt.figure(figsize=(12,7))
proj = ccrs.PlateCarree(central_longitude=0)  

ax=plt.axes(projection=proj)

ax.add_feature(cfeature.LAND, color='lightgray')
ax.add_feature(cfeature.OCEAN)

# Select area
ax.set_extent([MIN_LON, MAX_LON, MIN_LAT, MAX_LAT], crs=proj)

fig.canvas.draw()

在此处输入图片说明

For example, given pixel coordinate (0, 0) (bottom left corner in matplotlib), I expect to return geographic coordinates (MIN_LON, MIN_LAT).

In the PlateCarree projection, X and Y map linearly to longitude and latitude. So, assuming you know the width and height of the bitmap:

longitude = MIN_LON + x * (MAX_LON-MIN_LON) / width
latitude = MIN_LAT + y * (MAX_LAT-MIN_LAT) / height

You can use the inverse of the data transformation that converts from display coordinates (pixels) to data coordinates :

ax.transData.inverted().transform((x_pixel, y_pixel))

Please keep in mind, however, that the display window (figure) usually shows some margins around your image, so 0,0 is the bottom left corner of the figure, not the axes!

The interactive backends use this transformation to show the data coords of the current cursor position in the top right corner:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM