Format cursor readout for interactive image plot with WCSAxes

Hello astropyers,

I have just found an nice undocumented(?) feature of WCSAxes running an a jupyter notebook - you can switch the cursor readout between pixel and world coordinate systems by pressing “w”. Very nice! Is there a way to control the format of the values displayed? Currently the RA/Dec are not displayed to sufficient precision for my purposes and the pixel coordinates are displayed with >12 decimal places.

Here is what I am doing so far …

%matplotlib notebook
from astropy.wcs import WCS
from astropy.io import fits
import matplotlib.pyplot as plt
im,hdr = fits.getdata('IMG_0004_2.fits',header=True)
wcs = WCS(hdr)
ax = plt.subplot(projection=wcs)
ax.imshow(im,origin='lower',cmap='Greens')
ax.grid(color='gray', ls='solid')
plt.title('Press w to switch between pixel and sky coords');

Thanks,
-Pierre

1 Like

Answering my own question …


class myWCSAxes(WCSAxes):
   def _display_world_coords(self, x, y):
       if not self._drawn:
           return ""


       pixel = np.array([x, y])

       coords = self._all_coords[self._display_coords_index]

       world = coords._transform.transform(np.array([pixel]))[0]
       radeg = world[0]
       rastr = f"{radeg/15:02.0f}h {60*(radeg/15 % 1):02.0f}m"
       dedeg = world[1]
       destr = f"{dedeg:+02.0f}° {60*(dedeg % 1):02.0f}'"

       return f"{rastr} {destr} ({x:6.1f}, {y:6.1f})"


fig = plt.figure(figsize=(9,6))
ax = myWCSAxes(fig, [0.1,0.1,0.8,0.8], wcs=wcs)
ax.imshow(im, 
         vmin=np.percentile(im,90), 
         vmax=np.percentile(im,99.9), 
         origin='lower',cmap='Greens')
lon = ax.coords[0]
lat = ax.coords[1]
lon.set_ticks_position('lr')
lon.set_ticklabel_position('lr')
lat.set_ticks_position('tb')
lat.set_ticklabel_position('tb')
ax.grid()
ax.set_xlabel('Dec')
ax.set_ylabel('RA')
fig.tight_layout()
fig.add_axes(ax)  # note that the axes have to be explicitly added to the figure

1 Like