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

多NC文件循环绘图时标题不显示问题排查

问题分析与解决

你遇到的标题不显示、绘图逻辑错误主要有以下几个核心问题:

1. 数据存储与时间列表填充错误

  • 第一个循环中,a_foot每次都会被当前文件的foot覆盖,最终仅保留最后一个NC文件的数据,前48个文件的数据全部丢失。
  • 填充Time列表的逻辑完全错误:for num in time:循环里,每次都把**整个时间维度的格式化结果(一个数组)**追加到Time中,导致Time存储的是大量重复数组,而非单个时间字符串,数量也远超出49个。

2. 绘图循环的索引错误

第二个循环for i in Time:中,i是Time里的元素(不是索引值),你用Time[i]取元素会触发索引异常,这是标题无法显示的直接原因——代码在此处抛出错误后,plt.title根本无法正常执行。

3. 绘图逻辑与需求不匹配

你的需求是为49个文件各绘制一幅(时间维度求和后的)足迹图,但当前代码是遍历Time列表元素绘图,完全偏离了「一个文件一幅图」的核心需求。


修正后的代码

import glob
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import xarray as xr

# 获取排序后的NC文件列表
file_list = sorted(glob.glob('*.nc'))

for file in file_list:
    # 打开单个NC文件
    data = xr.open_dataset(file)
    lon = data['lon']
    lat = data['lat']
    time = data['time']
    foot = data['foot']
    
    # 对时间维度求和,得到二维足迹数据
    foot_sum = foot.sum(dim='time')
    
    # 获取该文件对应的时间范围(可根据需求调整为单个时间点)
    time_str = f"{time[0].dt.strftime('%Y-%m-%d %H:%M:%S').item()} 至 {time[-1].dt.strftime('%Y-%m-%d %H:%M:%S').item()}"
    
    # 初始化绘图轴
    ax = plt.axes(projection=ccrs.PlateCarree())
    levels = [0.01, 0.05, 0.1, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50, 0.55, 0.60]
    plt.contourf(lon, lat, foot_sum,
                 levels=levels,
                 colors=['mediumblue', 'deepskyblue', 'aqua', 'lightseagreen', 'mediumseagreen', 'limegreen', 'yellow', 'gold', 'orange', 'darkorange', 'tomato', 'orangered', 'red'],
                 )
    
    # 设置地图范围与样式
    ax.set_extent([-150, -143, 57.5, 72])
    ax.coastlines()
    gls = ax.gridlines(draw_labels=True)
    gls.top_labels = False
    gls.right_labels = False
    
    # 添加色标
    plt.colorbar(label='Footprints, ppm (umol-1 m2 s)', location='right', shrink=0.5, format='%.0e', extend="both")
    # 标记受体位置
    ax.plot(-146.231483, 64.054333, marker='o', markerfacecolor="None", markeredgecolor='black', markersize=6)
    
    # 设置标题(包含位置与时间范围)
    plt.title(f'location, {time_str}')
    plt.show()
    
    # 关闭文件释放资源
    data.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 02:53:16