Python 使用可变坐标绘制xarray数据集

Python 使用可变坐标绘制xarray数据集,python,matplotlib,python-xarray,Python,Matplotlib,Python Xarray,我正在尝试使用xarray在可变网格上绘制数据。存储数据的网格会随着时间的推移而变化,但保持相同的维度 我希望能够在给定的时间绘制它的1d切片。下面是我尝试做的一个玩具示例 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

我正在尝试使用xarray在可变网格上绘制数据。存储数据的网格会随着时间的推移而变化,但保持相同的维度

我希望能够在给定的时间绘制它的1d切片。下面是我尝试做的一个玩具示例

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})
如果我尝试在不同的时间绘制它,即

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

但我希望它能够复制我可以显式使用的行为 matplotlib。在这里,它正确地绘制了当时速度与半径的关系

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

我可能用错了xarray,但它应该根据当时半径的正确值绘制速度


我是设置数据集错误还是使用绘图/索引功能错误?

我同意这种行为是意外的,但并不完全是错误

查看您试图绘制的变量:

da = ds.sel(time=0.2)['velocity']
print(da)
收益率:

<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

有没有更好的方法来构造我的数据集以避免这种情况?这似乎是多余的…@smillerc-不是真的。正如您发布的github问题中提到的,我们可能可以在xarray绘图代码中实现这一点,但我的回答似乎是当前版本的最佳方法。
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')