Home > Backend Development > Python Tutorial > How to Align Rotated xticklabels with Corresponding xticks in Matplotlib?

How to Align Rotated xticklabels with Corresponding xticks in Matplotlib?

DDD
Release: 2024-10-28 18:37:02
Original
646 people have browsed it

How to Align Rotated xticklabels with Corresponding xticks in Matplotlib?

Aligning Rotated xticklabels with Corresponding xticks

In plotting, one may encounter the issue of misaligned x-axis tick labels when rotating them. The rotation default aligns the labels around their center, resulting in a shift away from the corresponding ticks.

To resolve this issue, the ha parameter in set_xticklabels can be used to control the horizontal alignment. This parameter specifies the side of the bounding box around the rotated label that should be aligned with the tick.

Consider the following code:

<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, axs = plt.subplots(1,3, figsize=(12,3))

alignments = ['right', 'center', 'left']

for n, ax in enumerate(axs):
    ax.plot(x,y, 'o-')
    ax.set_title(alignments[n])
    ax.set_xticks(x)
    ax.set_xticklabels(xlabels, rotation=40, ha=alignments[n])</code>
Copy after login

The output plot illustrates the effect of different ha values:

  • ha='right' aligns the right side of the label box with the tick.
  • ha='center' aligns the label box's center with the tick.
  • ha='left' aligns the left side of the label box with the tick.

By selecting the appropriate ha value, tick labels can be precisely aligned with their corresponding ticks, even when rotated.

The above is the detailed content of How to Align Rotated xticklabels with Corresponding xticks 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template