Dance Party2
Dance Party2

Reputation: 7536

Matplotlib set_yticklabels shifting

Given the following code:

import matplotlib.pyplot as plt
import numpy as np

x = [1.0, 1.1, 2.0, 5.7]
y = np.arange(len(x))
fsize=(2,2)
fig, ax = plt.subplots(1,1,figsize=fsize)
ax.set_yticklabels(['a','b','c','d'])
ax.barh(y,x,align='center',color='grey')
plt.show()

Why are the labels not showing as expected ('a' does not show up and everything is shifted down by 1 place)?

enter image description here

Upvotes: 6

Views: 6204

Answers (2)

Vince Hall
Vince Hall

Reputation: 44

No, none of that works for me on Windows, Python 3.7. Just print it as text with the x-axis location slightly to the left of the smallest x value.

import matplotlib.pyplot as plt
import numpy as np

ax.set_yticklabels("")
x = [1.0, 1.1, 2.0, 5.7]
y = np.arange(len(x))
fsize=(2,2)
fig, ax = plt.subplots(1,1,figsize=fsize)
    names = ['a','b','c','d']
    for i in np.arange(len(x)):
        plt.text(-0.05,len(x)-i-1,names[i])
    plt.show()

Upvotes: 0

Mad Physicist
Mad Physicist

Reputation: 114440

The locator is generating an extra tick on each side (which are not being shown because they is outside the plotted data). Try the following:

>>> ax.get_yticks()
array([-1.,  0.,  1.,  2.,  3.,  4.])

You have a couple of options. You can either hard-code your tick labels to include the extra ticks (which I think is a bad idea):

ax.set_yticklabels(list(' abcd')) # You don't really need 'e'

Or, you can set the ticks to where you want them to be along with the labels:

ax.set_yticks(y)
ax.set_yticklabels(list('abcd'))

A more formal solution to the tick problem would be to set a Locator object on the y-axis. The tick label problem is formally solved by setting the Formatter for the y-axis. That is essentially what is happening under the hood when you call set_yticks and set_yticklabels anyway, but this way you have full control:

from matplotlib.ticker import FixedLocator, FixedFormatter

...

ax.yaxis.set_major_locator(FixedLocator(y))
ax.yaxis.set_major_formatter(FixedFormatter(list('abcd')))

Upvotes: 5

Related Questions