如何将Matplotlib时间轴设为年份数字+大写月份缩写?
解决Matplotlib时间轴自定义格式化问题(年份+大写季度月份缩写)
直接用MonthLocator指定要显示的月份,配合自定义FuncFormatter就能实现你要的效果,不用纠结ConciseDateFormatter的冲突问题,核心是在格式化函数里做逻辑判断:
完整代码示例
import matplotlib.pyplot as plt from matplotlib.dates import MonthLocator, FuncFormatter import datetime # 生成测试数据 dates = [datetime.date(2016, m, 1) for m in range(1, 25)] values = list(range(24)) fig, ax = plt.subplots() ax.plot(dates, values) # 设置x轴只显示1、4、7、10月的刻度 ax.xaxis.set_major_locator(MonthLocator(bymonth=[1,4,7,10])) # 自定义格式化函数 def format_tick(x, pos): # 将时间戳转换为datetime对象 dt = datetime.date.fromordinal(int(x)) if dt.month == 1: # 1月显示年份 return f"{dt.year}" elif dt.month in [4,7,10]: # 指定月份显示大写缩写 return dt.strftime('%b').upper() # 其他情况返回空(locator已限制只显示指定月份,此处不会触发) return "" # 应用自定义格式化器 ax.xaxis.set_major_formatter(FuncFormatter(format_tick)) # 调整x轴标签角度,避免重叠 plt.xticks(rotation=45) plt.tight_layout() plt.show()
关键说明
- 指定刻度位置:
MonthLocator(bymonth=[1,4,7,10])确保x轴只在1、4、7、10月生成刻度,避免多余标签。 - 自定义格式化逻辑:
- 把刻度对应的时间戳转成
datetime.date对象 - 1月时输出年份(如2016)
- 4/7/10月时用
strftime('%b')获取默认小写月份缩写,再调用upper()转成大写(APR、JUL、OCT)
- 把刻度对应的时间戳转成
- 避免冲突:直接替换默认的格式化器,不用和ConciseDateFormatter混用,从根源解决冲突问题。
运行代码后,x轴会显示成你想要的样式:2016 - APR - JUL - OCT - 2017 - APR - JUL - OCT - 2018
内容的提问来源于stack exchange,提问作者steven
相关产品推荐
相关产品推荐

