Home >Backend Development >Python Tutorial >How to Align Rotated xticklabels with Ticks in Matplotlib?
Aligning Rotated xticklabels with Ticks
When rotating xticklabels using ax.set_xticklabels(xlabels, rotation=45), the rotation axis defaults to the center of the label text. This may lead to misalignment with ticks, particularly noticeable with long labels. To resolve this, you can adjust the horizontal alignment of the labels.
The ha parameter in ax.set_xticklabels allows you to set the horizontal alignment of the label text. The options are 'left', 'center', and 'right'. By setting ha='right', you can align the right edge of the label box with the tick points.
Consider the following code snippet:
<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]) plt.show()</code>
The resulting figure demonstrates how the labels are aligned with the tick positions depending on the specified horizontal alignment.
The above is the detailed content of How to Align Rotated xticklabels with Ticks in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!