6

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.

Alex
  • 3,958
  • 4
  • 17
  • 24

3 Answers3

4

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

for tick in ax.yaxis.get_majorticklabels():
    tick.set_horizontalalignment("left")
lhoupert
  • 584
  • 8
  • 25
  • 2
    Thanks, this one works, but the labels now overlap with the lines — it's probably best to use `ax.text()` for more flexibility (like @Arne indicated earlier). Image: https://i.imgur.com/BJXAHKc.png – Alex Jul 10 '20 at 11:47
2

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.

Arne
  • 9,990
  • 2
  • 18
  • 28
0

Pick a padding that's right for your list of labels

ax.tick_params(pad=25)    
ax.set_yticklabels(labels, ha='left')
msch
  • 1,349
  • 2
  • 8
  • 5