首页 > 解决方案 > 时间序列图:xarray 中多年的 Groupby 季节(或特定月份)

问题描述

感谢您对我的问题感兴趣。

我希望在 1981 年至 1999 年的 1 月至 8 月之间专门绘制温度时间序列图。

以下是我的代码和尝试:

temperature = xr.open_dataarray('temperature.nc')

temp = temperature.sel(latitude=slice(34.5,30), longitude=slice(73,78.5))

templatlonmean = temp.mean(dim=['latitude','longitude'])-273.15

tempgraph1 = templatlonmean.sel(time=slice('1981','1999'))

上面的命令可以正常读取,没有任何错误。

以下是我将月份划分为季节的尝试:

第一次尝试

tempseason1 = tempgraph1.groupby("time.season").mean("time")

#Plotting Graph Command
myfig, myax = plt.subplots(figsize=(14,8))

timeyears = np.unique(tempgraph1["time.season"])
tempseason1.plot.line('b-', color='red', linestyle='--',linewidth=4, label='1981-1999 Mean')

我收到此错误:“绘图要求坐标为数字、布尔值或 numpy.datetime64、datetime.datetime、cftime.datetime 或 pandas.Interval 类型的日期。改为接收对象类型的数据。

我尝试将此作为我的第二次尝试(从这篇文章Select xarray/pandas index based on specific months 中检索)但是,我不确定如何用它绘制图表,所以我尝试了以下方法:

def is_amj(month):
    return (month >= 4) & (month <= 6)

temp_seasonal = tempgraph1.sel(time=is_amj(tempgraph1['time.month']))

#Plotting Graph Command
timeyears = np.unique(tempgraph1["time.season"])
temp_seasonal.plot.line('b-', color='red', linestyle='--',linewidth=4, label='1981-1999 Mean')

它没有引起错误,但图表并不理想 图形

所以我继续我的第三次尝试(从这里http://xarray.pydata.org/en/stable/examples/monthly-means.html):

month_length = tempmean.time.dt.days_in_month

weights = month_length.groupby('time.season') / month_length.groupby('time.season').sum()


np.testing.assert_allclose(weights.groupby('time.season').sum().values, np.ones(4))


ds_weighted = (tempmean * weights).groupby('time.season').sum(dim='time')


ds_unweighted = tempmean.groupby('time.season').mean('time')


#Plot Commands
timeyears = np.unique(tempgraph1["time.season"])
ds_unweighted.plot.line('b-', color='red', linestyle='--',linewidth=4, label='1981-1999 Mean')

我仍然遇到与第一次尝试相同的错误:“绘图需要坐标为数字、布尔值或 numpy.datetime64、datetime.datetime、cftime.datetime 或 pandas.Interval 类型的日期。而是接收到对象类型的数据。”

因为我这个命令用于绘制天气图而不是时间序列图,但是我相信 groupby 过程甚至会相似或相同,这就是我使用它的原因。

但是,由于我在编码方面相对较新,请原谅任何语法错误,并且我无法发现任何明显的方法来解决这个问题。

因此,我想知道您是否可以建议任何其他方法来绘制 xarray 的特定月度数据,或者我是否需要对我尝试过的命令进行任何调整。

我非常感谢您的慷慨帮助。如果您需要更多信息,请告诉我,我会尽快回复。谢谢!

标签: pythonnumpytime-seriesnetcdfpython-xarray

解决方案


关于你的问题1.和3.,对象是分组的季节。
您可以通过执行以下操作来可视化:

tempseason1 = tempgraph1.groupby("time.season").mean("time")
print(tempseason1.coords)

您应该会看到如下内容:

Coordinates:
  * lon      (lon) float32 ...
  * lat      (lat) float32 ...
  * season   (season) object 'DJF' 'JJA' 'MAM' 'SON'

注意季节维度的类型对象

我认为你应该使用resample而不是groupby这里。重采样基本上是对时间序列进行上采样或下采样的 groupby。它看起来像:

tempseason1 = tempgraph1.resample(time="Q").mean("time")

参数“Q”是季度频率的 pandas 偏移量,详情请参见此处。

我对绘图了解不多。


推荐阅读