How to graph adjacency matrix using MATLAB

前端 未结 3 1445
暖寄归人
暖寄归人 2021-01-05 01:25

I want to create a plot showing connections between nodes from an adjacency matrix like the one below.

\"enter

3条回答
  •  佛祖请我去吃肉
    2021-01-05 01:29

    One way would be to write your own algorithm using some sort of electrostatic repulsion as in the paper you linked. Can probably be done in less than 40 lines of Matlab (it seems others have tried). But sometimes, it is better to use external tools than to do everything in Matlab. The best tool for drawing graphs is probably Graphviz, which comes with a suite of tools for drawing different style graphs. For undirected graphs, the one to use is neato. I don't know which algorithm it uses to distribute the nodes, but I guess it is something similar to the ones in your paper (one of the references even mentions Graphviz!).

    The input for these tools is a very simple text format, which is easy enough to generate using Matlab. Example (this works on linux, you might have to change it a bit on windows):

    % adjacency matrix
    A = [1 1 0 0 1 0;
         1 0 1 0 1 0;
         0 1 0 1 0 0;
         0 0 1 0 1 1;
         1 1 0 1 0 0;
         0 0 0 1 0 0];
    
    % node labels, these must be unique
    nodes = {'A', 'B', 'C', 'D', 'E', 'F'};
    
    n = length(nodes);
    assert(all(size(A) == n))
    
    % generate dot file for neato
    fid = fopen('test.dot', 'w');
    fprintf(fid, 'graph G {\n');
    for i = 1:n
        for j = i:n
            if A(i, j)
                fprintf(fid, '    %s -- %s;\n', nodes{i}, nodes{j});
            end
        end
    end
    fprintf(fid, '}\n');
    fclose(fid);
    
    % render dot file
    system('neato -Tpng test.dot -o test.png')
    

    Which yields the file test.dot:

    graph G {
        A -- A;
        A -- B;
        A -- E;
        B -- C;
        B -- E;
        C -- D;
        D -- E;
        D -- F;
    }
    

    and finally an image test.png (note that your adjacency matrix lists a connection of the first item with itself, which shows as the loop at node A):

    enter image description here

    As a more complex example, you could plot a bucky-ball as in the documentation of gplot:

    [A, XY] = bucky;
    nodes = arrayfun(@(i) num2str(i), 1:size(A,1), 'uni', 0);
    

    with result (note that the layout is done by neato, it does not use XY):

    enter image description here

提交回复
热议问题