Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

enter image description here

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.

like image 654
Alex Avatar asked Aug 01 '26 05:08

Alex


2 Answers

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

for tick in ax.yaxis.get_majorticklabels():
    tick.set_horizontalalignment("left")
like image 150
lhoupert Avatar answered Aug 02 '26 17:08

lhoupert


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

label alignment example

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

like image 41
Arne Avatar answered Aug 02 '26 17:08

Arne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!