Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 489
JPV Avatar asked Oct 26 '25 08:10

JPV


1 Answers

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

like image 190
Serenity Avatar answered Oct 28 '25 22:10

Serenity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!