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