【问题标题】:Plotting xarray datasets with variable coordinates绘制具有可变坐标的 xarray 数据集
【发布时间】:2018-01-10 11:09:48
【问题描述】:

我正在尝试使用 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,但它应该根据当时的适当半径值绘制速度。

我是否设置了错误的数据集或使用了错误的绘图/索引功能?

【问题讨论】:

    标签: python matplotlib python-xarray


    【解决方案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 坐标时所寻找的。在您的情况下,您需要一个简单的工作,我们将一维坐标变量重命名为与维度相同的名称:

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

    【讨论】:

    • 有没有更好的方法来构建我的数据集以避免这种情况?这似乎是多余的......
    • @smillerc - 不是真的。正如您发布的 github 问题中所述,我们可能可以在 xarray 绘图代码中实现这一点,但我的回答似乎是当前版本的最佳方法。
    猜你喜欢
    • 2016-08-12
    • 2018-12-24
    • 2020-10-08
    • 2021-02-16
    • 2020-12-06
    • 2020-04-27
    • 2016-06-08
    • 1970-01-01
    • 2017-03-28
    相关资源
    最近更新 更多