79
import matplotlib.pyplot as plt

x = range(1, 7)
y = (220, 300, 300, 290, 320, 315)

def test(axes):
    axes.bar(x, y)
    axes.set_xticks(x, [i+100 for i in x])

fig, (ax1, ax2) = plt.subplots(1, 2)
test(ax1)
test(ax2)

enter image description here

I am expecting the xlabs as 101, 102 ... However, if i switch to use plt.xticks(x, [i+100 for i in x]) and rewrite the function explicitly, it works.

tdy
  • 36,675
  • 19
  • 86
  • 83
colinfang
  • 20,909
  • 19
  • 90
  • 173
  • 1
    My guess is because in your code set_xticks is getting a generator object, not a list. Try `list([i+100 for i in x)]` instead. – rabs Feb 20 '14 at 14:55
  • 1
    @rabs there is no generator involved, they are both lists, I am using python 2 – colinfang Feb 20 '14 at 15:00

3 Answers3

145

.set_xticks() on the axes will set the locations and set_xticklabels() will set the displayed text.

def test(axes):
    axes.bar(x,y)
    axes.set_xticks(x)
    axes.set_xticklabels([i+100 for i in x])

enter image description here

Shihe Zhang
  • 2,641
  • 5
  • 36
  • 57
Hooked
  • 84,485
  • 43
  • 192
  • 261
9

Another function that might be useful, if you don't want labels for every (or even any) tick is axes.tick_params.

def test(axes):
    axes.tick_params(axis='x',which='minor',direction='out',bottom=True,length=5)

enter image description here

groceryheist
  • 1,538
  • 17
  • 24
5

New in matplotlib 3.5.0

ax.set_xticks now accepts a labels param to set ticks and labels simultaneously:

fig, ax = plt.subplots()
ax.bar(x, y)
ax.set_xticks(x, labels=[i + 100 for i in x])
#                ^^^^^^

ticklabels changed with labels param

Since changing labels usually requires changing ticks, the labels param has been added to all relevant tick functions for convenience:

  • ax.xaxis.set_ticks(..., labels=...)
  • ax.yaxis.set_ticks(..., labels=...)
  • ax.set_xticks(..., labels=...)
  • ax.set_yticks(..., labels=...)
tdy
  • 36,675
  • 19
  • 86
  • 83