In plotting, one may encounter the issue of misaligned x-axis tick labels when rotating them. The rotation default aligns the labels around their center, resulting in a shift away from the corresponding ticks.
To resolve this issue, the ha parameter in set_xticklabels can be used to control the horizontal alignment. This parameter specifies the side of the bounding box around the rotated label that should be aligned with the tick.
Consider the following code:
<code class="python">import numpy as np import matplotlib.pyplot as plt n = 5 x = np.arange(n) y = np.sin(np.linspace(-3,3,n)) xlabels = ['Ticklabel %i' % i for i in range(n)] fig, axs = plt.subplots(1,3, figsize=(12,3)) alignments = ['right', 'center', 'left'] for n, ax in enumerate(axs): ax.plot(x,y, 'o-') ax.set_title(alignments[n]) ax.set_xticks(x) ax.set_xticklabels(xlabels, rotation=40, ha=alignments[n])</code>
The output plot illustrates the effect of different ha values:
By selecting the appropriate ha value, tick labels can be precisely aligned with their corresponding ticks, even when rotated.
The above is the detailed content of How to Align Rotated xticklabels with Corresponding xticks in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!