Vectorfield#

Download this notebook from GitHub (right-click to download).


import hvplot.xarray  # noqa

vectorfield accepts 2d arrays of magnitude and angle on a grid and produces an array of vectors. x and y can be 2d or 1d coordinates.

import numpy as np
import xarray as xr
import cartopy.crs as ccrs
def sample_data(shape=(20, 30)):
    """
    Return ``(x, y, u, v, crs)`` of some vector data
    computed mathematically. The returned crs will be a rotated
    pole CRS, meaning that the vectors will be unevenly spaced in
    regular PlateCarree space.

    """
    crs = ccrs.RotatedPole(pole_longitude=177.5, pole_latitude=37.5)

    x = np.linspace(311.9, 391.1, shape[1])
    y = np.linspace(-23.6, 24.8, shape[0])

    x2d, y2d = np.meshgrid(x, y)
    u = 10 * (2 * np.cos(2 * np.deg2rad(x2d) + 3 * np.deg2rad(y2d + 30)) ** 2)
    v = 20 * np.cos(6 * np.deg2rad(x2d))

    return x, y, u, v, crs

xs, ys, U, V, crs = sample_data()

mag = np.sqrt(U**2 + V**2)
angle = (np.pi/2.) - np.arctan2(U/mag, V/mag)

ds = xr.Dataset({'mag': xr.DataArray(mag, dims=('y', 'x'), coords={'y': ys, 'x': xs}),
                 'angle': xr.DataArray(angle, dims=('y', 'x'), coords={'y': ys, 'x': xs})}, 
                attrs={'crs': crs})
ds
<xarray.Dataset>
Dimensions:  (y: 20, x: 30)
Coordinates:
  * y        (y) float64 -23.6 -21.05 -18.51 -15.96 ... 17.16 19.71 22.25 24.8
  * x        (x) float64 311.9 314.6 317.4 320.1 ... 382.9 385.6 388.4 391.1
Data variables:
    mag      (y, x) float64 6.459 2.149 5.899 11.25 ... 20.98 22.28 22.74 22.0
    angle    (y, x) float64 1.413 0.3677 -0.9793 ... -0.9368 -1.049 -1.127
Attributes:
    crs:      +proj=ob_tran +ellps=WGS84 +a=6378137.0 +o_proj=latlon +o_lon_p...
ds.hvplot.vectorfield(x='x', y='y', angle='angle', mag='mag', hover=False).opts(magnitude='mag')

Geographic Data#

If a dataset has an attr called crs which is a cartopy object or a proj4 string, then just by setting the option geo=True will use the correct crs.

ds.hvplot.vectorfield(x='x', y='y', angle='angle', mag='mag',
                      hover=False, geo=True, tiles="CartoLight")

If you set coastline or features it will keep the original crs and transform the features to the data crs.

ds.hvplot.vectorfield(x='x', y='y', angle='angle', mag='mag',
                      hover=False, geo=True, coastline=True)
This web page was generated from a Jupyter notebook and not all interactivity will work on this website. Right click to download and run locally for full Python-backed interactivity.

Download this notebook from GitHub (right-click to download).