Getting Started with Astropy

Beyza Ulasti
2 min readMar 6, 2023

--

Why

Astropy is a community-developed python package worth exploring if you are interested in astronomy-adjacent fields. As expected, the package is able to handle FITS files with ease. Even if you don’t have any experience with Astropy, this is an easy tutorial to follow.

Getting Started

The first thing you want to do is make sure you have installed and imported the required packages. For the purposes of this tutorial, you will need pandas, matplotlib, and astropy.

#installing astropy
pip install astropy
#importing packages
import pandas as pd
import matplotlib.pyplot as plt
from astropy.io import fits
from astropy.visualization import astropy_mpl_style

The Dataset

NASA is an excellent data source. There are plenty of datasets you can play around with. For this tutorial, I picked a sample they provided under FITS files. You can find more elaborate datasets here. Once you download the sample, you can open it in python.

hdul = fits.open('rosat.fits')

HDUL in astropy refers to a FITS file containing one or more Header-Data Units (HDU).

Exploring the data

You can skip this step, but I like to look at the data before visualizing it.

#looking at the file we opened
hdul.info()

#Output:
Filename: rosat.fits
No. Name Ver Type Cards Dimensions Format
0 PRIMARY 1 PrimaryHDU 80 (512, 512) int16 (rescales to float32)

#We can also print the header, since it is a Header-Data Unit
print(hdul[0].header)

Visualizing the data

Finally, we can visualize the sample and see what it actually holds.

# Get the data and header from the first HDU
data = hdul[0].data
header = hdul[0].header

# Use Astropy's default style for Matplotlib
plt.style.use(astropy_mpl_style)

# Create a 2D image plot of the data
fig, ax = plt.subplots()
im = ax.imshow(data, cmap='viridis')

# Add a colorbar
cbar = fig.colorbar(im)

# Show the plot
plt.show()

Here is what that looks like:

Now you can find entire datasets, or another FITS file sample, and explore what is inside. As fun as exploring random image files are, astropy is capable of handling much more. You can read the documentation and try it out yourself!

--

--