How to place text label near line, but avoiding other lines and labels?
77 views (last 30 days)
Show older comments
I would like to plot many lines and put a text label near each line. But often the text labels lie over other lines or labels, and so can't be read. How can I reduce visual clutter by smarter label placement? I don't want to move the labels manually due to the large number of plots. Nor should the label text have a white background because it would obscure the plotted data. A plot legend doesn't work due to the large number of lines; the label needs to be near the line instead.
Here's an example of how the labels are hard to read. How can I clean this up?
figure;
x = 1:10;
nLine = 15;
y = rand(size(x));
for iLine = 1:nLine
y = rand(size(x));
h = plot(x, y); % Plot a line
hold on;
% Put a text label at the max of the line
iMax = find(y == max(y)); % Find the highest point
% Label the line
t = text(x(iMax), y(iMax), ['Line ' num2str(iLine)], 'color', get(h, 'color'));
% Could also randomly pick a point on line to label; that will be
% cluttered too
% Instead, want to place label near line but where it won't overlap
% anything
end
box off;
% Looks so cluttered!
3 Comments
dpb
on 10 Jun 2021
"I do hope smart placement is possible because clabel places text in a smart way..."
But not smart in the sense of your problem -- it has defined isolines in which it simply inserts a value every so often; it doesn't have to worry about another isoline intersecting or occluding the one it's currently working on (at least with smooth surfaces for which it was developed; I supposed one could dream up a counter-example).
If data are scattered all over as your example of random lines is; then KAE's suggestion of labeling at the ends of the lines or a vertical legend outside the axes is about the only choice there is.
It's not an easy problem in general, virtually all references to algorithms I found are for cartography applications that could be adapted I suppose, but in a fairly quick look I didn't find anything specific.
Answers (1)
piston_pim_offset
on 14 Nov 2023
Take a look at this:
https://www.mathworks.com/help/matlab/ref/text.html
See Also
Categories
Find more on Labels and Annotations 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!