matplotlib: draw major tick labels under minor labels

梦想的初衷 提交于 2019-12-03 09:45:20

问题


This seems like it should be easy - but I can't see how to do it:

I have a plot with time on the X-axis. I want to set two sets of ticks, minor ticks showing the hour of the day and major 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 labels the ticks ok, but the major tick labels (day/month) are drawn on top of the minor tick labels:

How do I force the major tick labels to get plotted below the minor ones? I tried putting newline escape characters (\n) in the DateFormatter, but it is a poor solution as the vertical spacing is not quite right.

Any advice would be appreciated!


回答1:


You can use axis method set_tick_params() with the keyword pad. Compare 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's how the above snippet would render:



来源:https://stackoverflow.com/questions/17718827/matplotlib-draw-major-tick-labels-under-minor-labels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!