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:
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:
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)
So, there are two questions:
- Is it possible to format to the labels when using
set_xticklabels
function? For example, by using a format string. - What is the link between
set_xticklabels
and the Formatter? It appears that the Formatter is not takingset_xticklabels
at all into account, and produces the labels by itself.