You can't "save contours as a FITS file" directly, but there are other approaches you can try.
You can use the matplotlib._cntr
tool as described here: Python: find contour lines from matplotlib.pyplot.contour() to get the endpoints in figure coordinates, then use the WCS to convert between pixel and world coordinates. aplpy.FITSFigure
s have convenience functions, F.world2pixel
and F.pixel2world
, which each accept 2 arrays:
F.pixel2world(arange(5),arange(5))
So if you are working with a grid that is identical to that shown in the FITSFigure
window, you could convert your points to world coordinates and plot them with show_lines
:
ra,dec = F.pixel2world(xpix,ypix)
F.show_lines([[ra,dec]])
or for a more realistic contour case, now copying the code from the linked article:
import numpy as np
import aplpy
def get_contour_verts(cn):
contours = []
# for each contour line
for cc in cn.collections:
paths = []
# for each separate section of the contour line
for pp in cc.get_paths():
xy = []
# for each segment of that section
for vv in pp.iter_segments():
xy.append(vv[0])
paths.append(np.vstack(xy))
contours.append(paths)
return contours
# This line is copied from the question's code, and assumes that has been run previously
CS = plt.contour(Xgrid, Ygrid, Hsmooth,levels=loglvl,extent=extent,norm=LogNorm())
contours = get_contour_verts(CS) # use the linked code
gc = aplpy.FITSFigure('2MASS.fits',figsize=(10,9))
# each level comes with a different set of vertices, so you have to loop over them
for contours_at_level in Contour_arrays:
clines = [cl.T for cl in contours_at_level]
img.show_lines(clines,color='red', zorder=100)
Still the simplest approach is, if you have a FITS file from which you're generating said contours, just use that file directly. Or if you don't have a FITS file, you can make one with pyfits by creating your own header.