Skip to content

Instantly share code, notes, and snippets.

@spestana
Created December 2, 2021 16:06
Show Gist options
  • Save spestana/ab0dd6d48b5b9343893902a882fad9b1 to your computer and use it in GitHub Desktop.
Save spestana/ab0dd6d48b5b9343893902a882fad9b1 to your computer and use it in GitHub Desktop.
xarray pcolormesh and contour plotting of gridded 3d data
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
# make fake data grid of x and y values
x, y, = np.meshgrid(np.arange(-5,5,0.01),np.arange(-5,5,0.01))
# compute some function on x and y to get z values
z = np.sin(x**2 + y**2) / (x**2 + y**2)
# create xr data array
da = xr.DataArray(data=z,
dims=["x", "y"],
coords=dict(
x_coord=(["x", "y"], x),
y_coord=(["x", "y"], y))
)
# make figure
fig, ax = plt.subplots(figsize=(7,6))
# pcolormesh
pcolormeshplot = da.plot.pcolormesh(x='x_coord', y='y_coord', ax=ax, add_colorbar=False)
# contour lines
countourplot = da.plot.contour(x='x_coord', y='y_coord', colors='k', levels=[0], ax=ax, linewidths=0.8, linestyles='dotted')
# colorbar
cbar = plt.colorbar(pcolormeshplot)
cbar.add_lines(countourplot)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment