numpy 使用.nc文件的4D等高线图

ezykj2lf  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(159)

我试图从netcdf数据中绘制一个4D表面图,它有4个维度:5个变量(DU001、DU002...005)的time、lat、long和lev(sample data)。我必须绘制第一个变量DU001与纬度、长度和水平(72个水平)的关系图,这样x轴是纬度,y轴是长度,z轴是水平,DU001将用颜色表示。到目前为止,我已经尝试了下面的代码,但我只得到一个表面在我的阴谋


我认为这只是一个层面。如何纠正?

import xarray as xr
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from matplotlib import cm
path= 'D:\\DATA\\2015\\test_data'# Open the NetCDF file
data = xr.open_dataset('D:\\DATA\\2015\\test_data\\MERRA2_400.inst3_3d_aer_Nv.20150515.SUB.nc')
# Select the DU01 variable and the lat, long, and lev dimensions
lat = data['lat']
lon = data['lon']
lev = data['lev']
DMR = data['DU001'] 
# Reshape the data
du001_2d = DMR[:, :, :].squeeze()
dmr_values = du001_2d.values.squeeze()
# Create meshgrid for coordinates
lon_2d, lat_2d = np.meshgrid(lon, lat)
# Create the 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plot the surface for each level
for i, level in enumerate(lev):
    ax.plot_surface(lon_2d, lat_2d, dmr_values[i], cmap='viridis')
    # Set labels and title
    ax.set_xlabel('Longitude')
    ax.set_ylabel('Latitude')
    ax.set_zlabel('Level')
    ax.set_title('3D Plot of Dust Mixing Ratio')

    # Set the z-limits based on the valid range of the lev array
    ax.set_zlim(lev[0], lev[71])  # Assuming lev is a 1D array

# Display the plot
plt.show()

我不知道我哪里做错了。我对Python还是个新手。任何帮助都将不胜感激

我尝试绘制的示例是

guykilcj

guykilcj1#

你把所有的dmr_values一个标在另一个上,即你看到的只是dmr_values[-1]。层的最大高度约为6e-8,这就是为什么当使用0 - 72的z轴范围时,它只显示为一个平面。
如果你想绘制72个彩色图层,你需要提供72个平面并自己给它们上色:

ax.plot_surface(lon_2d,
                lat_2d,
                np.full_like(lat_2d, level),
                facecolors=cm.ScalarMappable(cmap='viridis').to_rgba(dmr_values[i]),
                shade=False)

**更新以下注解:**如果要进行插值,可以为3个可见表面使用3个填充等高线图:

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr

path = 'MERRA2_400.inst3_3d_aer_Nv.20150515.SUB.nc'
data = xr.open_dataset(path)

lat = data['lat']
lon = data['lon']
lev = data['lev']
DMR = data['DU001']

fig, ax = plt.subplots(subplot_kw=dict(projection="3d"))

x, y, z = np.meshgrid(lon, lat, lev, indexing='ij')

du = np.swapaxes(DMR[:, :, :].squeeze().values, 0, -1)
kw = {
    'vmin': du.min(),
    'vmax': du.max(),
    'levels': np.linspace(du.min(), du.max(), 20),
}

_ = ax.contourf(
    x[:, :, 0], y[:, :, 0], du[:, :, -1],
    zdir='z', offset=z.max(), **kw
)

_ = ax.contourf(
    x[:, 0, :], du[:, 0, :], z[:, 0, :],
    zdir='y', offset=y.min(), **kw
)

c = ax.contourf(
    du[-1, :, :], y[0, :, :], z[0, :, :],
    zdir='x', offset=x.max(), **kw
)

xmin, xmax = x.min(), x.max()
ymin, ymax = y.min(), y.max()
zmin, zmax = z.min(), z.max()
ax.set(xlim=[xmin, xmax], ylim=[ymin, ymax], zlim=[zmin, zmax],
       xlabel='Longitude', ylabel='Latitude', zlabel='Level')
fig.colorbar(c, ax=ax, shrink=0.7)

相关问题