基于xarray与Matplotlib绘制多年逐月均值双Y轴坐标图咨询
双Y轴逐月均值图实现方案
核心修正内容
- 新增双Y轴配置,分别对应雪深、径流量两个不同量纲的变量,解决单Y轴下一类变量显示为直线的问题
- 修正原代码中雪深逐年曲线错用径流量数据的BUG
- 合并双Y轴的图例条目,解决雪深相关图例不显示的问题
- 补全原代码中缺失的雪深月均值变量定义
import xarray as xr import numpy as np import matplotlib.pyplot as plt # 数据读取与预处理部分 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() # 补全原代码缺失的雪深月度均值定义 snmonthlymean = snyrs snowlatlonmean = snmonthlymean.mean(dim=['latitude','longitude']) # 计算多年逐月均值 disgroupby = dislatlonmean.groupby("time.month").mean("time") sngroupby = snowlatlonmean.groupby("time.month").mean("time") TYs = np.unique(dislatlonmean["time.year"]) # 绘图部分 双Y轴配置 myfig, ax1 = plt.subplots(figsize=(12,6)) # 第一Y轴:雪深相关(红色系) ax1.set_ylabel('雪深水当量(米)', color='red') # 雪深多年均值粗线 sngroupby.plot.line(ax=ax1, color='red', linestyle='-', linewidth=4, label='雪深多年均值') # 雪深逐年细线 for YY in TYs: ax1.plot(np.arange(1,13), snowlatlonmean.sel(time=YY.astype("str")), color='red', alpha=0.2, label='_nolegend_') # _nolegend_表示不加入图例 ax1.tick_params(axis='y', labelcolor='red') # 第二Y轴:径流量相关(蓝色系) ax2 = ax1.twinx() ax2.set_ylabel('河流径流量(立方米/秒)', color='blue') # 径流量多年均值粗线 disgroupby.plot.line(ax=ax2, color='blue', linestyle='-', linewidth=4, label='径流量多年均值') # 径流量逐年细线 for YY in TYs: ax2.plot(np.arange(1,13), dislatlonmean.sel(time=YY.astype("str")), color='blue', alpha=0.2, label='_nolegend_') ax2.tick_params(axis='y', labelcolor='blue') # X轴配置 ax1.set_xlabel('月份') ax1.set_xticks(range(1, 13)) ax1.set_xticklabels(['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月']) # 合并双Y轴图例 lines1, labels1 = ax1.get_legend_handles_labels() lines2, labels2 = ax2.get_legend_handles_labels() ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right') # 标题与网格 ax1.set_title('1981-1999年喜马拉雅西部雪深与印度河径流量变化') ax1.grid() plt.show()
关键逻辑说明
- 双Y轴通过
ax1.twinx()生成,两个轴共享X轴(月份),分别配置独立的Y轴标签、刻度颜色、对应数据系列,解决两类变量量纲差异过大的显示问题 - 逐年曲线的label设置为
_nolegend_,避免大量重复的逐年线占满图例,仅保留两类数据的多年均值粗线在图例中展示 - 合并两个Y轴的图例句柄后统一展示,解决单轴图例只能显示对应轴系列的问题
内容的提问来源于stack exchange,提问作者grace11
相关产品推荐
相关产品推荐

