Search code examples
matlabplotgraph3dadjacency-matrix

How to plot 3d directed graph in matlab


I have an upper triangular adjacent matrix which represents a set of nodes which are connected. Every node is defined by three geographical coordinates: x y z. My goal is to plot the network in order to see what it looks like by taking into account also the direction of the edges.

If I do not take into account the z coordinate, I am able to display the result easily:

enter image description here

The lines of code to get this result are:

A = [0 1 1 0 0 0 0;
     0 0 1 1 0 0 0;
     0 0 0 1 1 1 0;
     0 0 0 0 1 1 0;
     0 0 0 0 0 0 1;
     0 0 0 0 0 0 1;
     0 0 0 0 0 0 0];

 xyz = [ 0  0  0;
      -15 20   5;
       17 24  -3;
       -5 36   7;
      -14 50  -8;
       16 56   3;
        3 70  -1];

F = digraph(A);
figure
p = plot(F,'XData',xyz(:,2),'YData',xyz(:,1)); axis equal;
highlight(p,1,'NodeColor','g'); highlight(p,size(A,1),'NodeColor','r');
view([0 90])

How should I modify my code in order to assign to the graph also the z coordinates so I can have a 3d graph? (remember I want to display the edge direction too!!).

What I tried to do is this:

p = plot3(F,'XData',xyz(:,2),'YData',xyz(:,1),'ZData',xyz(:,3)); 

but I had no success.


Solution

  • In the newest MATLAB Release (R2016b), it's now possible to plot a node-link graph in 3d by choosing a different layout method, or specifying x, y and z coordinates directly. In your example, replace the plotting line by

    p = plot(F,'XData',xyz(:,2),'YData',xyz(:,1),'ZData',xyz(:,3));
    

    Resulting plot:

    A 3-dimensional plot of the graph data