【发布时间】:2021-10-09 08:08:43
【问题描述】:
感谢您对我的问题感兴趣。
我希望在 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 的特定月度数据,或者我是否需要对我尝试过的命令进行任何调整。
非常感谢您的慷慨帮助。 如果您需要更多信息,请告诉我,我会尽快回复。 谢谢!
【问题讨论】:
-
您必须对坐标进行类型转换。我的建议是您应该以 numpy 数组的形式接收坐标并使用
astype函数。然后再次覆盖坐标。
标签: python numpy time-series netcdf python-xarray