Matplotlib日期操作,使年刻度每12个月显示一次 [英] Matplotlib date manipulation so that the year tick show up every 12 months

查看:404
本文介绍了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个月显示一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆