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

基于NetCDF4的2D经纬度网格处理与温度等值线绘制需求

解决方案

1. 提取指定Bounding Box内的子网格数据

由于经纬度是2D变量,无法直接通过一维索引筛选,需先创建空间掩码定位目标区域,再提取对应数据。以下是基于netCDF4和numpy的实现:

import numpy as np
from netCDF4 import Dataset

# 读取NetCDF文件
nc_file = Dataset("your_data.nc", "r")
lon = nc_file.variables["lon"][:]  # shape (52, 46)
lat = nc_file.variables["lat"][:]
tdisk = nc_file.variables["TDISK"][:]  # shape (68, 52, 46)

# 定义目标边界框(按需修改)
lon_min, lon_max = 110.0, 120.0
lat_min, lat_max = 25.0, 35.0

# 创建空间掩码:筛选落在边界框内的网格点
mask = np.logical_and(
    np.logical_and(lon >= lon_min, lon <= lon_max),
    np.logical_and(lat >= lat_min, lat <= lat_max)
)

# 提取子网格数据
# 提取所有扫描层的子数据,shape为(68, N),N为符合条件的点数
tdisk_subset = tdisk[:, mask]
# 对应的经纬度子集,shape为(N,)
lon_subset = lon[mask]
lat_subset = lat[mask]

# 若需保留原2D结构(仅当边界框对应连续行列时适用,否则会包含NaN)
tdisk_masked = np.where(mask, tdisk, np.nan)

如果使用xarray,代码会更简洁,原生支持2D坐标筛选:

import xarray as xr

ds = xr.open_dataset("your_data.nc")
ds_subset = ds.where(
    (ds.lon >= lon_min) & (ds.lon <= lon_max) &
    (ds.lat >= lat_min) & (ds.lat <= lat_max),
    drop=False  # drop=True会只保留非NaN点,False保留原网格形状
)

2. 绘制经纬度为坐标轴的温度等值线图

利用matplotlib的contourf函数,直接传入2D经纬度数组作为坐标轴,无需依赖网格索引:

import matplotlib.pyplot as plt

# 选择某一扫描层的数据(示例为第0层)
tdisk_scan = tdisk[0, :, :]

# 绘制完整区域等值线图
plt.figure(figsize=(10, 6))
contour = plt.contourf(lon, lat, tdisk_scan, cmap="viridis", levels=20)
plt.colorbar(contour, label="Temperature (K)")
plt.xlabel("Longitude (°E)")
plt.ylabel("Latitude (°N)")
plt.title("Temperature Contour Map")
plt.grid(True, linestyle="--", alpha=0.7)
plt.show()

# 仅绘制边界框内的区域
plt.figure(figsize=(10, 6))
# 使用之前的掩码将区域外数据设为NaN
tdisk_scan_masked = np.where(mask, tdisk_scan, np.nan)
contour = plt.contourf(lon, lat, tdisk_scan_masked, cmap="viridis", levels=20)
plt.colorbar(contour, label="Temperature (K)")
plt.xlim(lon_min, lon_max)
plt.ylim(lat_min, lat_max)
plt.xlabel("Longitude (°E)")
plt.ylabel("Latitude (°N)")
plt.title("Temperature Contour Map (Bounding Box)")
plt.grid(True, linestyle="--", alpha=0.7)
plt.show()

若使用xarray,绘图可一步完成:

ds_subset.TDISK.isel(nscans=0).plot.contourf(
    x="lon", y="lat", cmap="viridis", levels=20
)
plt.xlim(lon_min, lon_max)
plt.ylim(lat_min, lat_max)
plt.grid(True, linestyle="--", alpha=0.7)
plt.show()

关键说明

  • 2D经纬度无需转换为网格索引,contourf可直接接受2D的X/Y坐标数组。
  • 用掩码筛选数据时,若需保留原网格结构,可将区域外值设为NaN,绘图时会自动忽略这些区域。
  • 若只需提取边界框内的离散点,直接用tdisk[:, mask]即可得到一维化的子数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 22:07:29