Why set_xticks doesn't set the labels of ticks?

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.

131918 次浏览

.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

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

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=...)