Search code examples
matlabgraphplot

Visualize sparsity pattern with intensity using Matlab spy function


Matlab has a function spy for visualizing sparsity patterns of graph adjacency matrices.

Unfortunately it does not display the points by taking into account the magnitude of the values in the matrix. It uses a single color with same intensity to display all entries.

I wish to display the same spy plot but with the points "color-coded" like in a heatmap to indicate the magnitude of the entries. How can I do that?


Solution

  • If your matrix is not very large you could try to view it as an image using imagesc(). (Well you could use it for quite large matrices as well, but the pixels become very small.)

    Here is an example of 20 random points in a 100x100 matrix, using colormap hot:

    N = 100;
    n = 20;
    
    x = randi(N,1,n);
    y = randi(N,1,n);
    z = randi(N,1,n);
    
    data = sparse(x,y,z);
    
    imagesc(data)
    axis square
    colormap('hot')
    

    This is the resulting image.

    Imagesc using colormap hot

    This can be compared to the plot we get using spy(data) where the markers are a bit larger.

    Reference figure using spy

    If a white background is desired an easy way to achieve this is to flip the colormap:

    figure
    imagesc(data)
    axis square
    cmap = flipud(colormap('hot'));
    colormap(cmap)
    

    Imagesc using reversed colormap hot

    Hack solution redefining spy()

    Googling a bit I found this thread at Matlab Central:

    Spy with color for values?

    There a solution is suggested that redefines spy(). It's however worth noting that (further down in the thread) this solution can also cause Matlab to crash for larger matrices.