微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用Xarray绘制多年来的月平均值

如何解决使用Xarray绘制多年来的月平均值

我有来自ERA 5重新分析的u和v分量的月平均值。我首先根据u和v分量计算出风向和速度,然后将其保存到新变量中。然后,我选择一个位置来绘制这些新变量的时间序列,这很好。

我接下来要做的是将每年的月值绘制成单独的一行。因此,X值是jan到dec,y值是速度(或方向),并且每行都用年标记

我的数据:https://1drv.ms/u/s!AjhLAXJj0C_0t2w1j5TCjzR3g1My?e=IjMFbk

dataset = xr.open_dataset("Feb2020.nc")    
                                  
# Create new layer of speed m/s
dataset["speed"] = np.sqrt(np.square(dataset.u10) + np.square(dataset.v10))    
dataset.speed.attrs["units"] = "meter_second"
dataset.speed.interpolate_na(dim='time')

# Create new layer of direction
dataset["direction"] =  270 - (np.arctan2(dataset.v10,dataset.u10)*(180/np.pi))
dataset.direction.attrs["units"] = "degrees"

# Set lat and lon for extraction point
lon_st = 6.25                                                                  
lat_st = -55.00

# Extract timeseries based on lat/lon
monthly_speed = dataset.speed.sel(longitude=lon_st,latitude=lat_st,expver=1,method='nearest')    
monthly_direction = dataset.direction.sel(longitude=lon_st,method='nearest') 

#What my data looks like

In[13]: dataset
Out[13]: 
<xarray.Dataset>
Dimensions:    (expver: 2,latitude: 7,longitude: 17,time: 493)
Coordinates:
  * longitude  (longitude) float32 -57.5 -57.25 -57.0 ... -54.0 -53.75 -53.5
  * latitude   (latitude) float32 7.0 6.75 6.5 6.25 6.0 5.75 5.5
  * expver     (expver) int32 1 5
  * time       (time) datetime64[ns] 1979-01-01 1979-02-01 ... 2020-01-01
Data variables:
    u10        (time,expver,latitude,longitude) float32 -3.9958236 ... -2.9505084
    v10        (time,longitude) float32 -3.8422172 ... -1.6807995
    speed      (time,longitude) float32 5.543396 ... 3.3956716
    direction  (time,longitude) float32 406.12274 ... 420.33136
Attributes:
    Conventions:  CF-1.6
    history:      2020-02-20 12:31:11 GMT by grib_to_netcdf-2.16.0: /opt/ecmw...

解决方法

  1. 如果您不共享数据或其他任何事情来重现您的问题,社区很难为您提供帮助
  2. 您可以使用matplotlib。代码应如下所示:
from matplotlib import pyplot as plt
plt.plot(dataset.time.values,dataset.speed.values,label='Windspeed')
plt.legend()
plt.savefig('monthly_wind_speed_mean.png')
  1. 或者您也使用xmat函数之一,也使用matplotlib:

Check out Multiple lines from a 2d DataArray example

,

您可以通过将 Xarray 数据集转换为 Pandas 数据帧来做到这一点。 原因是你需要两个 - 年和月的 groupby 操作,而 Xarray 目前只支持一个 groupby。

# convert to dataframe:
df = monthly_speed.reset_coords(drop=True).to_dataframe()
# add year and month indices:
df['month']=df.index.month
df['year']=df.index.year
# groupby month and year then mean:
dfm = df.groupby(['year','month']).mean().unstack().T.droplevel(0)
# plot:
dfm.plot()

剧情不是很好,可以调整一下。 enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。