Home  >  Article  >  Backend Development  >  How to Align Rotated X-Axis Tick Labels in Matplotlib?

How to Align Rotated X-Axis Tick Labels in Matplotlib?

Linda Hamilton
Linda HamiltonOriginal
2024-11-03 15:14:03457browse

How to Align Rotated X-Axis Tick Labels in Matplotlib?

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:

  • 'left': Align the left side of the label rectangle with the tick point.
  • 'center': Align the center of the label rectangle with the tick point.
  • 'right': Align the right side of the label rectangle with the tick point.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn