emax
emax

Reputation: 7245

How to plot geotiff files with xarray?

I have downloaded some data from Google Earth Engine. The data looks like the following:

import xarray as xr
da = xr.open_rasterio('myFile.tiff')

da

enter image description here

I can show the image but I would like to avoid to consider values that are equal to zero.

f,ax = plt.subplots()
da.plot(ax=ax, cmap='hot_r')

enter image description here

Upvotes: 1

Views: 1855

Answers (1)

Val
Val

Reputation: 7023

xarray has a quite extensive matplotlib backend, check the documentation on the different plotting options.

To answer your question, you can use the plot.imshow method of your DataArray to visualize your raster (there you can also pass keywords for colormap, range, colorbar, etc. ...).

To exclude values equal (or equal and below) 0, just run where before plotting, to set all values which don't comply to the specified condition to Nan and therefore exclude for plotting. Be aware that this will change the datatype.

One final thing, plot.imshow expects a 2d array, and your dataset seems to have a 3rd dimension band that has only one 'layer'. You can easily drop that with squeeze, either before where or plot.imshow.

Here's an example:

import xarray as xr

# test data
ds = xr.tutorial.load_dataset("rasm")

# replicate 3d data array
da = ds.isel(time=0).Tair.expand_dims({"band":1})

# exclude vals below or equal to 0, squeeze to 2d and plot
da.where(da>=0).squeeze().plot.imshow(cmap="hot_r")

enter image description here

Upvotes: 2

Related Questions