简体   繁体   English

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

[英]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. 我正在尝试使用APLpy创建多个拟合图像子图,并且希望能够通过for循环创建这些子图,以防止我不得不为N个图多次键入数十个参数。

Using an inelegant brute-force method, for N=2 plots it might go like this: 使用优美的蛮力方法,对于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')

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. 但是我想用for循环替换两组绘图参数,因为许多其他绘图参数都以这种方式控制,并且我想再做几个绘图。 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. 本质上,我需要能够在for循环中修改代码本身。 I can't find how to do this in Python, but if I were doing something similar in .csh, I might write it as eg f"$i".show_grayscale() . 我找不到如何在Python中执行此操作,但是如果我在.csh中执行类似操作,则可能会将其编写为例如f"$i".show_grayscale()

Thanks. 谢谢。

A way to do it is to add your FITSFigure objects into a list: 一种方法是将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))

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

I was shown the way to the solution to this today. 今天向我展示了解决此问题的方法。 The exec() command lets you execute a string of code in exactly this way. exec()命令使您可以完全按照这种方式执行代码字符串。 The solution to this particular case would be to use: 解决此特定情况的方法是使用:

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

The downside here is that the code you write inside the string to be executed does not have the colour-coded formatting that it would normally have. 缺点是您在要执行的字符串中编写的代码没有通常具有的颜色编码格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM