我正在尝试使用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_grayscale()。
谢谢。
发布于 2015-10-23 18:15:40
这样做的一种方法是将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()发布于 2015-04-17 14:31:34
今天向我介绍了解决这一问题的方法。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)')这里的缺点是,您在要执行的字符串中编写的代码不具有通常使用的颜色编码格式。
https://stackoverflow.com/questions/29679743
复制相似问题