Aligning rotated xticklabels with their respective xticks

前端 未结 4 1453
刺人心
刺人心 2020-11-27 11:24

Check the x axis of the figure below. How can I move the labels a bit to the left so that they align with their respective ticks?

I\'m rotating the labels using:

相关标签:
4条回答
  • 2020-11-27 11:34

    Rotating the labels is certainly possible. Note though that doing so reduces the readability of the text. One alternative is to alternate label positions using a code like this:

    import numpy as np
    n=5
    
    x = np.arange(n)
    y = np.sin(np.linspace(-3,3,n))
    xlabels = ['Long ticklabel %i' % i for i in range(n)]
    
    
    fig, ax = plt.subplots()
    ax.plot(x,y, 'o-')
    ax.set_xticks(x)
    labels = ax.set_xticklabels(xlabels)
    for i, label in enumerate(labels):
        label.set_y(label.get_position()[1] - (i % 2) * 0.075)
    

    For more background and alternatives, see this post on my blog

    0 讨论(0)
  • 2020-11-27 11:43

    An easy, loop-free alternative is to use the horizontalalignment Text property as a keyword argument to xticks[1]. In the below, at the commented line, I've forced the xticks alignment to be "right".

    n=5
    x = np.arange(n)
    y = np.sin(np.linspace(-3,3,n))
    xlabels = ['Long ticklabel %i' % i for i in range(n)]
    fig, ax = plt.subplots()
    ax.plot(x,y, 'o-')
    
    plt.xticks(
            [0,1,2,3,4],
            ["this label extends way past the figure's left boundary",
            "bad motorfinger", "green", "in the age of octopus diplomacy", "x"], 
            rotation=45,
            horizontalalignment="right")    # here
    plt.show()
    

    (yticks already aligns the right edge with the tick by default, but for xticks the default appears to be "center".)

    [1] You find that described in the xticks documentation if you search for the phrase "Text properties".

    0 讨论(0)
  • 2020-11-27 11:43

    If you dont want to modify the xtick labels, you can just use:

    plt.xticks(rotation=45)

    0 讨论(0)
  • 2020-11-27 11:53

    You can set the horizontal alignment of ticklabels, see the example below. If you imagine a rectangular box around the rotated label, which side of the rectangle do you want to be aligned with the tickpoint?

    Given your description, you want: ha='right'

    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])
    

    enter image description here

    0 讨论(0)
提交回复
热议问题