When I use a xarray dataset created from a pandas DataFrame, rather than pygmt.xyz2grd()
, the x and y dimensions (lon and lat) are switched when I try to plot them (pygmt.grdview) or get the range (pygmt.grdinfo). I have the xarray already so I’d rather not convert back to a DataFrame to use pygmt.xyz2grd() if possible.
df = pd.DataFrame({"lon": [-70.2, -70.1, -70, -70.2, -70.1, -70, -70.2, -70.1, -70],
"lat": [19.0, 19.0, 19.0, 19.1, 19.1, 19.1, 19.2, 19.2, 19.2],
"depth": [1.1, 2.1, 3.1, 1.2, 2.2, 3.2, 1.3, 2.3, 3.3]}).set_index(["lon", "lat"])
# I have a number of variables in a xarray.DataSet, e.g.:
ds = df.to_xarray().sortby("lon", "lat")
ds["depth_10"] = ds["depth"] * 10
# depth DataArray
da = ds["depth"]
# DataArray from xyz2grd
da_gmt = pygmt.xyz2grd(df.reset_index(), spacing=0.1, region=[-70.2, -70, 19, 19.2])
# DataArray to DataFrame back to DataArray <- I'd like to avoid this
da_to_df_to_da_gmt = pygmt.xyz2grd(da.to_dataframe().reset_index(), spacing=0.1, region=[-70.2, -70, 19, 19.2])
# I've also tried renaming lon, lat to x, y
da_xy = da.rename({"lon": "x", "lat": "y"}) #["depth"]
print(f"grdinfo on da: {pygmt.grdinfo(da, spacing=0.1)}", end="")
print(f"grdinfo on da_xy: {pygmt.grdinfo(da_xy, spacing=0.1)}", end="")
print(f"grdinfo on da_gmt: {pygmt.grdinfo(da_gmt, spacing=0.1)}", end="")
print(f"grdinfo on da_to_df_to_da_gmt: {pygmt.grdinfo(da_to_df_to_da_gmt, spacing=0.1)}", end="")
Output:
grdinfo on da: -R19/19.2/-70.2/-70
grdinfo on da_xy: -R19/19.2/-70.2/-70
grdinfo on da_gmt: -R-70.2/-70/19/19.2
grdinfo on da_to_df_to_da_gmt: -R-70.2/-70/19/19.2
pygmt.grdinfo
(and grdimage, grdview) are swapping my longitude and latitude (or x and y). Instead of converting my DataArrays back to DataFrames to use pygmt.xyz2grd()
, is there a way to use the original xarray DataSet/DataArray directly?
Thank you,
Jason
(abbreviated) PyGMT information:
- version: v0.14.2
- python: 3.13.2 | packaged by conda-forge | …
- machine: macOS-14.7.4-arm64-arm-64bit-Mach-O
- numpy: 2.2.4
- pandas: 2.2.3
- xarray: 2024.11.0
- netCDF4: 1.7.2
- version: 6.5.0