Plotting xarray datasets with variable coordinates

Viewed 2036

I'm trying to use xarray to plot data on a variable grid. The grid that my data is stored on is changing over time, but keeps the same dimensions.

I'd like to be able to plot 1d slices of it at a given time. A toy example of what I'm trying to do is shown below.

import xarray as xr
import numpy as np
import matplotlib.pyplot as plt

time = [0.1, 0.2] # i.e. time in seconds

# a 1d grid changes over time, but keeps the same dims
radius = np.array([np.arange(3),
                   np.arange(3)*1.2])

velocity = np.sin(radius) # make some random velocity field

ds = xr.Dataset({'velocity': (['time', 'radius'],  velocity)},
            coords={'r': (['time','radius'], radius), 
                    'time': time})

If I try to plot it at different times, i.e.

ds.sel(time=0.1)['velocity'].plot()
ds.sel(time=0.2)['velocity'].plot()
plt.show()

xarray plot version

But I'd like it to replicate the behavior that I can do explicitly using matplotlib. Here it properly plots the velocity against the radius at that time.

plt.plot(radius[0], velocity[0])
plt.plot(radius[1], velocity[1])
plt.show()

proper plot version

I may be using xarray wrong, but it should be plotting the velocity against the proper value of radius at that time.

Am I setting up the Dataset wrong or using the plot/index feature wrong?

1 Answers
Related