import matplotlib.pyplot as plt
import numpy as np
import sys

def main(argv = None):
    if argv is None:
        argv = sys.argv

    M=np.array([[0.91044776,0.,0.01492537,0.05970149,0.,0.,0.01492537,0.,0.,0.],
        [0.,0.89830508,0.05084746,0.,0.03389831,0.,0.,0.01694915,0.,0.],
        [0.,0.15492958,0.07042254,0.,0.1971831,0.57746479,0.,0.,0.,0.],
        [0.,0.,0.,0.95833333,0.,0.,0.04166667,0.,0.,0.],
        [0.,0.02739726,0.02739726,0.,0.73972603,0.20547945,0.,0.,0.,0.],
        [0.01470588,0.10294118,0.,0.,0.00735294,0.86764706,0.,0.00735294,0.,0.],
        [0.04166667,0.,0.,0.,0.,0.,0.95833333,0.,0.,0.],
        [0.,0.08910891,0.,0.,0.,0.07920792,0.,0.83168317,0.,0.],
        [0.01515152,0.,0.,0.01515152,0.,0.,0.04545455,0.,0.92424242,0.],
        [0.01538462,0.,0.,0.01538462,0.,
        0.,0.01538462,0.,0.03076923,0.92307692]])

    # should we write 0.0 in empty fields or not?
    show_zeros = False
    horizlabels = ['foobar1', ' foobar2', ' foobar3', ' foobar4', ' foobar5',
        ' foobar6', 'verysuperduperlonglabel', ' foobar8', ' foobar9', ' foobar10']
    vertlabels = horizlabels[:]

    fig = plt.figure()
    fig.subplots_adjust(top=0.8)
    ax = fig.add_subplot(111)

    xax = ax.get_xaxis()
    yax = ax.get_yaxis()

    xax.set_ticks(np.arange(0,10))# + 0.40)
    # is there a better way to make the rotated labels start in the middle?
    # Yes, there is, see below!
    yax.set_ticks(np.arange(0,10))

    xax.set_ticklabels(vertlabels)
    yax.set_ticklabels(horizlabels)

    xax.set_tick_params(top=False, bottom=False, labeltop=True,
            labelbottom=False)
    yax.set_tick_params(left=False, right=False, labelleft=True,
            labelright=False)

    for label in xax.get_ticklabels():
        # State where to place the anchor of the label.
        label.set_horizontalalignment('left')
        label.set_verticalalignment('baseline')
        # Make the label anchor first, and then rotate around the anchor.
        # This lets the label rotate around the point where it would be 
        # anchored with 'left' and 'baseline' in horizontal alignment.
        label.set_rotation_mode('anchor')
        # Let the label rotate.
        label.set_rotation(45)
        # Actually the order of this commands does not matter, since the
        # values are used on render time.

    for row in range(len(vertlabels)):
        for col in range(len(horizlabels)):
            if M[col, row] < 0.5:
                c = 'black'
            else:
                c = 'white'
            if show_zeros or int(1000*M[col,row]) > 0:
                ax.text(row, col, "%.1f" % (100*M[col, row]), color=c, ha='center', va='center')

    ax.imshow(M, cmap=plt.cm.binary, interpolation='nearest')
    plt.show()

if __name__ == "__main__":
    sys.exit(main())
