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

John Hunter jdhunter at ace.bsd.uchicago.edu
Thu Nov 11 09:05:04 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 ?

A quick matplotlib implementation is below.  In matlab this function
is called "spy" and Alexander Schmolck requested this in an earlier
post.  The spy implementation uses plot markers which are fixed sizes
(in points).  For large matrices, you'll likely want to use a smaller
markersize.

Perhaps better would be to use a polygon collection setup so that the
marker sizes filled the boundaries of the matrix cell.  This would
take a little more work, and would also have a different call
signature that matlab's, since matlab also uses plots markers .  If
you have any thoughts on how you would like the implementation to
work, please share them...

JDH

from matplotlib.matlab import *

def get_xyz_where(Z, Cond):
    """
    Z and Cond are MxN matrices.  Z are data and Cond is a boolean
    matrix where some condition is satisfied.  Return value is x,y,z
    where x and y are the indices into Z and z are the values of Z at
    those indices.  x,y,z are 1D arrays

    This is a lot easier in numarray - is there a more elegant way to
    do this that works on both numeric and numarray?
    """
    
    M,N = Z.shape
    z = ravel(Z)
    ind = nonzero( ravel(Cond) )

    x = arange(M); x.shape = M,1
    X = repeat(x, N, 1)
    x = ravel(X)

    y = arange(N); y.shape = 1,N
    Y = repeat(y, M)
    y = ravel(Y)

    x = take(x, ind)
    y = take(y, ind)
    z = take(z, ind)
    return x,y,z


def spy(Z,  marker='s', markersize=10, **kwargs):
    """
    SPY(Z, **kwrags) plots the sparsity pattern of the matrix S.

    kwargs give the marker properties - see help(plot) for more
    information on marker properties


    """
    x,y,z = get_xyz_where(Z, Z>0)
    plot(x+0.5,y+0.5, linestyle='None', marker=marker,markersize=markersize, **kwargs)

M,N = 25,20
data = zeros((M,N))*0.
data[:,12] = rand(M)
data[5,:] = rand(N)
spy(data)
axis([0,M,0,N])
show()



More information about the SciPy-user mailing list