首页 > 解决方案 > 如何使用 xarray 绘图功能将多个 xarray DataArray 对象绘制成一个图形?

问题描述

time我有以下具有 3 个维度 ( , latitude, longitude) 和 2 个变量 ( __xarray_dataarray_variable__, )的 xarray 数据集regionsregions变量可以是 nan、0、1、2、3、4 或 5,表示纬度/经度的区域 ID 。__xarray_dataarray_variable__变量是整数。

<xarray.Dataset>
Dimensions:                        (latitude: 106, longitude: 193, time: 92)
Coordinates:
  * latitude                       (latitude) float32 -39.2 -39.149525 ... -33.9
  * longitude                      (longitude) float32 140.8 140.84792 ... 150.0
  * time                           (time) datetime64[ns] 1972-01-01 ... 2017-07-01
Data variables:
    __xarray_dataarray_variable__  (time, latitude, longitude) int32 dask.array<shape=(92, 106, 193), chunksize=(2, 106, 193)>
    regions                        (latitude, longitude) float64 nan nan ... nan

我想绘制一个包含 6 条线的图形,其中 Y 轴是空间平均值__xarray_dataarray_variable__,X 轴是time. 每行对应一个区域 ID。

da = ds["__xarray_dataarray_variable__"]

# Region 0
da_region_0 = da.where(ds.regions == 0)
da_region_0_mean = da_region.mean(['longitude', 'latitude'])  # Get spatial mean

# We can follow the example to get da for region 1 - region 5.
... ...
p_mean = da_region_0_mean.plot.line(x='time')  # This is only plotting a figure for each region but not all 6 regions.

如何使用 xarray 绘图功能绘制一个包含所有 6 个区域的线的单个图形,而不是每个区域的单个图形?

标签: pythonnumpymatplotlibpython-xarray

解决方案


我想我明白你在找什么。这是我接近它的方式。我将首先按照您的风格设置一些数据:

import matplotlib.pyplot as plt
import numpy as np
import xarray as xr

data = np.random.random((6, 3, 11))
da = xr.DataArray(data, dims=['longitude', 'latitude', 'time'], name='foo')

region_data = np.random.choice(range(6), size=(6, 3))
region = xr.DataArray(region_data, dims=['longitude', 'latitude'], name='region')

ds = xr.merge([da, region])

这个数据集ds,看起来像:

<xarray.Dataset>
Dimensions:  (latitude: 3, longitude: 6, time: 11)
Dimensions without coordinates: latitude, longitude, time
Data variables:
    foo      (longitude, latitude, time) float64 0.7016 0.1519 ... 0.1446 0.2396
    region   (longitude, latitude) int64 5 1 1 5 0 1 0 0 2 3 0 4 4 3 3 1 2 1

为了计算区域均值,我们可以首先堆叠数据集的经度和纬度维度:

stacked = ds.stack(xy=('longitude', 'latitude'))

这将使我们能够groupby在计算平均值时轻松地使用按区域编号进行分组:

regional_means = stacked.foo.groupby(stacked.region).mean('xy')

要进行绘图,我们可以使用xarray.DataArray.plot.line关键字hue参数来生成单个面板,其中包含每个区域的时间序列线:

lines = regional_means.plot.line(hue='region', add_legend=False)
labels = range(6)
plt.legend(lines, labels, ncol=2, loc='lower right')

在这里,我们选择创建自己的图例,以尽可能多地控制其位置和格式。这会产生这样的情节:

多线图

更多线图示例可以在这里找到。


推荐阅读