Search code examples
pythonpython-2.7matplotlibaxis-labels

Align xticks on top of axes with bars in matplotlib


I have the following bar graph.

enter image description here

I want the xticks on the x-axis on top of the graph to align with the bars.

So rather than spacing [105, 20, 75, ...] evenly, I want them spaced so that 105 is above the first bar, 4 is above the last bar, etc.

How would this be done?

Example code (that generates above graph):

from matplotlib import pyplot as plt

x = [10, 20, 30, 40, 90]
y = [7, 8, 12, 25, 50]
other = [105, 20, 75, 20, 4]

fig,ax = plt.subplots()
plt.bar(x,y)

ax.set_title('title', y=1.04)
ax.set_xlabel('x label')
ax.set_ylabel('y label')

ax2 = ax.twiny()
ax2.set_xticklabels(ax2.xaxis.get_majorticklabels(), rotation=90)
ax2.set_xticklabels(other)

plt.show()

Solution

  • What you want to do, is to manually specify the xtick locations using ax2.set_xticks(locations). Also, you want to ensure that the xlims are the same for both ax and ax2. This guarantees that the ticks will line up with the bars. We can do this with set_xlim and get_xlim. If we modify the ax2 portion of the code and take these changes into consideration, we would get the following.

    ax2 = ax.twiny()
    
    # Ensure that the x limits are the same
    ax2.set_xlim(ax.get_xlim())
    
    # Set the labels to be the values we want and rotated
    ax2.set_xticklabels(other, rotation=90)
    
    # Place the xticks on ax2 at the bar centers
    ax2.set_xticks(x)
    

    enter image description here