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
209 views
in Technique[技术] by (71.8m points)

python - MonthLocator in Matplotlib

I have plot like this:

enter image description here

And I want to change the ticks for 12 positions indicating the respective months in this format : Jan-Feb_Mar...

When I am using the MonthLocator funciton the ticks dispappear from plot

ax = plt.gca()
ax.set_xlim([0, 365])
ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_minor_locator(MonthLocator(bymonthday=15))
ax.xaxis.set_major_formatter(ticker.NullFormatter())
ax.xaxis.set_minor_formatter(dates.DateFormatter('%b'))

I do not know where is the error in this code. Thanks

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Main problem of your code is that x axis consists of numbers. If you use dates' formatters you axis have to have dates too.

from datetime import datetime, timedelta
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter
from matplotlib.dates import MonthLocator, DateFormatter
import numpy as np

# example data
x = np.arange(0,366,1)
y = np.random.uniform(-100,100,len(x)) 

# generate list of dates from 01.01.2017 to 01.01.2018 through 1 day
dates = list()
dates.append(datetime.strptime('2017-01-01', '%Y-%m-%d'))
for d in x[1:]:
    dates.append(dates[0] + timedelta(days = d))

# plot with dates not x!
plt.plot(dates,y)
ax = plt.gca()

# set dates limits
ax.set_xlim([dates[0], dates[-1]])

# formatters' options
ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_minor_locator(MonthLocator(bymonthday=15))
ax.xaxis.set_major_formatter(NullFormatter())
ax.xaxis.set_minor_formatter(DateFormatter('%b'))
plt.show()

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

...