【问题标题】:Using a for loop to make multiple Python APLpy subplots使用 for 循环制作多个 Python APLpy 子图
【发布时间】:2015-06-23 03:44:57
【问题描述】:

我正在尝试使用 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().

谢谢。

【问题讨论】:

    标签: python for-loop subplot aplpy


    【解决方案1】:

    一种方法是将您的 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()
    

    【讨论】:

    • 谢谢 - 这正是我想要的。
    【解决方案2】:

    今天向我展示了解决此问题的方法。 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)')
    

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

    【讨论】:

    • 这是一个非常好的答案,曾经通过电子邮件发送给您的人一定是个聪明人......
    • 我对此投了反对票,因为这是一个糟糕的答案。使用exec 语句和串联代码 sn-ps 编写代码会使代码不可读且难以调试,更不用说速度要慢得多 - 通常exec 不应该成为 Python 代码库的一部分。
    • 你说得对,这是我四年前提出的一个糟糕的解决方案。 FraDega 的回应正是我当时所追求的,尽管我只是在您的评论之后看到了回复。因此,我更改了接受的答案。
    猜你喜欢
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 2023-04-08
    • 1970-01-01
    • 2021-08-02
    • 2021-01-02
    相关资源
    最近更新 更多