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

Linda Hamilton
Release: 2024-11-03 15:14:03
Original
456 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!