How do I add a legend to a selected graph?
I want to add a legend in graph G according to different selected edges. Can this be done with just one graph G
?
Here is an example of toys 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 selected all the edges with three colors according to the edge types. The 3 edge types indicate that in my case there are 3 different relationships between nodes.
This is how I selected all the 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 need to remove vertices that have degree less than any integer (say 2). So I cannot 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 build 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');
My ideal situation would be a legend like this: label the red edges as "type 1", assign the blue edges to "type 2" and assign the green edges to "type 3". I want something like this:
Once again: I cannot plot 3 plots independently according to 3 pages in M, merge 3 plots together, and then add a legend. Since, as you can see, outdegree
requires the input of a whole graph G
, it is impractical to divide G
by G1
, G2
and G3
.
source to share
One way is to manipulate the function by adding invisible like this: legend
plot
%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:
source to share