Is it possible to format the labels using set_xticklabels in matplotlib?

Viewed 9083

In order to set the labels of an axis object, one uses the xticklabels method:

fig, ax = plt.subplots()
ax.imshow(np.eye(101))
labels = np.linspace(2, 4, 4)
ax.set_xticks([0, 33, 66, 100])
ax.set_xticklabels(labels)

Which gives:

1

It is also possible to format the labels using a formatter:

fig, ax = plt.subplots()
labels = np.linspace(2, 4, 4)
ax.imshow(np.eye(101))
ax.set_xticks([0, 33, 66, 100])
ax.set_xticklabels(labels)
ax.xaxis.set_major_formatter(FormatStrFormatter('%.2f'))

But the formatter only uses the tick position, and not his label:

2

The workaround is to manually format the labels before using set_xticklabels:

fig, ax = plt.subplots()
labels = ["{0:.1f}".format(x) for x in np.linspace(2, 4, 4)]
ax.imshow(np.eye(101))
ax.set_xticks([0, 33, 66, 100])
ax.set_xticklabels(labels)

3

So, there are two questions:

  1. Is it possible to format to the labels when using set_xticklabels function? For example, by using a format string.
  2. What is the link between set_xticklabels and the Formatter? It appears that the Formatter is not taking set_xticklabels at all into account, and produces the labels by itself.
3 Answers

By now (tested on matplotlib 3.4.2) you can also use the .format_ticks method of a Formatter.

ax.set_xticklabels(FormatStrFormatter('%.2f').format_ticks(ticks))

The Formatter formats the ticks before passing them to set_xticklabels.

Related