Visualize sparse pattern with intensity using Matlab spy function

Matlab has a spy function to visualize sparse patterns of graph adjacency matrices.

Unfortunately, it does not display points, taking into account the magnitude of the values ​​in the matrix. It uses one color with the same intensity to display all records.

I want to display the same spy graph, but with color-coded dots, like in a heat map, to indicate the size of the records. How can i do this?

+4
source share
3 answers

If your matrix is ​​not very large, you can try to view it as an image using imagesc() . (Well, you can use it for fairly large matrices, 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 graph we get with spy(data) , where the markers are a bit larger.

Reference figure using spy

If you need a white background, an easy way to achieve this is to flip the color code:

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

Imagesc using reversed colormap hot

Hack () override solution

Populating a bit I found this thread in Matlab Central:

Spy with color for meanings?

A solution is proposed to override spy() . However, it is worth noting that (further in the stream) this solution can also lead to the failure of Matlab for large matrices.

+4
source
Function

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

On the other hand, a patch object can have different marker colors for different vertices. patch was originally designed to draw polygons, but without a complexion and no edge, you can get a similar plot result without a 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([mn], 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 color maps, for example colormap(flipud(hot)) .

Result with reversed <code> hot </code>

+5
source

I sent the file to MATLAB exchange, which also performs the spy task with points colored according to their value. See here .

+1
source

Source: https://habr.com/ru/post/1498538/


All Articles