[SciPy-user] Re: [Matplotlib-users] Visualizing Sparsity Pattern of matrices

John Hunter jdhunter at ace.bsd.uchicago.edu
Thu Nov 11 09:16:03 CST 2004

>>>>> "Nils" == Nils Wagner <nwagner at mecha.uni-stuttgart.de> writes:

    Nils> Hi all, Structure plots provide a quick visual check on the
    Nils> sparsity pattern of the matrix.  A structure plot is a
    Nils> rectangular array of dots; a dot is black if the
    Nils> corresponding matrix element is nonzero otherwise it is
    Nils> white.

    Nils> Is it possible to generate such plots with scipy or should
    Nils> we switch over to matplotlib ?

Here's another implementation that uses images - likely to be much
faster for very large matrices.

import random
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.matlab import *

def spy2(Z):
    SPY(Z) plots the sparsity pattern of the matrix S as an image

    #binary colormap min white, max black
    cmapdata = {
         'red'  :  ((0., 1., 1.), (1., 0., 0.)),
         'green':  ((0., 1., 1.), (1., 0., 0.)),
         'blue' :  ((0., 1., 1.), (1., 0., 0.))
    binary =  LinearSegmentedColormap('binary',  cmapdata, 2)

    Z = where(Z>0,1.,0.)
    imshow(transpose(Z), interpolation='nearest', cmap=binary)

def get_sparse_matrix(M,N,frac=0.1):
    'return a MxN sparse matrix with frac elements randomly filled'
    data = zeros((M,N))*0.
    for i in range(int(M*N*frac)):
        x = random.randint(0,M-1)
        y = random.randint(0,N-1)
        data[x,y] = rand()
    return data

data = get_sparse_matrix(50,60)

More information about the SciPy-user mailing list