Welcome, guest | Sign In | My Account | Store | Cart

I really like the 'spy' and 'pcolor' functions, which are useful in viewing matrices. 'spy' prints colored blocks for values that are above a threshold, and 'pcolor' prints out each element in a continuous range of colors. The attached is a little Python/PIL script that does these functions for Numpy arrays.

Python, 104 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def spy_matrix_pil(A,fname='tmp.png',cutoff=0.1,do_outline=0,
                   height=300,width=300):
    """\
    Use a matlab-like 'spy' function to display the large elements
    of a matrix using the Python Imaging Library.

    Arguments:
    A          Input Numpy matrix
    fname      Output filename to which to dump the graphics (default 'tmp.png')
    cutoff     Threshold value for printing an element (default 0.1)
    do_outline Whether or not to print an outline around the block (default 0)
    height     The height of the image (default 300)
    width      The width of the image (default 300)

    Example:
    >>> from Numeric import identity,Float
    >>> a = identity(10,Float)
    >>> spy_matrix_pil(a)
    
    """
    import Image,ImageDraw
    img = Image.new("RGB",(width,height),(255,255,255))
    draw = ImageDraw.Draw(img)
    n,m = A.shape
    if n>width or m>height:
        raise "Rectangle too big %d %d %d %d" % (n,m,width,height)
    for i in range(n):
        xmin = width*i/float(n)
        xmax = width*(i+1)/float(n)
        for j in range(m):
            ymin = height*j/float(m)
            ymax = height*(j+1)/float(m)
            if abs(A[i,j]) > cutoff:
                if do_outline:
                    draw.rectangle((xmin,ymin,xmax,ymax),fill=(0,0,255),
                                        outline=(0,0,0))
                else:
                    draw.rectangle((xmin,ymin,xmax,ymax),fill=(0,0,255))
    img.save(fname)
    return

def pcolor_matrix_pil(A,fname='tmp.png',do_outline=0,
                      height=300,width=300):
    """\
    Use a matlab-like 'pcolor' function to display the large elements
    of a matrix using the Python Imaging Library.

    Arguments:
    A          Input Numpy matrix
    fname      Output filename to which to dump the graphics (default 'tmp.png')
    do_outline Whether or not to print an outline around the block (default 0)
    height     The height of the image (default 300)
    width      The width of the image (default 300)

    Example:
    >>> from Numeric import identity,Float
    >>> a = identity(10,Float)
    >>> pcolor_matrix_pil(a)
    
    """
    import Image,ImageDraw
    img = Image.new("RGB",(width,height),(255,255,255))
    draw = ImageDraw.Draw(img)

    mina = min(min(A))
    maxa = max(max(A))

    n,m = A.shape
    if n>width or m>height:
        raise "Rectangle too big %d %d %d %d" % (n,m,width,height)
    for i in range(n):
        xmin = width*i/float(n)
        xmax = width*(i+1)/float(n)
        for j in range(m):
            ymin = height*j/float(m)
            ymax = height*(j+1)/float(m)
            color = get_color(A[i,j],mina,maxa)
            if do_outline:
                draw.rectangle((xmin,ymin,xmax,ymax),fill=color,
                               outline=(0,0,0))
            else:
                draw.rectangle((xmin,ymin,xmax,ymax),fill=color)
                    
    img.save(fname)
    return

def get_color(a,cmin,cmax):
    """\
    Convert a float value to one of a continuous range of colors.
    Rewritten to use recipe 9.10 from the Python Cookbook.
    """
    import math
    try: a = float(a-cmin)/(cmax-cmin)
    except ZeroDivisionError: a=0.5 # cmax == cmin
    blue = min((max((4*(0.75-a),0.)),1.))
    red = min((max((4*(a-0.25),0.)),1.))
    green = min((max((4*math.fabs(a-0.5)-1.,0)),1.))
    return '#%1x%1x%1x' % (int(15*red),int(15*green),int(15*blue))

from Numeric import identity,Float

a = identity(10,Float)
spy_matrix_pil(a)
pcolor_matrix_pil(a,'tmp2.png')

I often want to use Matlab's wonderful matrix viewing capabilities, especially the 'spy' and 'pcolor' functions, but the hassles of dumping a numpy matrix and reading it into Matlab normally keep me from doing this. Here's a little toy that I wrote to do this using the PIL.

There are some idiocies in this script, particularly the way that elements are converted to pixels. But this function does 99% of what I need out of a code.

2 comments

john cole 19 years, 1 month ago  # | flag

Tweak for Numarray. I had to make a small tweak to pcolor_matrix_pil() to get it to work with Numarray:

# For Numeric
#mina = min(min(A))
#maxa = max(max(A))

# For Numarray
mina = A.min()
maxa = A.max()

Otherwise, it seems to work nicely. I am using your recipe to visualize coefficients of inbreeding and relationship in pedigrees. Thanks for the cool recipe -- it took me about fifteen minutes to drop it into my app and get it working.

Ted Drain 19 years, 1 month ago  # | flag

Check out matplotlib. Take a look at the matplotlib package:

http://matplotlib.sourceforge.net/

It's a recreation (ongoing) of the matlab plotting system in python using a variety of rendering packages (backends) and non-GUI and GUI front ends. I believe that it implements pcolor and spy (as well as most 2-D matlab plotting)