xarray绘图时如何将month维度的数值转换为月份名称显示
解决方案
有两种常用实现方式,可按需选择:
方法1:修改数据集month坐标值(推荐,一次修改永久生效)
直接将month维度的整数值替换为对应的月份名称,后续所有基于该数据集的绘图都会自动使用月份标签:
import calendar # 替换为英文月份缩写 temp_rain_mean_months['month'] = [calendar.month_abbr[m] for m in temp_rain_mean_months.month.values] # 如果需要中文月份,使用下面的代码替换即可 # cn_months = ["", "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"] # temp_rain_mean_months['month'] = [cn_months[m] for m in temp_rain_mean_months.month.values] # 执行原绘图代码即可自动显示月份标签 temp_rain_mean_months.Tair_C.plot(x='longitude', y='latitude', col='month', col_wrap=4, levels=[-10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 40])
方法2:绘图后修改子图标题(不改动原数据集,适合临时调整)
保留原数据集的数值坐标,仅对当前生成的绘图对象的子图标题做替换:
import calendar # 保存绘图返回的FacetGrid对象 g = temp_rain_mean_months.Tair_C.plot(x='longitude', y='latitude', col='month', col_wrap=4, levels=[-10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 40]) # 定义月份标签,替换为中文只需修改这个列表即可 month_labels = [calendar.month_abbr[m] for m in range(1, 13)] # 遍历所有子图修改标题 for ax, label in zip(g.axes.flat, month_labels): ax.set_title(label)
内容的提问来源于stack exchange,提问作者HMadadi
相关产品推荐
相关产品推荐

