Reputation: 717
I have an xarray object containing MODIS data imported from HDF4 format. The structure of the DataSet is something like the structure below where I have spectral bands in an array format stored within a Data Variable - each band is a different variable.
# Create example DataSet with 5 variables (let's pretend each layer is a band)
ds = xr.Dataset(
{var: (("band", "x", "y"), np.random.rand(1, 10, 10)) for var in "abcde"}
)
If the bands were stored in an array, it would be easy to explore the data and plot each band using .plot and the built in facet grid tools. However in this case i have to plot each layer individually or using a loop. Is there a quick way to automate grabbing say x number of those variables or bands (maybe b,c and e as an example) and plotting them?
In some cases you may need to plot an RGB image - so i'd do something like this:
# This is one way of combining several bands into a single array object however it's very
# manual. I need to specify each band in the concat statement. But it does achieve
# the output that I want using a manual approach.
new_object = xr.concat([ds.b,
ds.c],
ds.e,
dim="band")
# Now I can plot the data
new_object.imshow.plot()
My goal is to automate the process of selecting x bands (or x number of data variables) for both plotting / visualization and analysis. I don't want to hard code each band into a concat()
function as I did above. In the example above i wanted to plot an RGB image. In other examples i'd want visually explore each band before addition processing OR just extract a few bands for other types of calculations & analysis.
Thank you for any direction!!
Upvotes: 1
Views: 402
Reputation: 2097
I think xarray.Dataset.to_array()
may be what you are looking for. For example for the RGB image I think something like the following would work:
ds.squeeze("band").to_array(dim="band").sel(band=["b", "c", "e"]).plot.imshow()
You could also facet over the "band"
dimension in that case:
ds.squeeze("band").to_array(dim="band").plot(col="band")
Upvotes: 2