|
3 | 3 | Center labels between ticks
|
4 | 4 | ===========================
|
5 | 5 |
|
6 |
| -Ticklabels are aligned relative to their associated tick. The alignment |
7 |
| -'center', 'left', or 'right' can be controlled using the horizontal alignment |
8 |
| -property:: |
9 |
| -
|
10 |
| - for label in ax.get_xticklabels(): |
11 |
| - label.set_horizontalalignment('right') |
| 6 | +Tick labels are aligned relative to their associated tick, and are by default |
| 7 | +centered. |
12 | 8 |
|
13 | 9 | However, there is no direct way to center the labels between ticks. To fake
|
14 |
| -this behavior, one can place a label on the minor ticks in between the major |
15 |
| -ticks, and hide the major tick labels and minor ticks. |
| 10 | +this behavior, one can place a minor tick in between the major ticks. Then |
| 11 | +label the minor tick, and hide the minor tick lines and the major tick labels. |
16 | 12 |
|
17 | 13 | Here is an example that labels the months, centered between the ticks.
|
18 | 14 | """
|
|
34 | 30 | # 16 is a slight approximation since months differ in number of days.
|
35 | 31 | ax.xaxis.set_minor_locator(dates.MonthLocator(bymonthday=16))
|
36 | 32 |
|
| 33 | +# The NullFormatter removes the major tick labels |
37 | 34 | ax.xaxis.set_major_formatter(ticker.NullFormatter())
|
38 | 35 | ax.xaxis.set_minor_formatter(dates.DateFormatter('%b'))
|
39 | 36 |
|
40 |
| -# Remove the tick lines |
| 37 | +# Remove the minor tick lines |
41 | 38 | ax.tick_params(axis='x', which='minor', tick1On=False, tick2On=False)
|
42 | 39 |
|
43 |
| -# Align the minor tick label |
44 |
| -for label in ax.get_xticklabels(minor=True): |
45 |
| - label.set_horizontalalignment('center') |
46 | 40 | imid = len(r) // 2
|
47 | 41 | ax.set_xlabel(str(r["date"][imid].item().year))
|
48 | 42 | plt.show()
|
0 commit comments