Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

python - Matplotlib date manipulation so that the year tick show up every 12 months

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

Year tick shows up every 12 months, but months show only every 3 months

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:

Not right

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

E.g.

years = mdates.YearLocator()
months = mdates.MonthLocator()
monthsFmt = mdates.DateFormatter('%b') 
yearsFmt = mdates.DateFormatter('

%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)

Results in: enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...