Is it possible to change the position of graph plot node labels?

I used GraphPlot to create a graph but some node labels are on top of edges. Is it possible to change the label positions? If not, are there any alternatives to create visually appealing graphs?
untitled.png

 Accepted Answer

I don't think there are documented properties of a GraphPlot that allow you to change the placement of the labels relative to the nodes. However, you could remove the labels and replace them with your own matching text labels. That way you have complete control over the placement of each label.
Here's a demo.
% Creat a graphplot
s = [1 1 1 1 1 1 1 9 9 9 9 9 9 9];
t = [2 3 4 5 6 7 8 2 3 4 5 6 7 8];
G = graph(s,t);
h = plot(G)
% Add new labels that are to the upper, right of the nodes
text(h.XData+.01, h.YData+.01 ,h.NodeLabel, ...
'VerticalAlignment','Bottom',...
'HorizontalAlignment', 'left',...
'FontSize', 7)
% Remove old labels
h.NodeLabel = {};
As you can see, the demo manipulates the horizontal and vertical placement of the lables relative to the nodes. The demo also offsets the labels by 0.1 from the nodes. Check out text properties for many more options.

2 Comments

Thank you, this works perfectly. Adding the code
text(h.XData+[-0.1 -0.1 0 0 0.1 0.1], h.YData+[0 0 0.15 0.15 0 0], h.NodeLabel,...
'HorizontalAlignment', 'center', 'FontSize', 24);
h.NodeLabel={};
I obtained
Nice! Just keep in mind that your offsets are unique to this graph. So if you were to apply this code to another graph, the offsets may not work in your favor (that's true of any type of hard coded offsets).

Sign in to comment.

More Answers (0)

Categories

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

Asked:

on 27 Aug 2019

Commented:

on 27 Aug 2019

Community Treasure Hunt

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

Start Hunting!