Search code examples
pythonfor-loopsubplotaplpy

Using a for loop to make multiple Python APLpy subplots


I'm trying to create multiple subplots of fits images using APLpy, and I'd like to be able create these through a for loop to prevent me having to type out dozens of parameters multiple times for N plots.

Using an inelegant brute-force method, for N=2 plots it might go like this:

import aplpy
import matplotlib.pyplot as plt

fig = plt.figure()
f1 = aplpy.FITSFigure("figure1.fits", figure=fig, subplot=[0,0,0.5,0.5])
f2 = aplpy.FITSFigure("figure2.fits", figure=fig, subplot=[0.5,0.5,0.5,0.5])
# And there are many more images at this point, but let's look at 2 for now.

f1.show_colorscale()
f1.add_colorbar()
f1.frame.set_linewidth(0.75)
# And many more settings would follow

# Repeat this all again for the second plot
f2.show_colorscale()
f2.add_colorbar()
f2.frame.set_linewidth(0.75)

fig.canvas.draw()
fig.savefig('figure.eps')

But I'd like to replace the two sets of plot parameters with a for loop since many of the other plot parameters are controlled in this way and I'd like to do several more plots. I'd like to replace those lines with something like:

for i in range(1,3):
    f{i}.show_grayscale()
    f{i}.add_colorbar()
    f{i}.frame.set_linewidth(0.75)

etc.

Obviously this syntax is wrong. Essentially I need to be able to modify the code itself in the for loop. I can't find how to do this in Python, but if I were doing something similar in .csh, I might write it as e.g. f"$i".show_grayscale().

Thanks.


Solution

  • A way to do it is to add your FITSFigure objects into a list:

    fig = plt.figure(figsize=(8,10))
    gc = []
    gc.append(aplpy.FITSFigure(img1, subplot=[0.05,0.05,0.9,0.3], figure=fig))
    gc.append(aplpy.FITSFigure(img2, subplot=[0.05,0.35,0.9,0.3], figure=fig))
    

    then you can iterate with a normal for:

    for i in xrange(len(gc)):
      gc[i].recenter(ra, dec, radius=0.5)
      gc[i].tick_labels.hide()
      gc[i].axis_labels.hide()