How do you annotate a matplotlib imshow map with an arrow *and* text?

vy32 picture vy32 · Oct 8, 2013 · Viewed 11.3k times · Source

I am trying to make an illustration that looks like this:

better image

But instead I get this:

basic image

Here is my program:

from pylab import *
from matplotlib import colors
# A = [[1,2,3,4,5]]
A = [[0],[1]]
Amap = colors.ListedColormap(['blue','green'])

figure(1)
imshow(A, cmap=Amap, interpolation='nearest')
annotate('AA BB',xy=(0,0), xytext=(.8,0), fontsize=20)
axis('off')
savefig('graph-py.pdf')
show()

I've tried everything to get the arrow, but can't seem to make it happen. Any ideas?

Answer

wwii picture wwii · Oct 8, 2013

I usually look through the gallery to find examples of what I want to do. annotation_demo2 looked similar to what you wanted ... I came up with this. Looks like you were missing the arrowprops kwarg.

from pylab import *
from matplotlib import colors
# A = [[1,2,3,4,5]]
A = [[0],[1]]
Amap = colors.ListedColormap(['blue','green'])

fig = figure(1)
ax = fig.add_subplot(111, autoscale_on=False)
imshow(A, cmap=Amap, interpolation='nearest')
ax.annotate('AA BB', fontsize=20, xy=(.25, .75),
            xycoords='data', xytext=(150, -6),
            textcoords='offset points',
            arrowprops=dict(arrowstyle="->",
                            linewidth = 5.,
                            color = 'red')
            )
ax.annotate('CC DD', fontsize=20, xy=(.25, .25),
            xycoords='data', xytext=(150, -6),
            textcoords='offset points',
            arrowprops=dict(width = 5.,
                            headwidth = 15.,
                            frac = 0.2,
                            shrink = 0.05,
                            linewidth = 2,
                            color = 'red')
            )
axis('off')
savefig('graph-py.pdf')
show()
close()

Looks like this:

annotate example