Search code examples
pythonmatplotlibcartopy

Cartopy: Convert point from axes coordinates to lat/lon coordinates


I am working on a map plot with Cartopy (TransverseMercator projection). I have a point in axes coordinates (p_a = (0.1, 0.9)) and I need its lat/lon coordinates (i.e., those in PlateCarree projection). How can I achieve this?


Solution

  • For this you need to transform the point from axes coordinates to display coordinates, then to data coordinates, and finally to lat/ lon coordinates. Thus you need transformations from matplotlib and cartopy.

    The point p_a = (0.1, 0.9) seems to be outside of valid lat/ lon coordinates (for the default ccrs.TransverseMercator()). Therefore I use p_a = (0.6, 0.6)

    import cartopy.crs as ccrs
    import matplotlib.pyplot as plt
    
    proj = ccrs.TransverseMercator()
    proj_cart = ccrs.PlateCarree() 
    
    f, ax = plt.subplots(subplot_kw=dict(projection=proj))
    ax.coastlines()
    
    # define point
    p_a = (0.6, 0.6)
    
    # plot point in Axes coordinates
    ax.plot(*p_a, transform=ax.transAxes, marker='o', ms=10)
    
    # convert from Axes coordinates to display coordinates
    p_a_disp = ax.transAxes.transform(p_a)
    
    # convert from display coordinates to data coordinates
    p_a_data = ax.transData.inverted().transform(p_a_disp)
    
    # convert from data to cartesian coordinates
    p_a_cart = proj_cart.transform_point(*p_a_data, src_crs=proj)
    
    # make sure we are correct
    ax.plot(*p_a_cart, transform=proj_cart, marker='x', ms=10)
    
    

    This yields the following figure:

    original and transformed point