How to place text label near line, but avoiding other lines and labels?

87 次查看(过去 30 天)
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 个评论
KAE
KAE 2021-6-10
Thanks, very useful! I do hope smart placement is possible because clabel places text in a smart way, if I recall. I suppose I could get the location of all existing objects in the plot and maximize a label's distance to them, while minimizing its distance to the points on the line that it's labeling.
dpb
dpb 2021-6-10
"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.

请先登录,再进行评论。

回答(1 个)

piston_pim_offset
piston_pim_offset 2023-11-14
Take a look at this:
https://www.mathworks.com/help/matlab/ref/text.html
  1 个评论
KAE
KAE 2023-11-14
I use the text command in the example above, but is there a better way that you are pointing me to? Like an input argument that I should use?

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Labels and Annotations 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by