pythonmatplotlibxticks

Custom positioning of x-ticks & labels


For a simple bar chart, I want some of my x-tick labels to be below the x-axis (for positive y-values) while others are above the x-axis (for negative y-values).

I see, per the docs, that a string can be passed as an argument to matplotlib.axes.Axes.set_xticklabel to change vertical alignment, but this is a blanket application.

How would I achieve arbitrary positioning of particular x-tick labels?

bar_chart_x_ticks


Solution

  • You can modify the position / rotation of the labels in a for loop. Initially, I thought changing the rotation point would be enough, but the labels are anchored at the tip of the ticks, so the result was sub-optimal.

    This is my code. You may want to tweak the y position in plus or minus to get the alignment that you want:

    N = 10
    h = np.linspace(-10,10,N)
    xticks = [f'test #{n}' for n in range(N)]
    
    fig, ax = plt.subplots()
    ax.spines['bottom'].set_position('zero')
    ax.bar(range(N),h)
    ax.set_xticks(range(N))
    ax.set_xticklabels(xticks)
    
    for i,(g,t) in enumerate(zip(h,ax.get_xticklabels())):
        if g<0:
            t.set_ha('left')
            t.set_va('bottom')
        else:
            t.set_ha('right')
            t.set_va('top')
        t.set_rotation_mode('anchor')
        t.set_rotation(45)
        t.set_transform(ax.transData)
        t.set_position((i,0))
    

    enter image description here