How to add highlighted nodes and edges of a graph to the legend?

18 views (last 30 days)
Hi, do you know how to add graphhighlighted nodes and edges to the legend?
For example, in this case (highlight) , I would like to add one entry for the red edges and one entry for the green nodes
s = 1;
t = 2:6;
G = graph(s,t);
h = plot(G,'Layout','force')
highlight(h,[1 2 3],'NodeColor','g')
highlight(h,1,[2 4 5],'EdgeColor','r')
And/or in this case I would like to add the red edges to the legend as a unique entry
s = [1 1 1 1 1 1 2 3 4 5 6 7 7 7 7 8 9 10 11 8 6];
t = [2 3 4 5 6 7 3 4 5 6 2 8 9 10 11 10 10 11 8 1 11];
G = graph(s,t);
h = plot(G)
[T,p] = minspantree(G);
highlight(h,T,'EdgeColor','r','LineWidth',1.5)
Indeed, as I can see, it is not possible to handle the "highlight" object, for example as:
h = highlight (...)

Accepted Answer

Christine Tobler
Christine Tobler on 5 May 2020
The problem here is that legend will only provide labels for what graphics recognizes as individual objects. So in a line plot, each line is recognized as an object - but graph is recognized as one object only (which allows all the nodes and edges to be rearranged when the layout changes).
The output of highlight is not helpful because the highlights aren't a separate object, highlight is just a method which changes the coloring of the nodes and edges of the GraphPlot object.
The best way to achieve the requested plot is the following one (quite messy):
s = [1 1 1 1 1 1 2 3 4 5 6 7 7 7 7 8 9 10 11 8 6];
t = [2 3 4 5 6 7 3 4 5 6 2 8 9 10 11 10 10 11 8 1 11];
G = graph(s,t);
% Plot two lines; they will be invisible because all points are Not-A-Number,
% but they give legend some objects which it can label
plot([NaN NaN], [NaN NaN], '-')
hold on;
plot([NaN NaN], [NaN NaN], 'r-')
% Reset the default color to the beginning
set(gca, 'ColorOrderIndex', 1)
% Plot and highlight the graph
h = plot(G);
[T,p] = minspantree(G);
highlight(h,T,'EdgeColor','r','LineWidth',1.5)
% Add labels for the first two objects to label. Since we don't add a third label, the graph object itself will not be shown.
legend('standard edges', 'highlighted edges')
The messy part is that the legend is showing objects by the order in which they are plotted - so the objects you want to see in the legend need to be added first.
To do a legend entry for green nodes, use plot([nan nan], [nan nan], 'og', 'MarkerFaceColor', 'rg') (a bit more complicated because plot's circles are usually not filled, while the GraphPlot nodes are always filled).

More Answers (0)

Categories

Find more on Graph and Network Algorithms in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!