Home > Backend Development > Python Tutorial > How to Align Rotated X-axis Labels with Ticks in Matplotlib?

How to Align Rotated X-axis Labels with Ticks in Matplotlib?

Patricia Arquette
Release: 2024-11-02 10:16:03
Original
836 people have browsed it

How to Align Rotated X-axis Labels with Ticks in Matplotlib?

Aligning Rotated X-axis Labels with Ticks

In the context of a Matplotlib figure, you are having trouble aligning rotated x-axis labels with their corresponding ticks. By default, label rotation is centered on the middle of the text, causing them to appear shifted to the right when rotated.

To overcome this, you can utilize the ha parameter to set the horizontal alignment of ticklabels. This parameter specifies which side of the label's rectangular bounding box should be aligned with the tickpoint.

For your requirement, you want the right side of the label to align with the tickpoint. Therefore, you should specify ha='right'.

Here's a code example to demonstrate this:

<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])</code>
Copy after login

This code will produce a plot with three subplots, each showing the same data with rotated x-axis labels. The first subplot has labels aligned to the right of the ticks, the second has centered labels, and the third has labels aligned to the left of the ticks.

The above is the detailed content of How to Align Rotated X-axis Labels 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