Aligning Rotated X-axis Labels with Ticks
In the context of a Matplotlib figure, you are having trouble aligning rotated x-axis labels with their corresponding ticks. By default, label rotation is centered on the middle of the text, causing them to appear shifted to the right when rotated.
To overcome this, you can utilize the ha parameter to set the horizontal alignment of ticklabels. This parameter specifies which side of the label's rectangular bounding box should be aligned with the tickpoint.
For your requirement, you want the right side of the label to align with the tickpoint. Therefore, you should specify ha='right'.
Here's a code example to demonstrate this:
<code class="python">import matplotlib.pyplot as plt import numpy as np 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)) ha = ['right', 'center', 'left'] for n, ax in enumerate(axs): ax.plot(x, y, 'o-') ax.set_title(ha[n]) ax.set_xticks(x) ax.set_xticklabels(xlabels, rotation=40, ha=ha[n])</code>
This code will produce a plot with three subplots, each showing the same data with rotated x-axis labels. The first subplot has labels aligned to the right of the ticks, the second has centered labels, and the third has labels aligned to the left of the ticks.
The above is the detailed content of How to Align Rotated X-axis Labels with Ticks in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!