Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visualize sparsity pattern with intensity using Matlab spy function

Tags:

graph

plot

matlab

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?

like image 334
lightalchemist Avatar asked Dec 25 '22 22:12

lightalchemist


2 Answers

spy function uses plot, which cannot have different marker colors in a lineseries object.

On the other hand, patch object can have different marker colors for different vertices. patch is originally for drawing polygons, but with no face color and no edge color, one can get similar result to plot with no line style.

S = bucky();
[m, n] = size(S);
[X, Y] = meshgrid(1:m, 1:n);
S = (X + Y) .* S;

nonzeroInd = find(S);
[x, y] = ind2sub([m n], nonzeroInd);

figure();
hp = patch(x, y, S(nonzeroInd), ...
           'Marker', 's', 'MarkerFaceColor', 'flat', 'MarkerSize', 4, ...
           'EdgeColor', 'none', 'FaceColor', 'none');
set(gca, 'XLim', [0, n + 1], 'YLim', [0, m + 1], 'YDir', 'reverse', ...
    'PlotBoxAspectRatio', [n + 1, m + 1, 1]);

colorbar();

Result with <code>jet</code>

You can easily use different colormap, e.g., colormap(flipud(hot)).

Result with reversed <code>hot</code>

like image 124
dlimpid Avatar answered Jan 19 '23 14:01

dlimpid


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.

like image 35
user1884905 Avatar answered Jan 19 '23 15:01

user1884905