Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 526
nwly Avatar asked Feb 14 '16 21:02

nwly


People also ask

How do I customize Xticks in MatPlotLib?

Set the figure size and adjust the padding between and around the subplots. Create lists for height, bars and y_pos data points. Make a bar plot using bar() method. To customize X-axis ticks, we can use tick_params() method, with color=red, direction=outward, length=7, and width=2.

How do I turn on ticks in MatPlotLib?

To remove the ticks on both the x-axis and y-axis simultaneously, we can pass both left and right attributes simultaneously setting its value to False and pass it as a parameter inside the tick_params() function. It removes the ticks on both x-axis and the y-axis simultaneously.


1 Answers

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('\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)

Results in: enter image description here

like image 171
nwly Avatar answered Oct 26 '22 23:10

nwly