JPV
JPV

Reputation: 1079

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

Upvotes: 4

Views: 20444

Answers (1)

Serenity
Serenity

Reputation: 36695

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

Upvotes: 12

Related Questions