Skip to content Skip to sidebar Skip to footer

How Do You Align Tick Labels In Matplotlib?

I'm trying to build an infographic using matplotlib, and I want to left-align all the y-axis' tick labels. I want to move all the tick labels to the left — I want them all to be

Solution 1:

A flexible approach is to plot the labels separately, with ax.text(). Here is a simple example:

import matplotlib.pyplot as plt

y = [0, 1, 2]
width = [2, 2, 3]
labels = ['Colorado', 'Massachusetts', 'DC']

fig, ax = plt.subplots()
ax.barh(y=y, width=width)
ax.set_yticks(y)
ax.set_yticklabels([]) 

for i, yi inenumerate(y):
    ax.text(-0.8, yi, labels[i], horizontalalignment='left', verticalalignment='center')

label alignment example

Just adjust the offset (-0.8 in the example above) according to your longest label.

Solution 2:

Did you try using the set_horizontalalignment() for each tick on the axis?

for tick in ax.yaxis.get_majorticklabels():
    tick.set_horizontalalignment("left")

Post a Comment for "How Do You Align Tick Labels In Matplotlib?"