Why set_xticks doesn't set the labels of ticks?

PythonMatplotlib

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

.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

Solution 2 - Python

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

Solution 3 - Python

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

https://i.stack.imgur.com/v4C30.png"><img src="https://i.stack.imgur.com/v4C30.png" width="220" alt="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=...)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncolinfangView Question on Stackoverflow
Solution 1 - PythonHookedView Answer on Stackoverflow
Solution 2 - PythongroceryheistView Answer on Stackoverflow
Solution 3 - PythontdyView Answer on Stackoverflow