使用 for 循环制作多个 Python APLpy 子图

Using a for loop to make multiple Python APLpy subplots

我正在尝试使用 APLpy 创建拟合图像的多个子图,我希望能够通过 for 循环创建这些子图,以防止我不得不为 N 个图多次输入几十个参数。

使用不雅的蛮力方法,对于 N=2 个图,它可能是这样的:

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')

但我想用for循环替换两组绘图参数,因为许多其他绘图参数都是用这种方式控制的,我想再画几幅。我想用类似的东西替换这些行:

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

等等

显然这个语法是错误的。本质上,我需要能够在 for 循环中修改代码本身。我在 Python 中找不到如何做到这一点,但如果我在 .csh 中做类似的事情,我可能会把它写成例如f"$i".show_grayscale().

谢谢。

今天有人向我展示了解决此问题的方法。 exec() 命令可以让您以这种方式执行一串代码。这种特殊情况的解决方案是使用:

for i in range(1,3):
    exec('f' + str(i) + '.show_grayscale()')
    exec('f' + str(i) + '.add_colorbar()')
    exec('f' + str(i) + '.frame.set_linewidth(0.75)')

这里的缺点是您在要执行的字符串中编写的代码没有通常具有的颜色编码格式。

一种方法是将 FITSFigure 对象添加到列表中:

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))

然后你可以用一个正常的迭代:

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