使用for循环生成多个Python APLpy子批

使用for循环生成多个Python APLpy子批,python,for-loop,subplot,aplpy,Python,For Loop,Subplot,Aplpy,我正在尝试使用APLpy创建多个子批次的fits图像,我希望能够通过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.FITS

我正在尝试使用APLpy创建多个子批次的fits图像,我希望能够通过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\u 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()

这是一个非常好的答案,曾经给你发过邮件的人一定是个聪明人……我对此投了反对票,因为这是一个糟糕的答案。使用
exec
语句编写代码并连接代码段会使代码不可读且难以调试,更不用说速度会慢得多,而且一般来说
exec
不应该成为Python代码库的一部分。你完全正确,这是我四年前提出的一个糟糕的解决方案。弗拉德加的回答正是我当时想要的,尽管我只是看到了你评论后的回复。因此,我已经改变了被接受的答案。谢谢——这正是我想要的。