Created
November 8, 2019 21:23
-
-
Save blaylockbk/c638ccda90740085aac80954f35c4c91 to your computer and use it in GitHub Desktop.
infer interval and create new x and y grid to plot data with pcolormesh without loosing the last row and column (code snipet from xarray/plot/utils)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def xr_infer_interval_breaks(coord, axis=0): | |
""" | |
Code from xarray: (github/pydata/xarray/plot/utils) | |
Usage: if x is a 2d array of longitudes... | |
x = _infer_interval_breaks(x, axis=1) | |
x = _infer_interval_breaks(x, axis=0) # repeat for second axis | |
""" | |
deltas = 0.5 * np.diff(coord, axis=axis) | |
first = np.take(coord, [0], axis=axis) - np.take(deltas, [0], axis=axis) | |
last = np.take(coord, [-1], axis=axis) + np.take(deltas, [-1], axis=axis) | |
trim_last = tuple(slice(None, -1) if n==axis else slice(None) for n in range(coord.ndim)) | |
coord = np.concatenate([first, coord[trim_last]+deltas, last], axis=axis) | |
return coord | |
def _infer_interval_breaks(coord): | |
""" | |
Code from xarray: (github/pydata/xarray/plot/utils) | |
If you want to plot with pcolormesh, it will chop off the last row/column becuase | |
pcolormesh uses the box edges as the verticies, and not the center of the box. | |
This function infers the gridpoints to position the points in the center of the box. | |
This is slightly different from the xarray code, in that this one performs the | |
infering on both axes before returning the final product. | |
Usage: if x is a 2d array of longitudes... | |
x = _infer_interval_breaks(x) | |
""" | |
axis = 0 | |
deltas = 0.5 * np.diff(coord, axis=axis) | |
first = np.take(coord, [0], axis=axis) - np.take(deltas, [0], axis=axis) | |
last = np.take(coord, [-1], axis=axis) + np.take(deltas, [-1], axis=axis) | |
trim_last = tuple(slice(None, -1) if n==axis else slice(None) for n in range(coord.ndim)) | |
coord = np.concatenate([first, coord[trim_last]+deltas, last], axis=axis) | |
axis = 1 | |
deltas = 0.5 * np.diff(coord, axis=axis) | |
first = np.take(coord, [0], axis=axis) - np.take(deltas, [0], axis=axis) | |
last = np.take(coord, [-1], axis=axis) + np.take(deltas, [-1], axis=axis) | |
trim_last = tuple(slice(None, -1) if n==axis else slice(None) for n in range(coord.ndim)) | |
coord = np.concatenate([first, coord[trim_last]+deltas, last], axis=axis) | |
return coord |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment