How to Align Rotated xticklabels with Ticks in Matplotlib?

Mary-Kate Olsen
Release: 2024-10-30 10:33:02
Original
748 people have browsed it

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

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!

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!