import numpy as np
# Set up matplotlib and use a nicer set of plot parameters
%config InlineBackend.rc = {}
import matplotlib
matplotlib.rc_file("../../templates/matplotlibrc")
import matplotlib.pyplot as plt
%matplotlib inline
The following line is needed to download the example FITS files used in this tutorial.
from astropy.utils.data import download_file
from astropy.io import fits
FITS files can often contain large amount of multi-dimensional data and tables.
In this particular example, I will open a FITS file from a Chandra observation of the Galactic Center. The file contains a list of events with x and y coordinates, energy, and various other pieces of information.
event_filename = download_file( 'https://github.com/eblur/astropy-data/raw/gh-pages/tutorials/FITS-tables/chandra_events.fits', cache=True )
Since the file is big, I will open with memmap=True to prevent RAM storage issues.
hdu_list = fits.open(event_filename, memmap=True)
hdu_list.info()
I'm interested in reading EVENTS, which contains information about each X-ray photon that hit the detector.
To find out what information the table contains, I will print the column names.
print(hdu_list[1].columns)
Now I'll load the data into a separate variable.
evt_data = hdu_list[1].data
We can extract data from the table by referencing the column name.
For example, I'll make a histogram for the energy of each photon, giving us a sense for the spectrum (folded with the detector's efficiency).
NBINS = 500
energy_hist = plt.hist(evt_data['energy'], NBINS)
I will make an image by binning the x and y coordinates of the events into a 2-D histogram.
x = evt_data['x']
y = evt_data['y']
This particular observation spans five CCD chips. Here I will pick events that only fell on the main (ACIS-I) chips, which have number ids 0, 1, 2, and 3.
ii = np.any([evt_data['ccd_id'] == i for i in [0,1,2,3]], axis=0)
This method allowed me to create an image without stretching
NBINS = (100,100)
img_zero, yedges, xedges = np.histogram2d(evt_data['x'][ii], evt_data['y'][ii], NBINS)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
plt.imshow(img_zero, extent=extent, interpolation='nearest', cmap='gist_yarg', origin='lower')
plt.xlabel('x')
plt.ylabel('y')
# To see more color maps
# http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps
from matplotlib.colors import LogNorm
NBINS = (100,100)
img_zero_mpl = plt.hist2d(evt_data['x'][ii], evt_data['y'][ii], NBINS, cmap='jet', norm=LogNorm())
cbar = plt.colorbar(ticks=[1.0,3.0,6.0])
cbar.ax.set_yticklabels(['1','3','6'])
plt.xlabel('x')
plt.ylabel('y')
hdu_list.close()
Make a scatter plot of the same data you histogrammed above. The plt.scatter function is your friend for this. What are the pros and cons of doing this?
Try the same with the plt.hexbin plotting function. Which do you think looks better for this kind of data?