How to change the legend format to “Descriptive text + icon”

조회 수: 5 (최근 30일)
dongxu yu
dongxu yu 2025년 4월 6일
댓글: Walter Roberson 2025년 4월 6일
I’m currently using MATLAB 2024b. By default, the legend items are displayed in the order of “icon+ Descriptive text”. I want to change it to “Descriptive text + icon”.
Here is the code provided by an AI, but it doesn’t seem to work.
x = 1:10;
y1 = x;
y2 = x.^2;
plot(x, y1, 'ro', x, y2, 'b--');
hLegend = legend('y = x', 'y = x^2');
legendTexts = findobj(hLegend, 'Type', 'text');
legendIcons = findobj(hLegend, 'Type', 'patch');
numEntries = length(legendTexts);
for i = 1:numEntries
textPosition = get(legendTexts(i), 'Position');
iconPosition = get(legendIcons(i), 'Position');
newTextX = iconPosition(1);
newIconX = textPosition(1);
set(legendTexts(i), 'Position', [newTextX, textPosition(2), textPosition(3)]);
set(legendIcons(i), 'Position', [newIconX, iconPosition(2), iconPosition(3)]);
end
Thank you in advance for your help!

답변 (1개)

Image Analyst
Image Analyst 2025년 4월 6일
That's because legend() does not have any children, much less of types text and patch:
x = 1:10;
y1 = x;
y2 = x.^2;
plot(x, y1, 'ro', x, y2, 'b--');
hLegend = legend('y = x', 'y = x^2');
legendObjs = findobj(hLegend)
legendObjs =
Legend (y = x, y = x^2) with properties: String: {'y = x' 'y = x^2'} Location: 'northeast' Orientation: 'vertical' FontSize: 9 Position: [0.7259 0.8110 0.1607 0.0881] Units: 'normalized' Use GET to show all properties
fprintf('legend() has %d children objects.\n', numel(hLegend.Children));
legend() has 0 children objects.
And there is no option in legend to swap the positions of the text and the line/marker. You're basically either going to have to live with it, or build it yourself by editing legends.m.
If you do the latter, make sure you make a copy of legends.m in your own folder and then edit that one, not the built-in one.
builtInPath = 'C:\Program Files\MATLAB\R2024b\toolbox\matlab\graphics\graphics\scribe\legend.m';
copyfile(builtInPath, 'myLegend.m');
edit 'myLegend.m'
  댓글 수: 2
dongxu yu
dongxu yu 2025년 4월 6일
Thank you for your reply. I will just manually add a text box in the figure window to make the change.
Walter Roberson
Walter Roberson 2025년 4월 6일
It is possible to get it to work by using the undocumented second output of legend() and fudging the Position and XData properties of the resulting exposed icons. But it is a nuisance to get right; for example you need to use the Extent property of the text objects to figure out the size of the text in order to be able to place the icon after the text. Or, I suppose, the size of the legend box could be used and some subtraction...

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by