Matplotlib: draw the labels of the main labels under the small labels

It seems like this should be easy - but I don't see how to do it:

I have a graph with time along the X axis. I want to set two sets of ticks, minor ticks showing the hour of the day and the main ticks showing the day / month. So I do this:

# set date ticks to something sensible: xax = ax.get_xaxis() xax.set_major_locator(dates.DayLocator()) xax.set_major_formatter(dates.DateFormatter('%d/%b')) xax.set_minor_locator(dates.HourLocator(byhour=range(0,24,3))) xax.set_minor_formatter(dates.DateFormatter('%H')) 

This indicates the ticks in order, but the main label labels (day / month) are drawn on top of the label labels:

Sig. wave height ensemble time series

How to make shortcuts of main labels draw below secondary? I tried putting line break characters (\ n) in DateFormatter, but this is a bad solution, since the vertical spacing is not quite right.

Any advice would be appreciated!

+8
python matplotlib plot axis-labels
source share
1 answer

You can use the axis set_tick_params() method with the pad keyword. Compare the following example.

 import datetime import random import matplotlib.pyplot as plt import matplotlib.dates as dates # make up some data x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(100)] y = [i+random.gauss(0,1) for i,_ in enumerate(x)] # plot plt.plot(x,y) # beautify the x-labels plt.gcf().autofmt_xdate() ax = plt.gca() # set date ticks to something sensible: xax = ax.get_xaxis() xax.set_major_locator(dates.DayLocator()) xax.set_major_formatter(dates.DateFormatter('%d/%b')) xax.set_minor_locator(dates.HourLocator(byhour=range(0,24,3))) xax.set_minor_formatter(dates.DateFormatter('%H')) xax.set_tick_params(which='major', pad=15) plt.show() 

PS : this example is borrowed from moooeeeep


Here is what the above snippet would look like:

+15
source share

All Articles