1

Suppose I have a rather large NetCDF file that I open as a dataset using xarray.

import xarray

nc_in = r"....\D_P_WGS84_comp.nc"
nc_ds = xarray.open_dataset(nc_in)

It is composed of multiple raster variables, each with a single band, x, y coordinates and a crs (4326):

nc_ds

enter image description here

Suppose I want to visualize this very simply in my Python Notebook. I don't really want to add basemaps or legends or anything like that. I tried simply running show(nc_ds) but throws an errors AttributeError: 'Dataset' object has no attribute 'shape'`. I also noticed that the dimensions are frozen. What is the simplest way to visualize this dataset or a single variable of it in Python? Is there a mod or package extension that would do this?

3
  • 1
    Pretty sure you will need to select a DataArray from the DataSet, does show(nc_ds.data_vars['F02_NBR_E0002']) work? Commented Oct 23, 2020 at 19:40
  • It does! Thats exactly what I was looking for!
    – gwydion93
    Commented Oct 23, 2020 at 19:47
  • 1
    Sweet! Thanks for making me learn xarray today 😃 Commented Oct 23, 2020 at 20:24

1 Answer 1

2

Since a Dataset can contain more than one variable, it would not be trivial for software to know what you want it to display. If you select one of its variables as DataArray however, that can easily be displayed (if it is in an appropriate format).

The variables of a Dataset are available via its data_vars attribute. This exposes the variables as DataArrays in a dict with the variable names as keys.

Step by step:

variables = nc_ds.data_vars
f02_nbr_e0002 = variables['F02_NBR_E0002']
show(f02_nbr_e0002)

Efficient oneliner:

show(nc_ds.data_vars['F02_NBR_E0002'])
1
  • Thanks. I am somewhat new to working with xarray and rasters in this way and accessing the array in the data set to visualize it didn't occur to me (although originally, I had used .open_rasterio to turn the original tifs into a data array and visualize them). The 1-liner is great!
    – gwydion93
    Commented Oct 25, 2020 at 16:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.