Search code examples
pythonpython-xarrayhvplot

Plotting two data variables from an xarray dataset using hvplot


I have an xarray Dataset in python. I would like to plot two dependent (data) variables against each other using the hvplot library. Here's a simple example dataset:

import numpy as np
import xarray as xr
import hvplot.xarray

# Create the dataset
time = np.linspace(0,10)
x = time*2 + 1
y = time*3 - 1

ds = xr.Dataset()
ds.coords['time'] = time
ds['x'] = (['time'],x)
ds['y'] = (['time'],y)

# Output
<xarray.Dataset>
Dimensions:  (time: 50)
Coordinates:
  * time     (time) float64 0.0 0.2041 0.4082 0.6122 ... 9.388 9.592 9.796 10.0
Data variables:
    x        (time) float64 1.0 1.408 1.816 2.224 ... 19.78 20.18 20.59 21.0
    y        (time) float64 -1.0 -0.3878 0.2245 0.8367 ... 27.78 28.39 29.0

It's easy to plot x or y against time just by

ds.x.hvplot()

However what I want is to plot x against y. I would have expected this to work:

ds.hvplot(x='x',y='y')

but this only plots one point at a time, with a slider for the 'time' coordinate. xarray has a plot function which does plot as expected using matplotlib.

ds.plot.scatter(x='x',y='y')

Is there any way to reproduce this with hvplot?


Solution

  • Another possibility:

    ds.y.assign_coords(x=ds.x).hvplot.scatter(x="x", y="y")