You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的imshow和色条绘制10个FITS文件?现有代码仅显示单张

问题分析与解决

你的代码仅显示单张图像的原因如下:

  • plt.imshow()默认会在同一个绘图窗口/坐标轴上覆盖绘制新图像,最终仅保留最后一次绘制的结果
  • 未调用plt.show()触发图像显示(交互式环境可能会显示,但覆盖问题依然存在)
  • 额外说明:with fits.open(location) as image:会自动管理文件关闭,手动调用image.close()属于冗余操作,可直接删除

解决方案1:每张图单独创建窗口

在循环内创建新绘图窗口,让每张图像独立显示:

import glob
from astropy.io import fits
import matplotlib.pyplot as plt

f_name = sorted(glob.glob('/home/citlali/img_servicio/*.fits'))

for idx, location in enumerate(f_name):
    with fits.open(location) as image:
        DATOS = image["FLUX_ELINES"].data
        img = DATOS[45, :, :]
        
        # 创建新绘图窗口
        plt.figure()
        plt.imshow(img)
        # 添加标题区分不同文件
        plt.title(f"第{idx+1}张图:{location.split('/')[-1]}")

# 显示所有图像窗口
plt.show()

解决方案2:所有图排列在同一窗口的子图中

适合图像数量不多的场景(比如你的10张),将图像规整排列:

import glob
from astropy.io import fits
import matplotlib.pyplot as plt

f_name = sorted(glob.glob('/home/citlali/img_servicio/*.fits'))
total_files = len(f_name)
# 设置3行4列的子图网格(可容纳12张,适配10张的需求)
rows, cols = 3, 4

fig, axes = plt.subplots(rows, cols, figsize=(15, 10))
axes = axes.flatten()  # 转一维数组方便循环遍历

for idx, location in enumerate(f_name):
    with fits.open(location) as image:
        DATOS = image["FLUX_ELINES"].data
        img = DATOS[45, :, :]
        
        axes[idx].imshow(img)
        axes[idx].set_title(f"第{idx+1}张图\n{location.split('/')[-1]}", fontsize=8)
        axes[idx].axis('off')  # 关闭坐标轴优化显示

# 隐藏多余的空白子图
for idx in range(total_files, rows*cols):
    axes[idx].axis('off')

plt.tight_layout()
plt.show()

内容的提问来源于stack exchange,提问作者Hache 99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 09:36:26