I am reading in a raster file using rioxarray. However, when I try to plot it using grdimage, I get the error: pygmt.exceptions.GMTInvalidInput: Unrecognized data type for grid: <class 'numpy.ndarray'>. How can I fix it? Here is my code:
If you are trying to plot an image rather than a 2D grid, you currently need to provide a file path. The PyGMT team is working on improved support for images loaded as objects in Python (e.g., https://github.com/GenericMappingTools/pygmt/issues/1555).
Thank you, that direct usage of tif file does work great! However, my work case typically involves a raster that has been already been read in and maybe some values altered. I am trying a workaround where I write the raster object into a temporary file on disk using the tempfile library in Python. However, I am have not been able to get that working yet. Do you have a workaround solution for raster objects? Thanks again for some excellent work on this package.
Well, it depends on what you’re trying to plot I guess. Is there a reason you’re using fig.grdimage(grid=grid.data, ...) instead of just fig.grdimage(grid=grid)?
The thing is, PyGMT/GMT’s grdimage function requires coordinates in order to know how to label the x-axis and y-axis. These coordinates don’t exist in a numpy.ndarray since it is purely an array of numbers.
What you could try is to put a numpy.ndarray into an xarray.DataArray (i.e. have the coordinates included) following Data Structures. Something like this:
Thank you! Your solution works great! I used grid.data because when I use just grid I get the following error: ValueError: different number of dimensions on data and dims: 3 vs 2
Hmm, that error message looks strange. Could you post the output of print(grid) so that we can see what the original dimensions and data shape of the GeoTiff look like? I found a similar issue at https://github.com/pydata/xarray/issues/3437 but it didn’t seem very helpful.
Ah ok, you could try using plotting grid.isel(band=1) instead of grid.data perhaps. That should drop the band dimension and you wouldn’t need to do the extra steps I mentioned above.