matplotlib matshow labels
The other way to do this is to specify the ticks, and then set the corresponding labels. Then you don't have to worry about the extra out of bounds tick. This comes up in lots of matplotlib demos. So here, note the extra calls the ax.set_xticks
and ax.set_yticks
import numpy as np
import matplotlib.pyplot as plt
alpha = ['ABC', 'DEF', 'GHI', 'JKL']
data = np.random.random((4,4))
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(data, interpolation='nearest')
fig.colorbar(cax)
xaxis = np.arange(len(alpha))
ax.set_xticks(xaxis)
ax.set_yticks(xaxis)
ax.set_xticklabels(alpha)
ax.set_yticklabels(alpha)
plt.show()
What's happening is that the xticks actually extend outside of the displayed figure when using matshow. (I'm not quite sure exactly why this is. I've almost never used matshow, though.)
To demonstrate this, look at the output of ax.get_xticks()
. In your case, it's array([-1., 0., 1., 2., 3., 4.])
. Therefore, when you set the xtick labels, "ABC" is at <-1, -1>, and isn't displayed on the figure.
The easiest solution is just to prepend a blank label to your list of labels, e.g.
ax.set_xticklabels(['']+alpha)
ax.set_yticklabels(['']+alpha)
As a full example:
import numpy as np
import matplotlib.pyplot as plt
alpha = ['ABC', 'DEF', 'GHI', 'JKL']
data = np.random.random((4,4))
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(data, interpolation='nearest')
fig.colorbar(cax)
ax.set_xticklabels(['']+alpha)
ax.set_yticklabels(['']+alpha)
plt.show()