使用xarray绘制的双y轴图,多年的月平均值为xaxis

2024-10-01 09:22:54 发布

您现在位置:Python中文网/ 问答频道 /正文

谢谢你对这篇文章感兴趣

我希望创建一个双y轴图,说明两个变量(例如y1=融雪和y2=排放径流)。由于我在python方面的知识非常有限,因为我刚刚开始学习编码,所以对于如何进行这项工作,我感到非常困惑

我能够构建一个双y轴图和一个表示多年月平均值的图。但是,我不知道如何将这些matplotlib代码组合在一起,并创建一个双y轴图,将多年的月平均值作为x轴

月平均值代码


disda = xr.open_mfdataset(sorted(['1980.nc','1981.nc', '1982.nc', '1983.nc','1984.nc','1985.nc','1986.nc','1987.nc', '1988.nc','1989.nc', '1990.nc', '1991.nc', '1992.nc', '1993.nc', '1994.nc', '1996.nc', '1997.nc', '1998.nc','1999.nc']))
snowdepth_we = xr.open_dataarray('Snow depth water equivalent.nc')


disyrs = disda.sel(time=slice('1981','1999'))
snyrs = snowdepth_we.sel(time=slice('1981','1999'))


dismonthlymean = disyrs.dis24

dislatlonmean = dismonthlymean.mean(dim=['latitude','longitude']).resample(time='M').sum()
snowlatlonmean = snmonthlymean.mean(dim=['latitude','longitude'])


disgroupby = dislatlonmean.groupby("time.month").mean("time")
sngroupby = snowlatlonmean.groupby("time.month").mean("time")

#graph commands
myfig, myax = plt.subplots(figsize=(12,6))

    
TYs = np.unique(dislatlonmean["time.year"])
disgroupby.plot.line('b-', color='blue', linestyle='-', linewidth=4, label='Discharge Mean')
for YY in TYs: 
    plt.plot(np.arange(1,13), dislatlonmean.sel(time=YY.astype("str")), 'b-', color='blue', alpha=0.2)        

TYs = np.unique(dislatlonmean["time.year"])
sngroupby.plot.line('b-', color='red', linestyle='-', linewidth=4, label='Snowdepth Mean')
for YY in TYs: 
    plt.plot(np.arange(1,13), dislatlonmean.sel(time=YY.astype("str")), 'b-', color='blue', alpha=0.2)        
        

    
myax.set_title('Western Himalayas Snow Depth and River Indus Discharge Run-off 1981-1999')
myax.set_ylabel('m of water equivalent')
myax.set_xlabel('Month')
myax.set_xticks(range(1, 13))
myax.set_xticklabels(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'])
myax.grid()
myax.legend(['Discharge Mean','Snowdepth'])

由于这不是一个双y轴图,我无法将两个具有不同测量值的变量一起绘制,其中一个变量在图中变为一条平线,在另一个图的下方 monthly graph

另一方面,我能够使用这些命令创建双y轴绘图

disda_dis248199 = disda_dis24.loc['1981':'1999'].mean(dim=['latitude','longitude']).resample(time='M').mean()
snow8199 = snowdepth_we.loc['1981':'1999'].mean(dim=['latitude','longitude']).resample(time='M').mean()

x = disda_dis248199.time
y1 = snow8199
y2 = disda_dis248199

#plotting commands
fig, ax1 = plt.subplots(figsize=(14,8))

ax1.set_xlabel('Year')
ax1.set_ylabel('Snow depth water equivalent (m of w.e)')
ax1.plot(x, y1, color='red', label='River Discharge')
ax1.tick_params(axis='y', labelcolor='red')

ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis

ax2.set_ylabel('River Discharge (m3s−1)')  # we already handled the x-label with ax1
ax2.plot(x, y2, color='blue',alpha=0.4, label='Snow depth water equivalent')
ax2.tick_params(axis='y', labelcolor='blue')

fig.legend(loc="upper right")
ax1.set_title('Western Himalayas Snow Depth and River Indus Tributaries Comparison 1981 - 2016')
ax2.grid()

twin y-axes plot

我曾尝试将这两个命令合并在一起,但没有效果

因此,我想知道是否有任何方法可以像第二张图那样绘制一个双y轴图,但以月为x轴,图上的两条线将代表两个不同的变量

此外,如图1所示,图例仅显示了1981-1999年的流量平均值(粗线)和实际年平均值(细线),因此,我想知道如何解决这个问题

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


Tags: timeplotbluemeanlabelcolor平均值nc
1条回答
网友
1楼 · 发布于 2024-10-01 09:22:54

由于您只提供了部分代码,我无法运行它,因此也无法为您更改它。但是,我将尝试在第一段代码中解释应该更改什么

作为第一步,您希望定义第二个Axes对象,类似于您在第二段代码中所做的:

myax2 = myax.twinx()

由于现在有两个Axes实例,因此需要指定要在哪个Axes实例(或者myax或者myax2)上打印数据。这意味着

disgroupby.plot.line('b-', color='blue', linestyle='-', linewidth=4, label='Discharge Mean')
sngroupby.plot.line('b-', color='red', linestyle='-', linewidth=4, label='Snowdepth Mean')

你应该做一些事情,比如

disgroupby.plot.line('b-', ax=myax, color='blue', linestyle='-', linewidth=4, label='Discharge Mean')
sngroupby.plot.line('b-', ax=myax2, color='red', linestyle='-', linewidth=4, label='Snowdepth Mean')

注意在(关键字)参数列表中添加了ax=...。有关示例,请参见this part of xarray's documentation。此外,您不再希望使用plt.plot,因为这不会指定在哪个Axes实例上打印数据。相反,您希望调用要在其上绘制数据的Axes实例的plot方法。例如,第一次出现

plt.plot(np.arange(1,13), dislatlonmean.sel(time=YY.astype("str")), 'b-', color='blue', alpha=0.2)  

应改为

myax.plot(np.arange(1,13), dislatlonmean.sel(time=YY.astype("str")), 'b-', color='blue', alpha=0.2)

第二次出现应改为

myax2.plot(np.arange(1,13), dislatlonmean.sel(time=YY.astype("str")), 'b-', color='blue', alpha=0.2)

设置标签、标题等类似于您在第二段代码中所做的操作

关于你的plt.plot语句,你在参数列表中有..., 'b-', color='blue', ...。当这起作用时,可以指定两次颜色。您可以删除color='blue'部分,或者将'b-'更改为'-'

相关问题 更多 >