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

조회 수: 91 (최근 30일)
KAE
KAE 2021년 6월 10일
댓글: KAE 2023년 11월 14일
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에서 Axis Labels에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by