Plotting xarray datasets with variable coordinates
I am trying to use xarray to plot data in a variable grid. The grid that my data is stored in changes over time, but keeps the same dimensions.
I would like to be able to cut 1d pieces of it at a certain point in time. Below is an example of what I am trying to do.
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()
But I would like it to reproduce the behavior that I can explicitly use Matplotlib. Here he correctly calculates the speed in relation to the radius at this time.
plt.plot(radius[0], velocity[0])
plt.plot(radius[1], velocity[1])
plt.show()
I may be using xarray by mistake, but it should be plotting the speed against the correct radius value at this time.
Am I setting up the Dataset incorrectly or using the plot / index function incorrectly?
source to share
I agree that this behavior is unexpected, but it is not really a bug.
Take a look at the variables you are trying to build:
da = ds.sel(time=0.2)['velocity']
print(da)
gives:
<xarray.DataArray 'velocity' (radius: 3)>
array([ 0. , 0.932039, 0.675463])
Coordinates:
r (radius) float64 0.0 1.2 2.4
time float64 0.2
Dimensions without coordinates: radius
We see that there is no named coordinate variable radius
that it looks for xarray
when creating its x coordinate for the graphs shown above. In your case, you need a simple job where we rename the one-dimensional coordinate variable with the same name as the size:
for time in [0.1, 0.2]:
ds.sel(time=time)['velocity'].rename({'r': 'radius'}).plot(label=time)
plt.legend()
plt.title('example for SO')
source to share