title: How to convert pixel to wavelength in spectra from FITS files in Python?
body: <p>I've been using matplotlib.pyplot to plot a spectrum from fits files in Python and getting the intensity versus pixel, but what I actually need is to convert the pixels to wavelength. I've seen similar questions that got me in the right path of what I need to do (e.g. <a href="https://stackoverflow.com/questions/46910765/how-to-plot-graph-the-intensity-versus-wavelength-for-the-spectrum">similar question</a>,<a href="https://stackoverflow.com/questions/35481345/convert-rgb-pixel-to-wavelength" title="RGB example">RGB example</a>) but  I still feel lost in the process.</p>
  
  <p>I have FITS files with wavelengths around 3500 and 6000 (A), in float32 format and dimensions (53165,).</p>
  
  <p>So as I understand, I need to calibrate the pixel positions to wavelength. I have my rest wavelength header (RESW), my "step" wavelength header (STW) and I would need to get:</p>
  
  <p><strong>x = RESW + (number of pixels * STW)</strong></p>
  
  <p>and the plot it. Here is what I got in my code so far.</p>
  
  <pre><code>import os, glob
  from glob import glob
  from pylab import *
  from astropy.io import ascii
  import scipy.constants as constants
  import matplotlib.pylab as plt
  from astropy.io import fits
  
  #add directory you have your files in
  dir = '' 
  
  
  #OPEN ALL FILES AND STORE THEM INTO A LIST
  files= glob(dir + '*.fits')
  for fi in (files):
      print(fi)
      name = fi[:-len('.fits')] #Remove '.fits' from the file name
  
      with fits.open(dir + fi) as hdu:
          hdu.info()
          data = hdu[0].data
          hdr = hdu[0].header #added to try2
          step = hdr['CDELT1'] #added to try2
          restw = hdr['CRVAL1'] #added to try2
          #step = fits.getheader('STW') #added to try
          #restw = fits.getheader('RESW') #added to try
          spectra = restw + (data * step) #added to try
  
  plt.clf()
  plt.plot(spectra)
  plt.savefig(name + '.pdf')     
  </code></pre>
  
  <p>I've tried using fits.getheader('') but I don't know where or how to put it because this way is not working right.</p>
  
  <p>Could someone please help? Thanks in advance!</p>