Aligning Rotated X-Axis Tick Labels
When rotating x-axis tick labels, it is often desirable to align them properly with their corresponding ticks. This can be achieved by adjusting the horizontal alignment of the tick labels.
Using the ha Parameter
The matplotlib.axis.Tick.label1 object has a ha parameter that controls the horizontal alignment of the tick label. The available options are:
Example
To align the rotated tick labels with their respective ticks, use ha='right'.
<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, ax = plt.subplots() ax.plot(x, y, 'o-') ax.set_xticks(x) ax.set_xticklabels(xlabels, rotation=40, ha='right') plt.show()</code>
This will produce a plot with rotated tick labels that are aligned with their corresponding ticks, as shown in the image below:
[Image of a plot with rotated tick labels aligned with the ticks]
The above is the detailed content of How to Align Rotated X-Axis Tick Labels in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!