Avoid overlapping xline labels
이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
이전 댓글 표시
0 개 추천
Hi,
I'm trying to avoid overlapping xline labels. My code below attempts to identify the mean x,y and z components of the attached dataset 'corr'. Clearly I can play with the horizontal alignment command, but as I have multiple datasets with varying mean 'corr' values, I would prefer a more robust means of avoiding overlap, e.g. a slight vertical offset between the mean values (the 'LabelVerticalAlignment' command only offers limited options: top, middle and bottom - I would prefer all the labels to be positioned near the top of the graph, i.e. above the histogram, and avoiding any overlap). How would I achieve this?
Thanks
Here is my code.
% Plot correlation histogram
h = figure(2);
corr_bar = mean(corr(:,1:3));
for i = 1:3
H = histogram(corr(:,i:3),'FaceAlpha',0.4,'edgecolor','none');
H_max(i) = max(H.Values);
x = xline(corr_bar(i),':',sprintf('%c',V_i{i}),'LabelHorizontalAlignment',pos_h{i},'LineWidth',.5,'Color','b','HandleVisibility','off','interpreter','latex'); %sprintf('%c = %0.2f',V_i{i},round(corr_bar(i)*100)/100')
x.LabelHorizontalAlignment = 'center';
hold on
end
xlim([65 100])
ylim([0 max(H_max)*1.1])
xlabel('Correlation (\%)','interpreter','latex')
ylabel('Frequency (-)','interpreter','latex')
xline(70,'-.','Threshold','LineWidth',1,'Color','b','interpreter','latex')
legend('\it{u}','\it{v}','\it{w}','Location','southeast')
set(gca,'FontSize',12)
set(legend,'FontSize',12)
채택된 답변
Star Strider
2022년 2월 20일
The labels are always at the top of the xline so one option is just to pad the end of the label with spaces —
figure
xl1 = xline(0.55, '-', 'Label 1');
xl2 = xline(0.56, '--', ['Label 2' ' ']);
xlim([0 1])

There may be more elegant ways to accomplish this, however they do not appear to be in the xline properties. (This is obviously a text object, so there should be (x,y) position coordinates that can be changed, however it is not obvious to me how to find them in the properties, even using findobj.)
.
댓글 수: 20
Daniel Rowe
2022년 2월 20일
ok thank you. How would I incorporate that into my sprintf line code?
I would so something like this —
sprintf(['%c' repmat(' ',1,10)],V_i{i})
That adds spaces at the end.
To demonstrate the effect, change the space to something else, for example a hyphen —
i = 1;
V_i{i} = '$';
sprintf(['%c' repmat('-',1,10)],V_i{i})
ans = '$----------'
.
Daniel Rowe
2022년 2월 20일
the dashed line option works nicely to demonstrate, but my preference is for blank spaces after the mean value. I integrated this into the loop to get the graduated height differential but doesn't seem to work:
sprintf(['%c' repmat(' ',1,i*2)],V_i{i})
i.e. no spaces appear after printing the value
It appears to work for me here —
figure
xl1 = xline(0.55, '-', 'Label 1');
xl2 = xline(0.56, '--', sprintf(['%s' repmat(' ',1,20)],'Label 2'));
xlim([0 1])

I cannot determine the reason it fails to work in your code. Perhaps you just need more spaces?
.
Daniel Rowe
2022년 2월 21일
OK so the code works fine without the latex interpreter., which seems strange. Any idea why this might be, or how I might get around this?
LaTeX requires a different way of specifying spaces.
They must be ‘escaped’, that is written as ‘\ ’, as illustrated here, both in the repmat call and the spaces in the ‘Label 2’ character vector —
figure
xl1 = xline(0.55, '-', 'Label 1');
xl2 = xline(0.56, '--', sprintf(['$%s' repmat('\\ ',1,20), '$'],'Label\ \ 2'), 'Interpreter','latex');
xlim([0 1])

Each space needs to be written as a separate ‘escaped’ space, '\ \ \ ', for example, specifying 3 consecutive spaces.
That should work.
.
Daniel Rowe
2022년 2월 21일
Unfortunately, this does not work either. Instead, I receive a warning message:
Warning: Escaped character '\ ' is not valid. See 'doc sprintf' for supported special characters.
Star Strider
2022년 2월 21일
It works in my code, and throws no errors.
I have no idea what your code currently looks like, so I can’t offer any suggestions. Note that in the repmat call in my code, the backslants are themselves ‘escaped’ (as '\\ ') since that’s necessary to use them in sprintf.
Daniel Rowe
2022년 2월 23일
Works in isolation but I still can't get this to work in the code.
They have to be ‘escaped’ in the sprintf format string. They work without being ‘escaped’ in argument strings.
Using my approach in your posted code xline call, it appears to work —
i = 1;
corr_bar(i) = 0.5;
V_i{i} = 'Z';
pos_h{i} = 'right';
figure
xlim([0.4 0.6])
x = xline(corr_bar(i),':',sprintf(['$$%c' repmat('\\ ',1,30) '$$'],V_i{i}),'LabelHorizontalAlignment',pos_h{i},'LineWidth',.5,'Color','b','HandleVisibility','off','interpreter','latex'); %sprintf('%c = %0.2f',V_i{i},round(corr_bar(i)*100)/100')

The problem may be with whatever ‘V_1{i}’ is, since I could make it work with ASCII alphabet letters, although other symbols such as ‘#’ failed and threw an error. That could be due to those characters being unacceptable to the LaTeX interpreter. If so, I have no idea if a work-around exists, other than their being represented in the Interpreter symbols (that then would also have to have ‘escaped’ backslants). (I tried this with both ‘%c’ and ‘%s’.)
.
Daniel Rowe
2022년 2월 23일
Thanks again. This is the cell array in question:
V_i = {'u','v','w'};
Still won't work for me!
As always, my pleasure!
This seems to work —
corr_bar = 0.04:0.01:0.06;
V_i = {'u','v','w'};
figure
xlim([0.02 0.08])
for i = 1:3
pos_h{i} = 'right';
x = xline(corr_bar(i),':',sprintf(['$%c' repmat('\\ ',1,i*10) '$'],V_i{i}),'LabelHorizontalAlignment',pos_h{i},'LineWidth',.5,'Color','b','HandleVisibility','off','interpreter','latex'); %sprintf('%c = %0.2f',V_i{i},round(corr_bar(i)*100)/100')
x.FontSize = 16;
end

I also made the offset a function of ‘i’ so it varies automatically. (I added the 'FontSize' to make it easier to see.)
.
Daniel Rowe
2022년 2월 23일
Very nice!
Star Strider
2022년 2월 23일
Thank you!
Is it still not working correctly in your application?
Daniel Rowe
2022년 2월 23일
Works fine now, thankfully.
Star Strider
2022년 2월 23일
Great!
What was the problem? (Just curious.)
Daniel Rowe
2022년 2월 23일
It was those dollar signs either side of the repmat function, but I'm not entirely sure what they achieve to be honest.
The dollar signs tell the LaTeX interpreter to interpret everything between them. Without their being present, it won’t process anything and instead just ignore it and throw a Warning.
figure
text(0.2, 0.1, 'Text^2', 'Interpreter','latex')

Warning: Error updating Text.
String scalar or character vector must have valid interpreter syntax:
Text^2
String scalar or character vector must have valid interpreter syntax:
Text^2
figure
text(0.4, 0.1, '$Text^2$', 'Interpreter','latex')

.
Daniel Rowe
2022년 2월 23일
That is super useful information and explains why I couldn't itallicise any legends using sprintf. Thanks again!
Star Strider
2022년 2월 23일
As always, my pleasure!
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Creating, Deleting, and Querying Graphics Objects에 대해 자세히 알아보기
태그
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
