2017-08-03 24 views
3

我正在尝试使用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 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() 

xarray plot version

但我想它复制,我可以使用 matplotlib做明确的行为。在这里,它适当地绘制了当时对半径的速度。

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

proper plot version

我可使用xarray错,但应密谋反对半径当时的正确值的速度。

我是否设置了数据集错误或者使用了plot/index功能?

回答

1

我同意此行为是意外的,但它不完全是一个错误。

望着你想情节变量:

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 

我们看到的是,有没有命名radius坐标变量是什么xarray期待用于为上面显示的图绘制其x坐标。在你的情况,你需要一个工作简单的周围,我们重命名1-d坐标变量同名作为维度:

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') 

enter image description here

+0

有没有更好的方法来组织我的数据集,以避免这种情况?这似乎是多余的... – smillerc

+0

@smillerc - 不是真的。正如您在发布的github问题中提到的那样,我们可以在xarray plotting代码中做到这一点,但我的答案似乎是当前版本的最佳方法。 – jhamman