2017-08-03 70 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