How to change the legend format to “Descriptive text + icon”
조회 수: 5 (최근 30일)
이전 댓글 표시
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!
댓글 수: 0
답변 (1개)
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)
fprintf('legend() has %d children objects.\n', numel(hLegend.Children));
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
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 Center 및 File Exchange에서 Legend에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!