Matplotlib日期操作,使年刻度每12个月显示一次

编程入门 行业动态 更新时间:2024-10-24 12:25:58
本文介绍了Matplotlib日期操作,使年刻度每12个月显示一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在绘制一个图形,其中默认格式显示为:

I'm plotting a figure where the default format shows up as:

我想对其进行修改,以便每1个月显示一次月份刻度,但保留年份。我当前的尝试是:

I would like to modify it so that the month ticks show up every 1 month but keep the year. My current attempt is this:

years = mdates.YearLocator() months = mdates.MonthLocator() monthsFmt = mdates.DateFormatter('%b-%y') dts = s.index.to_pydatetime() fig = plt.figure(); ax = fig.add_subplot(111) ax.plot(dts, s) ax.xaxis.set_major_locator(months) ax.xaxis.set_major_formatter(monthsFmt)

,但未产生正确的结果:

but it's not producing the right result:

我究竟需要如何对其进行修改,使其像第一个一样显示,但每个月都会出现月份滴答声?

How exactly do I need to modify it so that it shows up like the first but with the months ticks appear every month?

推荐答案

提出了一种解决方案,即将几个月留在次要刻度中,而将几年保留为主要月数。

Figured out one solution, which is to stick months into the minor ticks and keep years as the major.

例如

years = mdates.YearLocator() months = mdates.MonthLocator() monthsFmt = mdates.DateFormatter('%b') yearsFmt = mdates.DateFormatter('\n\n%Y') # add some space for the year label dts = s.index.to_pydatetime() fig = plt.figure(); ax = fig.add_subplot(111) ax.plot(dts, s) ax.xaxis.set_minor_locator(months) ax.xaxis.set_minor_formatter(monthsFmt) plt.setp(ax.xaxis.get_minorticklabels(), rotation=90) ax.xaxis.set_major_locator(years) ax.xaxis.set_major_formatter(yearsFmt)

结果:

更多推荐

Matplotlib日期操作,使年刻度每12个月显示一次

本文发布于:2023-06-10 02:02:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/606258.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:刻度   个月   日期   操作   Matplotlib

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!