Search code examples
matlabplotgraphmatlab-figurelegend

How to add legend in a highlighted graph?


I want to add legend in a graph G according to different highlighted edges. Is it possible to do it with only one graph G?

Here is a toy example to play with. I have a plot G.

adj =[0 0 1 1 1;   % adjacency matrix
      1 0 1 0 1;
      0 1 0 1 1;
      1 1 1 0 1;
      0 0 1 0 0]
G = digraph(adj);

I highlighted all edges with 3 colors according to types of edges. 3 types of edges indicate there are 3 different relation between nodes in my case.

This is how I highlighted all edges:

M(:,:,1)=[0 0 1 0 0;1 0 0 0 1;0 0 0 0 0;1 0 0 0 0;0 0 1 0 0];
M(:,:,2)=[0 0 0 1 0; 0 0 1 0 0;0 1 0 0 1;0 0 0 0 0;0 0 0 0 0];              
M(:,:,3)=[0 0 0 0 1; 0 0 0 0 0; 0 0 0 1 0;0 1 1 0 1;0 0 0 0 0];

The difficulty in my problem is that I have to remove vertices whose out-degree is less than some integel (say it's 2). Thus I can't plot 3 graphs independently.

rmvNode=find(outdegree(G)<2);    % outdegree is the reason why single G is neccesary
adj(rmvNode,:)=[]; adj(:,rmvNode)=[];
M(:,rmvNode,:)=[]; M(rmvNode,:,:)=[];
G=digraph(adj);

Then we can plot it.

for k=1:3           %Looping depending on the third dimension
    [r,c]= find(M(:,:,k));  %Finding non-zero elements
    s{k}=r;     t{k}=c;    
end
h=plot(G);
highlight(h,s{1},t{1},'EdgeColor','r');
highlight(h,s{2},t{2},'EdgeColor','g');
highlight(h,s{3},t{3},'EdgeColor','b');

enter image description here My ideal situation would be a legend like this: assign red edges to label 'type 1', assign blue edges to 'type 2', and assign green ones to 'type 3'. I want something like this:

enter image description here

Once more: I can't plot 3 graphs independently according to 3 pages in M, combine 3 plots together and then add a legend. Because as you can see, outdegree requires a whole graph G as input, it's not viable to divide G into G1, G2 and G3.


Solution

  • One way would be to manipulate the legend function by adding an invisible plot like this:

    %put this at the end of your code
    hold on;                                      %to retain current plot
    ax=plot(NaN,NaN,'r',NaN,NaN,'g',NaN,NaN,'b'); %plotting invisible points of desired colors
    legend(ax,'Type 1','Type 2','Type 3');        %adding the legend
    

    which gives:

    output