5

This should work but it does not?

plt.figure()
plt.plot(x)
plt.xticks(range(4), [2, 64, 77, 89])  # works

f, ax = plt.subplots(nrows=2, ncols=2)
ax[0, 0].plot(x)
ax[0, 0].set_xticks(range(4), [2, 64, 77, 89])  # does not work

1 Answer 1

5

When using the object orientated API (as in your second example), the functions to set the tick locations and the tick labels are separate - ax.set_xticks and ax.set_xticklabels. Therefore, you will need:

f, ax = plt.subplots(nrows=2, ncols=2)
ax[0, 0].plot(x)
ax[0, 0].set_xticks(range(4))
ax[0, 0].set_xticklabels([2, 64, 77, 89])
2
  • Thanks! One more question about this one: if I do not use the "ax[0, 0].set_xticks(range(4))" the it "forgets" to use the first tick and it works for example with ax[0, 0].set_xticklabels([-999, 2, 64, 77, 89]) where the -999 is ignored why is that? The set_xticklabels documentation does not comment on it ...
    – lordy
    Commented Aug 14, 2018 at 14:39
  • 1
    Because it will apply the tick labels onto the automatically generated ticks that are on the axis, which can result in some undesired results as you've noticed. When setting tick labels it's usually a good idea to set the ticks as well, to make sure
    – DavidG
    Commented Aug 14, 2018 at 14:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.