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)

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.

2

3 Answers

.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])
3

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)

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])
#                ^^^^^^

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest