|
| 1 | +# sometimes it is nice to have ticklabels centered. mpl currently |
| 2 | +# associates a label with a tick, and the label can be aligned |
| 3 | +# 'center', 'feft', or 'right' using the horizontal alignment property: |
| 4 | +# |
| 5 | +# |
| 6 | +# for label in ax.xaxis.get_xticklabels(): |
| 7 | +# label.set_horizntal_alignment('right') |
| 8 | +# |
| 9 | +# |
| 10 | +# but this doesn't help center the label between ticks. One solution |
| 11 | +# is to "face it". Use the minor ticks to place a tick centered |
| 12 | +# between the major ticks. Here is an example that labels the months, |
| 13 | +# centered between the ticks |
| 14 | + |
| 15 | +import datetime |
| 16 | +import numpy as np |
| 17 | +import matplotlib |
| 18 | +import matplotlib.dates as dates |
| 19 | +import matplotlib.ticker as ticker |
| 20 | +import matplotlib.pyplot as plt |
| 21 | + |
| 22 | +# load some financial data; apple's stock price |
| 23 | +fh = matplotlib.get_example_data('aapl.npy') |
| 24 | +r = np.load(fh); fh.close() |
| 25 | +r = r[-250:] # get the last 250 days |
| 26 | + |
| 27 | +fig = plt.figure() |
| 28 | +ax = fig.add_subplot(111) |
| 29 | +ax.plot(r.date, r.adj_close) |
| 30 | + |
| 31 | +ax.xaxis.set_major_locator(dates.MonthLocator()) |
| 32 | +ax.xaxis.set_minor_locator(dates.MonthLocator(bymonthday=15)) |
| 33 | + |
| 34 | +ax.xaxis.set_major_formatter(ticker.NullFormatter()) |
| 35 | +ax.xaxis.set_minor_formatter(dates.DateFormatter('%b')) |
| 36 | + |
| 37 | +for tick in ax.xaxis.get_minor_ticks(): |
| 38 | + tick.tick1line.set_markersize(0) |
| 39 | + tick.tick2line.set_markersize(0) |
| 40 | + tick.label1.set_horizontalalignment('center') |
| 41 | + |
| 42 | +imid = len(r)/2 |
| 43 | +ax.set_xlabel(str(r.date[imid].year)) |
| 44 | +plt.show() |
0 commit comments