首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用xarray绘图功能将多个xarray DataArray对象绘制成一个图形?

如何使用xarray绘图功能将多个xarray DataArray对象绘制成一个图形?
EN

Stack Overflow用户
提问于 2019-04-10 11:15:05
回答 1查看 2.5K关注 0票数 0

我有以下具有3维(timelatitudelongitude)和2个变量(__xarray_dataarray_variable__regions)的xarray DataSet。regions变量可以是nan、0、1、2、3、4或5,表示经度/纬度的区域Id。__xarray_dataarray_variable__变量是整数。

代码语言:javascript
复制
<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。

代码语言:javascript
复制
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个区域的线的单个图形,而不是每个区域的单个图形?

EN

回答 1

Stack Overflow用户

发布于 2019-04-20 09:49:25

我想我知道你在找什么了。这就是我处理它的方式。首先,我将以您的样式设置一些数据:

代码语言:javascript
复制
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如下所示:

代码语言:javascript
复制
<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

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

代码语言:javascript
复制
stacked = ds.stack(xy=('longitude', 'latitude'))

这将使我们在计算平均值时,可以很容易地使用groupby来按区域编号分组:

代码语言:javascript
复制
regional_means = stacked.foo.groupby(stacked.region).mean('xy')

要绘制图形,我们可以结合使用xarray.DataArray.plot.linehue关键字参数来生成一个面板,其中包含每个区域的时间序列线:

代码语言:javascript
复制
lines = regional_means.plot.line(hue='region', add_legend=False)
labels = range(6)
plt.legend(lines, labels, ncol=2, loc='lower right')

在这里,我们选择创建自己的图例,让我们尽可能多地控制它的位置和格式。这将生成如下所示的图:

更多的线条绘制示例可以在here中找到。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55604236

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档