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 begin from the same x-location as District of Columbia.
I tried to do that using Axes.set_yticklabels, but I can't figure out how to do it.
Did you try using the set_horizontalalignment() for each tick on the axis?
for tick in ax.yaxis.get_majorticklabels():
tick.set_horizontalalignment("left")
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 in enumerate(y):
ax.text(-0.8, yi, labels[i], horizontalalignment='left', verticalalignment='center')

Just adjust the offset (-0.8 in the example above) according to your longest label.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With