views:

744

answers:

1

I want to plot a confusion matrix using Pylab. The class labels along the horizontal axis are long, so I want to plot them rotated vertically. However, I also want to plot them on top of the axis, not below.

This command can plot vertical labels on bottom:

pylab.imshow(confusion_matrix)
pylab.xticks(..., rotation='vertical')

and this command can plot horizontal labels on top without rotation:

pylab.matshow(confusion_matrix)

but I cannot find anything that does both. The following command does not work.

pylab.matshow(confusion_matrix)
pylab.xticks(..., rotation='vertical')

Can you suggest a way to plot a confusion matrix with xticks on top of the axis with vertical rotation? Thank you.

EDIT

Thank you, Mark, for your help. It got me on the right track by inspecting the tick properties more closely. The only difference with your answer and my desired answer is applying that idea to an AxesImage, not a plot. After investigation, here is the answer:

im = pylab.matshow(confusion_matrix)
for label in im.axes.xaxis.get_ticklabels():
    label.set_rotation(90)
im.figure.show()

To those reading... don't forget about show()! I forgot that I needed to refresh the figure. See output below.

Confusion matrix with vertical labels.

+1  A: 

If I understand you correctly, this will get you close. You might have to 'pad' your labels out with spaces to move them off the xaxis line.

from matplotlib import pylab 
pylab.plot([0, 6], [0, 6])
pylab.xticks([1,2,3,4,5,6],('one','two','three','four','five','six'),rotation='vertical',verticalalignment='bottom')

EDIT IN RESPONSE TO COMMENT

If you want them rotated vertical on the top x-axis, try this:

pylab.plot([0, 6], [0, 6])
pylab.xticks([1,2,3,4,5,6],('one','two','three','four','five','six'))
for tick in pylab.gca().xaxis.iter_ticks():
    tick[0].label2On = True
    tick[0].label1On = False
    tick[0].label2.set_rotation('vertical')

alt text

Mark
Thank you for your prompt response. I was unclear. I am trying to plot the labels on top of the entire figure. For example, pylab.matshow() does this, but the labels cannot be rotated. It would be really nice to rotate them, because it makes everything more readable, especially when the confusion matrix is large.
Steve
@Steve, see edits above.
Mark
Thank you, my I-95 neighbor. I learned a lot by analyzing your answer. See edit to original post above.
Steve