4D surface plot from NetCDF data

417 views Asked by At

I am trying to plot a 4D surface plot of netcdf data (attached file). It has 4 dimensions: lat, long, lev, and the value-dust mixing ratio (5 values DU01, DU02...05). As I am very much new to Python, I don't know about it much. I have to plot DU01 (which will be the fill value) vs lat, long, and levels. Sample plot what I need is sample plot.

Any help would be very much helpful and appreciated.

I am getting this error

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[59], line 9
      7 fig = plt.figure(figsize=(12, 8))
      8 ax = fig.add_subplot(111, projection='3d')
----> 9 ax.plot_surface(lon_3d, lat_3d, lev_3d, facecolors=plt.cm.jet(DMR/np.nanmax(DMR)), rstride=1, cstride=1, edgecolor='none', alpha=.8)
     10 ax.set_title('DU01 dust mixing ratio')
     11 ax.set_xlabel('Longitude')

File C:\ProgramData\anaconda3\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py:1381, in Axes3D.plot_surface(self, X, Y, Z, norm, vmin, vmax, lightsource, **kwargs)
   1378 had_data = self.has_data()
   1380 if Z.ndim != 2:
-> 1381     raise ValueError("Argument Z must be 2-dimensional.")
   1383 Z = cbook._to_unmasked_float_array(Z)
   1384 X, Y, Z = np.broadcast_arrays(X, Y, Z)

ValueError: Argument Z must be 2-dimensional.
1

There are 1 answers

5
MSS On

This code creates 3D surface plot of the data for DU01 mixing ratio value.

import xarray as xr
import plotly.graph_objs as go

# Load the netcdf file into an xarray dataset
ds = xr.open_dataset('your_file.nc')

# Select the DU01 variable and the lat, long, and lev dimensions
du01 = ds['value-dust_mixing_ratio'].sel(value='DU01')
lat = ds['lat'][:]
lon = ds['lon'][:]
lev = ds['lev'][:]

# Create a 3D meshgrid of the lat, long, and lev coordinates
lon_3d, lat_3d, lev_3d = np.meshgrid(lon, lat, lev, indexing='ij')

# Create the plotly figure object
fig = go.Figure(data=[go.Surface(z=lev_3d, x=lon_3d, y=lat_3d, surfacecolor=du01, colorscale='Jet')])

# Customize the layout
fig.update_layout(title='DU01 Dust Mixing Ratio',
                  scene=dict(xaxis_title='Longitude', yaxis_title='Latitude', zaxis_title='Level'))

# Show the plot
fig.show()