Just another option using PyGMT which integrates with pandas and xarray. There’s a suite of options to do gridding like nearneighbor, sphinterpolate, surface, triangulate and xyz2grd (depending on whether you want to grid things in Cartesian or Geographic space). I’ll just show the Delaunay Triangulation one as an example here.
- Turn longitude/latitude/n data into an
xarray.DataArray grid
import pandas as pd
import pygmt
import xarray as xr
# Ordinary Dataframe
df = pd.read_csv("https://minio.carlboettiger.info/shared-data/gbif.csv")
print(df.head())
# longitude latitude n
# 0 12.3 50.6 711
# 1 176.5 -38.3 159
# 2 -102.1 19.9 168
# 3 -88.1 21.2 77
# 4 43.1 53.7 11
# Turn XYZ data into 2D grid using Delaunay triangulation
dataarray: xr.DataArray = pygmt.triangulate.regular_grid(
x=df.longitude,
y=df.latitude,
z=df.n,
region="d", # global region from longitude -180 to +180
spacing="1d", # 1 arc degree grid spacing
)
# <xarray.DataArray 'z' (lat: 181, lon: 361)>
# array([[ nan, nan, nan, ..., nan,
# nan, nan],
# [ 2.9224806, 2.5833333, 2.6 , ..., nan,
# nan, 2.9224806],
# [ 2.8449612, 2.366853 , 2.1666667, ..., nan,
# nan, 2.8449612],
# ...,
# [ nan, 130.36208 , 113.53846 , ..., 21.555555 ,
# 17.713467 , nan],
# [ nan, 160.12338 , 149.14935 , ..., 1.5172414,
# 10.296875 , nan],
# [ nan, nan, nan, ..., nan,
# nan, nan]], dtype=float32)
# Coordinates:
# * lon (lon) float64 -180.0 -179.0 -178.0 -177.0 ... 178.0 179.0 180.0
# * lat (lat) float64 -90.0 -89.0 -88.0 -87.0 -86.0 ... 87.0 88.0 89.0 90.0
# Attributes:
# long_name: z
# actual_range: [1.000e+00 4.052e+03]
- Plot the gridded data with coastlines for extra context.
fig = pygmt.Figure()
fig.grdimage(grid=dataarray, frame=True, cmap="SCM/lajolla")
fig.coast(shorelines="thinnest")
fig.colorbar(frame=["x+ln", "y+lunits"])
fig.show()